问:
SQL Select where values in List<string>
Is there a way that I can create query against a data source (could be sql, oracle or access) that has a where clause that points to an ArrayList or List?

example:

```<code>Select * from Table where RecordID in (RecordIDList)
</code>```

I've seen some ways to do it with Linq, but I'd rather not resort to it if it's avoidable.

答:
Linq to Sql.  RecordList should be a List<T>, not an ArrayList or an IList<T>

```<code>IEnumerable<TableRow> query =
  from t in db.Table
  where RecordList.Any(r => t.RecordId == r)
  select t;
</code>```

This will generate sql with parameters:

```<code>SELECT *
FROM Table
WHERE RecordId in (@p0, @p1, @p2, @p3, @p4)
</code>```

Linq will generate as many parameters as are needed.  Some database implementations are limited in the number of parameters that can be accepted.  SqlServer2005's limit is a little over 2000 parameters... so don't use a list with more than 2000 elements.

OwnerDisplayName: JoelHess

ContentLicense: CC BY-SA 2.5

Title: SQL Select where values in List<string>

Body:
Is there a way that I can create query against a data source (could be sql, oracle or access) that has a where clause that points to an ArrayList or List?

example:

Select * from Table where RecordID in (RecordIDList)

I've seen some ways to do it with Linq, but I'd rather not resort to it if it's avoidable.

LastEditorDisplayName: Andrew Hare

Body:
Linq to Sql.  RecordList should be a List<T>, not an ArrayList or an IList<T>

IEnumerable<TableRow> query =
  from t in db.Table
  where RecordList.Any(r => t.RecordId == r)
  select t;

This will generate sql with parameters:

SELECT *
FROM Table
WHERE RecordId in (@p0, @p1, @p2, @p3, @p4)

Linq will generate as many parameters as are needed.  Some database implementations are limited in the number of parameters that can be accepted.  SqlServer2005's limit is a little over 2000 parameters... so don't use a list with more than 2000 elements.

OwnerDisplayName: David B


来源: stackexchange

问:
are there any memory leaks in this code?
I have successfully created a UITableView/UITableViewCell that is able to slide up and down and adjusting the height to show options. To see what this means, I have created a video here. The code is as follows:

```<code>- (void)swipe:(UISwipeGestureRecognizer *)recognizer direction:(UISwipeGestureRecognizerDirection)direction
{
    if (recognizer && recognizer.state == UIGestureRecognizerStateEnded)
    {
        // Get the table view cell where the swipe occured
        CGPoint location = [recognizer locationInView:self.tableView];
        NSIndexPath* indexPath = [self.tableView indexPathForRowAtPoint:location];
        MyCell* cell = (MyCell *) [self.tableView cellForRowAtIndexPath:indexPath];

        [self.tableView beginUpdates];

        //removing the options view at the other cell before adding a new one

        if (global != nil && global.row != indexPath.row){
            [sideSwipeView removeFromSuperview];
            sideSwipeView = nil;
        }

        //options already exist, we need to remove it
        if (sideSwipeView != nil){
            [sideSwipeView removeFromSuperview];
            sideSwipeView = nil;
            slide = NO;
        } else {
            //options do not exist and therefore we need to add it
            NSArray * buttonData = [[NSArray arrayWithObjects:
                                     [NSDictionary dictionaryWithObjectsAndKeys:@"Mark Read", @"title", @"mark.png", @"image", nil],
                                     [NSDictionary dictionaryWithObjectsAndKeys:@"Track", @"title", @"play.png", @"image", nil],
                                     nil] retain];

            NSMutableArray * buttons = [[NSMutableArray alloc] initWithCapacity:buttonData.count];
            sideSwipeView = [[UIView alloc] initWithFrame:CGRectMake(0, cell.frame.size.height-25, 320, 25)];
            [sideSwipeView setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin];
            [sideSwipeView setBackgroundColor:[UIColor colorWithPatternImage: [UIImage imageNamed:@"dotted-pattern.png"]]];
            [sideSwipeView setTag:-10];

            CGFloat leftEdge = BUTTON_LEFT_MARGIN;
            for (NSDictionary* buttonInfo in buttonData)
            {
                if (!([[buttonInfo objectForKey:@"title"] isEqualToString:@"Mark Read"] && [[[topics objectAtIndex:indexPath.row] unread] intValue] == 0))
                {

                    UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];

                    button.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin;

                    UIImage* buttonImage = [UIImage imageNamed:[buttonInfo objectForKey:@"image"]];
                    if ([[topics objectAtIndex:indexPath.row] tracked] && [[buttonInfo objectForKey:@"title"] isEqualToString:@"Track"]){
                        buttonImage = [UIImage imageNamed:@"pause.png"];
                        [button setSelected:YES];
                    } else {
                        [button setSelected:NO];
                    }
                    button.frame = CGRectMake(leftEdge, 0, buttonImage.size.width, buttonImage.size.height);

                    UIImage* grayImage = [self imageFilledWith:[UIColor colorWithWhite:0.9 alpha:1.0] using:buttonImage];
                    [button setImage:grayImage forState:UIControlStateNormal];

                    if ([[buttonInfo objectForKey:@"title"] isEqualToString:@"Mark Read"]){
                        [button addTarget:self action:@selector(markRead:) forControlEvents:UIControlEventTouchUpInside];
                    } else if ([[buttonInfo objectForKey:@"title"] isEqualToString:@"Track"]){
                        [button addTarget:self action:@selector(track:) forControlEvents:UIControlEventTouchUpInside];
                    }
                    [button setTag:indexPath.row];
                    [buttons addObject:button];

                    [sideSwipeView addSubview:button];

                    leftEdge = leftEdge + buttonImage.size.width + BUTTON_SPACING;
                }
            }

            [cell.contentView addSubview:sideSwipeView];
            [sideSwipeView release];
            global = indexPath;
            slide = YES;

        }
        [self.tableView endUpdates];
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];

    }
}
</code>```

However, I am not confident that the code is memory correct (i.e: ther's no memory leak and I am not misusing anything). I am mostly not confident in the sideSwipeView alloc, dealloc, and setting it up to nil. I think the others are fine. Can someone give me any pointers?

Profiler result:

答:
```<code>NSMutableArray * buttons = [[NSMutableArray alloc] initWithCapacity:buttonData.count];
</code>```

seems like you have not released, the space you have allocated in it, this may cause leak,
use,

```<code>[button release];
button=nil;
</code>```

I think, you should check and make sure that you have released  button in following scope:

```<code>else{
        //options do not exist and therefore we need to add it
        NSArray * buttonData = [[NSArray arrayWithObjects:
                                 [NSDictionary dictionaryWithObjectsAndKeys:@"Mark Read", @"title", @"mark.png", @"image", nil],
                                 [NSDictionary dictionaryWithObjectsAndKeys:@"Track", @"title", @"play.png", @"image", nil],
                                 nil] retain];

        NSMutableArray * buttons = [[NSMutableArray alloc] initWithCapacity:buttonData.count];
        sideSwipeView = [[UIView alloc] initWithFrame:CGRectMake(0, cell.frame.size.height-25, 320, 25)];
        [sideSwipeView setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin];
        [sideSwipeView setBackgroundColor:[UIColor colorWithPatternImage: [UIImage imageNamed:@"dotted-pattern.png"]]];
        [sideSwipeView setTag:-10];

        CGFloat leftEdge = BUTTON_LEFT_MARGIN;
        for (NSDictionary* buttonInfo in buttonData)
        {
            if (!([[buttonInfo objectForKey:@"title"] isEqualToString:@"Mark Read"] && [[[topics objectAtIndex:indexPath.row] unread] intValue] == 0))
            {

                UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];

                button.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin;

                UIImage* buttonImage = [UIImage imageNamed:[buttonInfo objectForKey:@"image"]];
                if ([[topics objectAtIndex:indexPath.row] tracked] && [[buttonInfo objectForKey:@"title"] isEqualToString:@"Track"]){
                    buttonImage = [UIImage imageNamed:@"pause.png"];
                    [button setSelected:YES];
                } else {
                    [button setSelected:NO];
                }
                button.frame = CGRectMake(leftEdge, 0, buttonImage.size.width, buttonImage.size.height);

                UIImage* grayImage = [self imageFilledWith:[UIColor colorWithWhite:0.9 alpha:1.0] using:buttonImage];
                [button setImage:grayImage forState:UIControlStateNormal];

                if ([[buttonInfo objectForKey:@"title"] isEqualToString:@"Mark Read"]){
                    [button addTarget:self action:@selector(markRead:) forControlEvents:UIControlEventTouchUpInside];
                } else if ([[buttonInfo objectForKey:@"title"] isEqualToString:@"Track"]){
                    [button addTarget:self action:@selector(track:) forControlEvents:UIControlEventTouchUpInside];
                }
                [button setTag:indexPath.row];
                [buttons addObject:button];

                [sideSwipeView addSubview:button];

                leftEdge = leftEdge + buttonImage.size.width + BUTTON_SPACING;
            }
        }

        [cell.contentView addSubview:sideSwipeView];
        [sideSwipeView release];
        global = indexPath;
        slide = YES;

    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have successfully created a UITableView/UITableViewCell that is able to slide up and down and adjusting the height to show options. To see what this means, I have created a video here. The code is as follows:

- (void)swipe:(UISwipeGestureRecognizer *)recognizer direction:(UISwipeGestureRecognizerDirection)direction
{
    if (recognizer && recognizer.state == UIGestureRecognizerStateEnded)
    {
        // Get the table view cell where the swipe occured
        CGPoint location = [recognizer locationInView:self.tableView];
        NSIndexPath* indexPath = [self.tableView indexPathForRowAtPoint:location];
        MyCell* cell = (MyCell *) [self.tableView cellForRowAtIndexPath:indexPath];

        [self.tableView beginUpdates];

        //removing the options view at the other cell before adding a new one

        if (global != nil && global.row != indexPath.row){
            [sideSwipeView removeFromSuperview];
            sideSwipeView = nil;
        }

        //options already exist, we need to remove it
        if (sideSwipeView != nil){
            [sideSwipeView removeFromSuperview];
            sideSwipeView = nil;
            slide = NO;
        } else {
            //options do not exist and therefore we need to add it
            NSArray * buttonData = [[NSArray arrayWithObjects:
                                     [NSDictionary dictionaryWithObjectsAndKeys:@"Mark Read", @"title", @"mark.png", @"image", nil],
                                     [NSDictionary dictionaryWithObjectsAndKeys:@"Track", @"title", @"play.png", @"image", nil],
                                     nil] retain];

            NSMutableArray * buttons = [[NSMutableArray alloc] initWithCapacity:buttonData.count];
            sideSwipeView = [[UIView alloc] initWithFrame:CGRectMake(0, cell.frame.size.height-25, 320, 25)];
            [sideSwipeView setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin];
            [sideSwipeView setBackgroundColor:[UIColor colorWithPatternImage: [UIImage imageNamed:@"dotted-pattern.png"]]];
            [sideSwipeView setTag:-10];

            CGFloat leftEdge = BUTTON_LEFT_MARGIN;
            for (NSDictionary* buttonInfo in buttonData)
            {
                if (!([[buttonInfo objectForKey:@"title"] isEqualToString:@"Mark Read"] && [[[topics objectAtIndex:indexPath.row] unread] intValue] == 0))
                {

                    UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];

                    button.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin;

                    UIImage* buttonImage = [UIImage imageNamed:[buttonInfo objectForKey:@"image"]];
                    if ([[topics objectAtIndex:indexPath.row] tracked] && [[buttonInfo objectForKey:@"title"] isEqualToString:@"Track"]){
                        buttonImage = [UIImage imageNamed:@"pause.png"];
                        [button setSelected:YES];
                    } else {
                        [button setSelected:NO];
                    }
                    button.frame = CGRectMake(leftEdge, 0, buttonImage.size.width, buttonImage.size.height);

                    UIImage* grayImage = [self imageFilledWith:[UIColor colorWithWhite:0.9 alpha:1.0] using:buttonImage];
                    [button setImage:grayImage forState:UIControlStateNormal];

                    if ([[buttonInfo objectForKey:@"title"] isEqualToString:@"Mark Read"]){
                        [button addTarget:self action:@selector(markRead:) forControlEvents:UIControlEventTouchUpInside];
                    } else if ([[buttonInfo objectForKey:@"title"] isEqualToString:@"Track"]){
                        [button addTarget:self action:@selector(track:) forControlEvents:UIControlEventTouchUpInside];
                    }
                    [button setTag:indexPath.row];
                    [buttons addObject:button];

                    [sideSwipeView addSubview:button];

                    leftEdge = leftEdge + buttonImage.size.width + BUTTON_SPACING;
                }
            }

            [cell.contentView addSubview:sideSwipeView];
            [sideSwipeView release];
            global = indexPath;
            slide = YES;

        }
        [self.tableView endUpdates];
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];

    }
}

However, I am not confident that the code is memory correct (i.e: ther's no memory leak and I am not misusing anything). I am mostly not confident in the sideSwipeView alloc, dealloc, and setting it up to nil. I think the others are fine. Can someone give me any pointers?

Profiler result:

Body:
NSMutableArray * buttons = [[NSMutableArray alloc] initWithCapacity:buttonData.count];

seems like you have not released, the space you have allocated in it, this may cause leak,
use,

[button release];
button=nil;

I think, you should check and make sure that you have released  button in following scope:

else{
        //options do not exist and therefore we need to add it
        NSArray * buttonData = [[NSArray arrayWithObjects:
                                 [NSDictionary dictionaryWithObjectsAndKeys:@"Mark Read", @"title", @"mark.png", @"image", nil],
                                 [NSDictionary dictionaryWithObjectsAndKeys:@"Track", @"title", @"play.png", @"image", nil],
                                 nil] retain];

        NSMutableArray * buttons = [[NSMutableArray alloc] initWithCapacity:buttonData.count];
        sideSwipeView = [[UIView alloc] initWithFrame:CGRectMake(0, cell.frame.size.height-25, 320, 25)];
        [sideSwipeView setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin];
        [sideSwipeView setBackgroundColor:[UIColor colorWithPatternImage: [UIImage imageNamed:@"dotted-pattern.png"]]];
        [sideSwipeView setTag:-10];

        CGFloat leftEdge = BUTTON_LEFT_MARGIN;
        for (NSDictionary* buttonInfo in buttonData)
        {
            if (!([[buttonInfo objectForKey:@"title"] isEqualToString:@"Mark Read"] && [[[topics objectAtIndex:indexPath.row] unread] intValue] == 0))
            {

                UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];

                button.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin;

                UIImage* buttonImage = [UIImage imageNamed:[buttonInfo objectForKey:@"image"]];
                if ([[topics objectAtIndex:indexPath.row] tracked] && [[buttonInfo objectForKey:@"title"] isEqualToString:@"Track"]){
                    buttonImage = [UIImage imageNamed:@"pause.png"];
                    [button setSelected:YES];
                } else {
                    [button setSelected:NO];
                }
                button.frame = CGRectMake(leftEdge, 0, buttonImage.size.width, buttonImage.size.height);

                UIImage* grayImage = [self imageFilledWith:[UIColor colorWithWhite:0.9 alpha:1.0] using:buttonImage];
                [button setImage:grayImage forState:UIControlStateNormal];

                if ([[buttonInfo objectForKey:@"title"] isEqualToString:@"Mark Read"]){
                    [button addTarget:self action:@selector(markRead:) forControlEvents:UIControlEventTouchUpInside];
                } else if ([[buttonInfo objectForKey:@"title"] isEqualToString:@"Track"]){
                    [button addTarget:self action:@selector(track:) forControlEvents:UIControlEventTouchUpInside];
                }
                [button setTag:indexPath.row];
                [buttons addObject:button];

                [sideSwipeView addSubview:button];

                leftEdge = leftEdge + buttonImage.size.width + BUTTON_SPACING;
            }
        }

        [cell.contentView addSubview:sideSwipeView];
        [sideSwipeView release];
        global = indexPath;
        slide = YES;

    }


问:
How to get db data back via repository service with MVC and Moq
I need to retrieve data from the db, via a service, in order to test captured data for structural validity.
i.e. The db data specifies the sizes of parts of a captured concatenated string, (in a certain order), which I mock.  So no worries there.

But I don't want to mock the service's data.

I want to actually retrieve the db data, which can change/vary vastly for different clients, and different scenarios, or be changed regularly.

 So, changing the mocked data for each scenario is not feasible.

The Service implements an interface and also injects the Data Access Layer's interface.

I do set 'CallBase' as true, but I'm not getting db Data back.
Please help.
Thanks

```<code>public interface I_PartDao
{
    ExBool List(out List<GXL_PartSizes> _PartSizes);
}

public class GXL_PartSizes
    {
        public int? ID { get; set; }
        public int? PartLength { get; set; }
        public int? SortOrder { get; set; }

        public  GXL_PartSizes()
        {
            this.ID = null;
            this.PartLength = null;
            this.SortOrder = null;
        }
    }

// Service Layer
public interface I_PartBo
{
    ExBool List(out List<GXL_PartSizes> _PartSizes);
}

public class PartBo : I_PartBo
{
    // For the injection of the Dao services (Dao handles the Ado CRUD operations against MSSQL dbase)
    private I_PartDao PartDao;

    public PartBo(I_PartDao dao_Part)
    {
        this.PartDao = dao_Part ?? throw new ArgumentNullException("dao_Part");
    }

    public ExBool List(out List<GXL_PartSizes> _PartSizes)
    {
        return this.PartDao.List(out _PartSizes);
    }
}

[TestClass]
public class GXL_ConcatenatedStructures_Test
{
    ExBool result = new ExBool();   // A class to handle error messages and statuses
    private List<GXL_PartSizes> partSizes;

    [TestMethod]
    public void Test_Part_1_Length_matches_dbStructure_for_part1()
    {
        // Arrange
        var mockService = new Mock<I_PartBo>();

        // This is retrieved from the data posted back to the controller,..but for here and now, just a local populated strign var
        var concatenatedString_part1 = "ABC";

        // Act
        //mockService.CallBase = true;

        mockService
            .Setup(x => x.List(out partSizes))
            .Returns(result);

        //  Assert
        Assert.AreEqual(concatenatedString_part1, partSizes[0].PartLength);
    }
}
</code>```

答:
I thought that there was a way to do what I wanted to, by using moq.

However,
by just using the normal concrete classes, as per the usual (sans DI) way, The db data is retrieved.
i.e.

```<code>NamespaceX.GLX_SetupDao dao = new NamespaceX.GLXSetupDao("data source=LAPTOP-a; Initial
                                                          Catalog=aaaa; Integrated Security=True;");
GLX_SetupBo boService = new GLX_SetupBo(dao);
result = boService.List(out List<GXL_PartSizes> sizes);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to retrieve data from the db, via a service, in order to test captured data for structural validity.
i.e. The db data specifies the sizes of parts of a captured concatenated string, (in a certain order), which I mock.  So no worries there.

But I don't want to mock the service's data.

I want to actually retrieve the db data, which can change/vary vastly for different clients, and different scenarios, or be changed regularly.

 So, changing the mocked data for each scenario is not feasible.

The Service implements an interface and also injects the Data Access Layer's interface.

I do set 'CallBase' as true, but I'm not getting db Data back.
Please help.
Thanks

public interface I_PartDao
{
    ExBool List(out List<GXL_PartSizes> _PartSizes);
}

public class GXL_PartSizes
    {
        public int? ID { get; set; }
        public int? PartLength { get; set; }
        public int? SortOrder { get; set; }

        public  GXL_PartSizes()
        {
            this.ID = null;
            this.PartLength = null;
            this.SortOrder = null;
        }
    }

// Service Layer
public interface I_PartBo
{
    ExBool List(out List<GXL_PartSizes> _PartSizes);
}

public class PartBo : I_PartBo
{
    // For the injection of the Dao services (Dao handles the Ado CRUD operations against MSSQL dbase)
    private I_PartDao PartDao;

    public PartBo(I_PartDao dao_Part)
    {
        this.PartDao = dao_Part ?? throw new ArgumentNullException("dao_Part");
    }

    public ExBool List(out List<GXL_PartSizes> _PartSizes)
    {
        return this.PartDao.List(out _PartSizes);
    }
}

[TestClass]
public class GXL_ConcatenatedStructures_Test
{
    ExBool result = new ExBool();   // A class to handle error messages and statuses
    private List<GXL_PartSizes> partSizes;

    [TestMethod]
    public void Test_Part_1_Length_matches_dbStructure_for_part1()
    {
        // Arrange
        var mockService = new Mock<I_PartBo>();

        // This is retrieved from the data posted back to the controller,..but for here and now, just a local populated strign var
        var concatenatedString_part1 = "ABC";

        // Act
        //mockService.CallBase = true;

        mockService
            .Setup(x => x.List(out partSizes))
            .Returns(result);

        //  Assert
        Assert.AreEqual(concatenatedString_part1, partSizes[0].PartLength);
    }
}

Body:
I thought that there was a way to do what I wanted to, by using moq.

However,
by just using the normal concrete classes, as per the usual (sans DI) way, The db data is retrieved.
i.e.

NamespaceX.GLX_SetupDao dao = new NamespaceX.GLXSetupDao("data source=LAPTOP-a; Initial
                                                          Catalog=aaaa; Integrated Security=True;");
GLX_SetupBo boService = new GLX_SetupBo(dao);
result = boService.List(out List<GXL_PartSizes> sizes);


问:
How can I create a computed array in Vue and then render it using v-if all while using v-model on the computed array?
I've been trying to create a computed array which I then render using v-if. But it also needs to work with v-model. The reason it needs v-model is because it's part of a draggable list using vuedraggable.

Currently I get the following error Computed property "list" was assigned to but it has no setter.

The following code is my drag.vue component:

```<code><template>
  <div>
    <draggable
      v-model="list"
      v-bind="dragOptions"
      class="bigger-area"
      @start="isDragging=true"
      @end="isDragging=false"
    >
      <transition-group name="flip-list" type="transition">
        <li
          v-for="text in list"
          :key="text"
          id="list1"
          class="drag-item flex flex-justify-betweeen"
        >{{ text }}</li>
      </transition-group>
    </draggable>
  </div>
</template>

<script>
import draggable from "vuedraggable";

export default {
  name: "Drag",
  data() {
    return {
      test: [],
      lists: [
        {
          title: "0-6 months",
          correctlyOrderedList: [
            "Lifting Head",
            "Rolling",
            "Sitting (with support)"
          ]
        },
        {
          title: "6-12 months",
          correctlyOrderedList: [
            "Crawling on stomach",
            "Sitting (without support)",
            "Stands with support and walks holding on",
            "Rolls a ball"
          ]
        },
        {
          title: "12-18 months",
          correctlyOrderedList: ["Crawling", "Walks alone"]
        },
        {
          title: "18 months – 2 years",
          correctlyOrderedList: [
            "Walks smoothly and turns corners",
            "Walks upstairs with support",
            "Begins running"
          ]
        },
        {
          title: "2-3 years",
          correctlyOrderedList: [
            "Walks upstairs without support",
            "Runs safely",
            "Catches using body and arms"
          ]
        },
        {
          title: "3-4 years",
          correctlyOrderedList: ["Kicks a ball forwards", "Can hop on one foot"]
        },
        {
          title: "4-5 years",
          correctlyOrderedList: [
            "Catches using only their hands",
            "Can skip following a demonstration"
          ]
        }
      ]
    };
  },
  components: {
    draggable
  },
  methods: {
    fullArrayMethod() {
      //Puts all statements into single array
      let i;
      let v;
      let fullArrayInOrder = [];
      for (i = 0; i < this.lists.length; i++) {
        for (v = 0; v < this.lists[i].correctlyOrderedList.length; v++) {
          fullArrayInOrder.push(this.lists[i].correctlyOrderedList[v]);
        }
      }
      return fullArrayInOrder;
    },
    disorderedArrayMethod() {
      //Randomizes array
      let fullArrayInOrder = this.fullArrayMethod();
      var copy = [],
        n = fullArrayInOrder.length,
        i;
      // While there remain elements to shuffle…
      while (n) {
        // Pick a remaining element…
        i = Math.floor(Math.random() * fullArrayInOrder.length);

        // If not already shuffled, move it to the new array.
        if (i in fullArrayInOrder) {
          copy.push(fullArrayInOrder[i]);
          delete fullArrayInOrder[i];
          n--;
        }
      }
      return copy;
    },
    chunk(array, size) {
      const chunked_arr = [];
      let index = 0;
      while (index < array.length) {
        chunked_arr.push(array.slice(index, size + index));
        index += size;
      }
      return chunked_arr;
    },
    splitArrayFinalProduct() {
      let disorderedArray = this.disorderedArrayMethod();
      let finalArray = this.chunk(disorderedArray, 3);
      return finalArray;
    }
  },
  computed: {
    dragOptions() {
      return {
        animation: 0,
        group: "shared",
        disabled: false,
        ghostClass: "ghost"
      };
    },
    list() {
      return this.disorderedArrayMethod();
    }
  }
};
</script>
</code>```

Context: I'm trying to create an application which consolidates multiple arrays into one. Randomises the array. The user can then put it back in order and then see if they got it right.

答:
For anyone who may find it useful this is what worked for me. I can't explain the in's and outs of why it works so hopefully somebody smarter than me can elaborate.

To get the computed array variable to work with v-model and v-for I used map() as shown below:

```<code>let completeListOfStatements = this.lists.map(
d => d.correctlyOrderedList
);
</code>```

My understanding of map() is it returns an array.

Then in the v-model I set it to the array that is within the object. This is the same one that I used map() on. This can be seen below.

```<code><draggable
   v-model="lists.correctlyOrderedList"
   v-bind="dragOptions"
   class="list-group"
   @start="isDragging=true"
   @end="isDragging=false"
>
</code>```

For comparisons to the code in my question here's all the code from the component:

```<code><template>
  <div class="draggable-list-container">
    <div
      class="draggable-list-inner-container"
      v-for="(statement, index) in splitCompleteListOfStatements"
      :key="index"
    >
      <h1>{{ lists[index].title }}</h1>
      <draggable
        v-model="lists.correctlyOrderedList"
        v-bind="dragOptions"
        class="list-group"
        @start="isDragging=true"
        @end="isDragging=false"
      >
        <transition-group name="flip-list" type="transition">
          <li
            v-for="(statement, index) in statement"
            :key="index + 'index'"
            class="drag-item flex flex-justify-betweeen"
          >{{ statement }}</li>
        </transition-group>
      </draggable>
    </div>
    <div class="submit-button-container">
      <button class="btn" @click="revealAnswers">Reveal answers</button>
    </div>
  </div>
</template>

<script>
import draggable from "vuedraggable";

export default {
  name: "Drag",
  data() {
    return {
      lists: [
        {
          title: "0-6 months",
          correctlyOrderedList: [
            "Lifting Head",
            "Rolling",
            "Sitting (with support)"
          ]
        },
        {
          title: "6-12 months",
          correctlyOrderedList: [
            "Crawling on stomach",
            "Sitting (without support)",
            "Stands with support and walks holding on",
            "Rolls a ball"
          ]
        },
        {
          title: "12-18 months",
          correctlyOrderedList: ["Crawling", "Walks alone"]
        },
        {
          title: "18 months – 2 years",
          correctlyOrderedList: [
            "Walks smoothly and turns corners",
            "Walks upstairs with support",
            "Begins running"
          ]
        },
        {
          title: "2-3 years",
          correctlyOrderedList: [
            "Walks upstairs without support",
            "Runs safely",
            "Catches using body and arms"
          ]
        },
        {
          title: "3-4 years",
          correctlyOrderedList: ["Kicks a ball forwards", "Can hop on one foot"]
        },
        {
          title: "4-5 years",
          correctlyOrderedList: [
            "Catches using only their hands",
            "Can skip following a demonstration"
          ]
        }
      ]
    };
  },
  components: {
    draggable
  },
  methods: {
    disorderedArrayMethod(value) {
      //Randomizes array
      let fullArrayInOrder = value;
      var copy = [],
        n = fullArrayInOrder.length,
        i;
      // While there remain elements to shuffle…
      while (n) {
        // Pick a remaining element…
        i = Math.floor(Math.random() * fullArrayInOrder.length);

        // If not already shuffled, move it to the new array.
        if (i in fullArrayInOrder) {
          copy.push(fullArrayInOrder[i]);
          delete fullArrayInOrder[i];
          n--;
        }
      }
      return copy;
    },
    revealAnswers() {this.splitCompleteListOfStatements[0].push("Hello")}
  },
  computed: {
    dragOptions() {
      return {
        animation: 0,
        group: "shared",
        disabled: false,
        ghostClass: "ghost"
      };
    },
    splitCompleteListOfStatements() {
      let completeListOfStatements = this.lists.map(
        //Maps out full array (Basically loops through gathers the arrays and creates an array from them)
        d => d.correctlyOrderedList
      );
      completeListOfStatements = completeListOfStatements.reduce(function(
        //The map returns an array as the following [[a,b], [], []] etc. So this turns it into [a,b,c,d]
        a,
        b
      ) {
        return a.concat(b);
      }, []);
      completeListOfStatements = this.disorderedArrayMethod(
        completeListOfStatements
      ); //This sends it to a method that jumbles the array

      var temp = [];
      var preVal = 0;
      var nextVal = 3;
      for (var i = 0; i < 7; i++) {
        temp.push(completeListOfStatements.slice(preVal, nextVal));
        preVal = nextVal;
        nextVal = nextVal + 3;
      }
      return temp;
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.title {
  margin-bottom: 0.5em;
}
.submit-button-container {
  margin-top: 5px;
}
.btn {
  width: 10em;
  height: 5em;
}
.draggable-list-container {
  display: inline-block;
  justify-content: center;
  min-height: 200px;
}
.list-group {
  min-height: 80px;
}
.drag-item {
  justify-content: center;
  padding: 15px 10px;
  background-color: whitesmoke;
  border: 1px solid black;
  width: 20em;
  margin: 2px;
  cursor: move;
}
.list-group-item {
  position: relative;
  display: block;
  padding: 0.75rem 1.25rem;
  margin-bottom: -1px;
  background-color: #fff;
  border: 1px solid rgba(0, 0, 0, 0.125);
}
.flip-list-move {
  transition: transform 0.5s;
}
.no-move {
  transition: transform 0s;
}
.ghost {
  opacity: 0.5;
  background: #c8ebfb;
}
.list-group-item {
  cursor: move;
}
</style>
</code>```

Body:
I've been trying to create a computed array which I then render using v-if. But it also needs to work with v-model. The reason it needs v-model is because it's part of a draggable list using vuedraggable.

Currently I get the following error Computed property "list" was assigned to but it has no setter.

The following code is my drag.vue component:

<template>

    <draggable
      v-model="list"
      v-bind="dragOptions"
      class="bigger-area"
      @start="isDragging=true"
      @end="isDragging=false"
    >
      <transition-group name="flip-list" type="transition">

{{ text }}

      </transition-group>
    </draggable>

</template>

Context: I'm trying to create an application which consolidates multiple arrays into one. Randomises the array. The user can then put it back in order and then see if they got it right.

Body:
For anyone who may find it useful this is what worked for me. I can't explain the in's and outs of why it works so hopefully somebody smarter than me can elaborate.

To get the computed array variable to work with v-model and v-for I used map() as shown below:

let completeListOfStatements = this.lists.map(
d => d.correctlyOrderedList
);

My understanding of map() is it returns an array.

Then in the v-model I set it to the array that is within the object. This is the same one that I used map() on. This can be seen below.

<draggable
   v-model="lists.correctlyOrderedList"
   v-bind="dragOptions"
   class="list-group"
   @start="isDragging=true"
   @end="isDragging=false"
>

For comparisons to the code in my question here's all the code from the component:

<template>
  <div class="draggable-list-container">
    <div
      class="draggable-list-inner-container"
      v-for="(statement, index) in splitCompleteListOfStatements"
      :key="index"
    >
      <h1>{{ lists[index].title }}</h1>
      <draggable
        v-model="lists.correctlyOrderedList"
        v-bind="dragOptions"
        class="list-group"
        @start="isDragging=true"
        @end="isDragging=false"
      >
        <transition-group name="flip-list" type="transition">
          <li
            v-for="(statement, index) in statement"
            :key="index + 'index'"
            class="drag-item flex flex-justify-betweeen"
          >{{ statement }}</li>
        </transition-group>
      </draggable>
    </div>
    <div class="submit-button-container">
      <button class="btn" @click="revealAnswers">Reveal answers</button>
    </div>
  </div>
</template>

<script>
import draggable from "vuedraggable";

export default {
  name: "Drag",
  data() {
    return {
      lists: [
        {
          title: "0-6 months",
          correctlyOrderedList: [
            "Lifting Head",
            "Rolling",
            "Sitting (with support)"
          ]
        },
        {
          title: "6-12 months",
          correctlyOrderedList: [
            "Crawling on stomach",
            "Sitting (without support)",
            "Stands with support and walks holding on",
            "Rolls a ball"
          ]
        },
        {
          title: "12-18 months",
          correctlyOrderedList: ["Crawling", "Walks alone"]
        },
        {
          title: "18 months – 2 years",
          correctlyOrderedList: [
            "Walks smoothly and turns corners",
            "Walks upstairs with support",
            "Begins running"
          ]
        },
        {
          title: "2-3 years",
          correctlyOrderedList: [
            "Walks upstairs without support",
            "Runs safely",
            "Catches using body and arms"
          ]
        },
        {
          title: "3-4 years",
          correctlyOrderedList: ["Kicks a ball forwards", "Can hop on one foot"]
        },
        {
          title: "4-5 years",
          correctlyOrderedList: [
            "Catches using only their hands",
            "Can skip following a demonstration"
          ]
        }
      ]
    };
  },
  components: {
    draggable
  },
  methods: {
    disorderedArrayMethod(value) {
      //Randomizes array
      let fullArrayInOrder = value;
      var copy = [],
        n = fullArrayInOrder.length,
        i;
      // While there remain elements to shuffle…
      while (n) {
        // Pick a remaining element…
        i = Math.floor(Math.random() * fullArrayInOrder.length);

        // If not already shuffled, move it to the new array.
        if (i in fullArrayInOrder) {
          copy.push(fullArrayInOrder[i]);
          delete fullArrayInOrder[i];
          n--;
        }
      }
      return copy;
    },
    revealAnswers() {this.splitCompleteListOfStatements[0].push("Hello")}
  },
  computed: {
    dragOptions() {
      return {
        animation: 0,
        group: "shared",
        disabled: false,
        ghostClass: "ghost"
      };
    },
    splitCompleteListOfStatements() {
      let completeListOfStatements = this.lists.map(
        //Maps out full array (Basically loops through gathers the arrays and creates an array from them)
        d => d.correctlyOrderedList
      );
      completeListOfStatements = completeListOfStatements.reduce(function(
        //The map returns an array as the following [[a,b], [], []] etc. So this turns it into [a,b,c,d]
        a,
        b
      ) {
        return a.concat(b);
      }, []);
      completeListOfStatements = this.disorderedArrayMethod(
        completeListOfStatements
      ); //This sends it to a method that jumbles the array

      var temp = [];
      var preVal = 0;
      var nextVal = 3;
      for (var i = 0; i < 7; i++) {
        temp.push(completeListOfStatements.slice(preVal, nextVal));
        preVal = nextVal;
        nextVal = nextVal + 3;
      }
      return temp;
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.title {
  margin-bottom: 0.5em;
}
.submit-button-container {
  margin-top: 5px;
}
.btn {
  width: 10em;
  height: 5em;
}
.draggable-list-container {
  display: inline-block;
  justify-content: center;
  min-height: 200px;
}
.list-group {
  min-height: 80px;
}
.drag-item {
  justify-content: center;
  padding: 15px 10px;
  background-color: whitesmoke;
  border: 1px solid black;
  width: 20em;
  margin: 2px;
  cursor: move;
}
.list-group-item {
  position: relative;
  display: block;
  padding: 0.75rem 1.25rem;
  margin-bottom: -1px;
  background-color: #fff;
  border: 1px solid rgba(0, 0, 0, 0.125);
}
.flip-list-move {
  transition: transform 0.5s;
}
.no-move {
  transition: transform 0s;
}
.ghost {
  opacity: 0.5;
  background: #c8ebfb;
}
.list-group-item {
  cursor: move;
}
</style>


问:
This works when HTML, JS and CSS are in one file but doesn't work when they are in different files
I'm creating an HTML, JS and CSS file, these files work together to create a subliminal test. This works when all the HTML, JS and CSS codes are in one file, but when I split them into separate files, and link them in HTML with

and

```<code><script src="filename.js"></script>
</code>```

It is not working.

You can find my code here: https://jsfiddle.net/2vasmch5/

function startTest(){

 var h = document.getElementById("bt");
 if (h.style.display === "none"){
  h.style.display = "block";
 } else {
  h.style.display = "none";
  }

var fourdigitsrandom  = Math.floor(1000 + Math.random() * 9000);

var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
var bgColor = "rgb(" + r + "," + g + "," + b + ")";

var rfd_rc = "rgb(" + (r-1) + "," + (g-1) + "," + (b-1) + ")";

document.querySelector('.rfd').style.color = rfd_rc;

function brColor() {
document.body.style.background = bgColor;
 }
brColor()
function rnColor() {
document.querySelector('.rfd').style.fontSize= "500%";
document.querySelector('.rfd').innerHTML=fourdigitsrandom;
 }
rnColor()

posChr();

const body = document.body;
const chr = document.querySelector('.rfd');
const prev = [0,0];

function posChr () {
  let x = Math.floor(Math.random() * body.offsetWidth);
  let y = Math.floor(Math.random() * body.offsetHeight);

  while (Math.sqrt((x - prev[0]) ** 2 + (y - prev[1]) ** 2) < 10) {
    x = Math.floor(Math.random() * body.offsetWidth);
   y = Math.floor(Math.random() * body.offsetHeight);
  }
  chr.style.left = `${x}px`;
  chr.style.top = `${y}px`;
  chr.textContent = fourdigitsrandom;
  prev[0] = x;
  prev[1] = y;

  setTimeout(posChr, 500);

}

setTimeout(posChr, 500)

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  height: 100vh;
}
.rfd {
  position: fixed;
}</code>```

<!DOCTYPE html>

<title>Subliminal Test</title>

Subliminal Test

<button id="bt" type="button" onclick="startTest();">Start Test</button>

```

(I made the JS code by gleaning other JS codes and some provided Stackoverflow users here)

What is the reason for this?

Also I'd like to know how can I run this JavaScript for two minutes and after that show a message like, test ended and provide users with multiple options to select one option from a five 4 digit random numbers. And when they select the chosen one, inform them that they have selected the chosen number.

答:
Please avoid using onclick="" in your html. It's a better practice to handle all events in the javascript file. So Remove that from your html:

onclick="startTest();"
```

<p>and add that in your <code>javascript</code>:</p>

<pre class="lang-js prettyprint-override"><code>document.getElementById("bt").addEventListener("click", startTest);
</code>```

Moreover you have a scope problem with yours variables body, chr and prev. You have to define them before the call of posChr().

You will get something like this:

document.getElementById("bt").addEventListener("click", startTest);

function startTest() {

  var h = document.getElementById("bt");
  if (h.style.display === "none") {
    h.style.display = "block";
  } else {
    h.style.display = "none";
  }

  var fourdigitsrandom = Math.floor(1000 + Math.random() * 9000);

  var r = Math.floor(Math.random() * 256);
  var g = Math.floor(Math.random() * 256);
  var b = Math.floor(Math.random() * 256);
  var bgColor = "rgb(" + r + "," + g + "," + b + ")";

  var rfd_rc = "rgb(" + (r - 1) + "," + (g - 1) + "," + (b - 1) + ")";

  document.querySelector('.rfd').style.color = rfd_rc;

  function brColor() {
    document.body.style.background = bgColor;
  }
  brColor()

  function rnColor() {
    document.querySelector('.rfd').style.fontSize = "500%";
    document.querySelector('.rfd').innerHTML = fourdigitsrandom;
  }
  rnColor()

  const body = document.body;
  const chr = document.querySelector('.rfd');
  const prev = [0, 0];

  posChr();

  function posChr() {
    let x = Math.floor(Math.random() * body.offsetWidth);
    let y = Math.floor(Math.random() * body.offsetHeight);

    while (Math.sqrt((x - prev[0]) ** 2 + (y - prev[1]) ** 2) < 10) {
      x = Math.floor(Math.random() * body.offsetWidth);
      y = Math.floor(Math.random() * body.offsetHeight);
    }
    chr.style.left = `${x}px`;
    chr.style.top = `${y}px`;
    chr.textContent = fourdigitsrandom;
    prev[0] = x;
    prev[1] = y;

    setTimeout(posChr, 500);

  }

  setTimeout(posChr, 500)

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  height: 100vh;
}

.rfd {
  position: fixed;
}</code>```

<!DOCTYPE html>

  <title>Subliminal Test</title>

Subliminal Test

  <button id="bt" type="button">Start Test</button>

```

Body:
I'm creating an HTML, JS and CSS file, these files work together to create a subliminal test. This works when all the HTML, JS and CSS codes are in one file, but when I split them into separate files, and link them in HTML with

and

It is not working.

You can find my code here: https://jsfiddle.net/2vasmch5/

function startTest(){

 var h = document.getElementById("bt");
 if (h.style.display === "none"){
  h.style.display = "block";
 } else {
  h.style.display = "none";
  }

var fourdigitsrandom  = Math.floor(1000 + Math.random() * 9000);

var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
var bgColor = "rgb(" + r + "," + g + "," + b + ")";

var rfd_rc = "rgb(" + (r-1) + "," + (g-1) + "," + (b-1) + ")";

document.querySelector('.rfd').style.color = rfd_rc;

function brColor() {
document.body.style.background = bgColor;
 }
brColor()
function rnColor() {
document.querySelector('.rfd').style.fontSize= "500%";
document.querySelector('.rfd').innerHTML=fourdigitsrandom;
 }
rnColor()

posChr();

const body = document.body;
const chr = document.querySelector('.rfd');
const prev = [0,0];

function posChr () {
  let x = Math.floor(Math.random() * body.offsetWidth);
  let y = Math.floor(Math.random() * body.offsetHeight);

  while (Math.sqrt((x - prev[0]) ** 2 + (y - prev[1]) ** 2) < 10) {
    x = Math.floor(Math.random() * body.offsetWidth);
   y = Math.floor(Math.random() * body.offsetHeight);
  }
  chr.style.left = `${x}px`;
  chr.style.top = `${y}px`;
  chr.textContent = fourdigitsrandom;
  prev[0] = x;
  prev[1] = y;

  setTimeout(posChr, 500);

}

setTimeout(posChr, 500)

}

body {
  height: 100vh;
}
.rfd {
  position: fixed;
}

<!DOCTYPE html>

<title>Subliminal Test</title>

Subliminal Test

<button id="bt" type="button" onclick="startTest();">Start Test</button>

(I made the JS code by gleaning other JS codes and some provided Stackoverflow users here)

What is the reason for this?

Also I'd like to know how can I run this JavaScript for two minutes and after that show a message like, test ended and provide users with multiple options to select one option from a five 4 digit random numbers. And when they select the chosen one, inform them that they have selected the chosen number.

Body:
Please avoid using onclick="" in your html. It's a better practice to handle all events in the javascript file. So Remove that from your html:

onclick="startTest();"

and add that in your javascript:

document.getElementById("bt").addEventListener("click", startTest);

Moreover you have a scope problem with yours variables body, chr and prev. You have to define them before the call of posChr().

You will get something like this:

document.getElementById("bt").addEventListener("click", startTest);

function startTest() {

  var h = document.getElementById("bt");
  if (h.style.display === "none") {
    h.style.display = "block";
  } else {
    h.style.display = "none";
  }

  var fourdigitsrandom = Math.floor(1000 + Math.random() * 9000);

  var r = Math.floor(Math.random() * 256);
  var g = Math.floor(Math.random() * 256);
  var b = Math.floor(Math.random() * 256);
  var bgColor = "rgb(" + r + "," + g + "," + b + ")";

  var rfd_rc = "rgb(" + (r - 1) + "," + (g - 1) + "," + (b - 1) + ")";

  document.querySelector('.rfd').style.color = rfd_rc;

  function brColor() {
    document.body.style.background = bgColor;
  }
  brColor()

  function rnColor() {
    document.querySelector('.rfd').style.fontSize = "500%";
    document.querySelector('.rfd').innerHTML = fourdigitsrandom;
  }
  rnColor()

  const body = document.body;
  const chr = document.querySelector('.rfd');
  const prev = [0, 0];

  posChr();

  function posChr() {
    let x = Math.floor(Math.random() * body.offsetWidth);
    let y = Math.floor(Math.random() * body.offsetHeight);

    while (Math.sqrt((x - prev[0]) ** 2 + (y - prev[1]) ** 2) < 10) {
      x = Math.floor(Math.random() * body.offsetWidth);
      y = Math.floor(Math.random() * body.offsetHeight);
    }
    chr.style.left = `${x}px`;
    chr.style.top = `${y}px`;
    chr.textContent = fourdigitsrandom;
    prev[0] = x;
    prev[1] = y;

    setTimeout(posChr, 500);

  }

  setTimeout(posChr, 500)

}

body {
  height: 100vh;
}

.rfd {
  position: fixed;
}

<!DOCTYPE html>
<html>

<head>
  <title>Subliminal Test</title>

</head>

<body>
  <h1>Subliminal Test</h1>

  <button id="bt" type="button">Start Test</button>

  <span class="rfd"></span>

</body>

</html>


问:
Checking position of newly added unique_ptr to priority_queue
I am switching my design to use smart pointers and I've encountered a problem with std::priority_que

I had a method that inserts new task into queue and signalizes if new task landed at the top of it:

```<code>bool foo(SchedulerTask* task)
{
  eventList_.push(task);
  return task == eventList_.top();
}
</code>```

After wrapping SchedulerTask into unique_ptr I met problem with checking its priority in container. After moving the object into queue I was not able to use it again for compare. I have end up with caching comparator member and comparing it with the top object:

```<code>bool foo(std::unique_ptr<SchedulerTask> task)
{
  const auto prio = task->getCycle(); // my priority_queue compares objects by getCycle() value

  eventList_.push(std::move(task));

  return prio >= eventList_.top()->getCycle();;
}
</code>```

Can it be done better way?

答:
As @Sam Varschavchik hinted at, you can compare to the raw pointer. I.e. you'd do something like:</p>

```<code>bool foo (std::unique_ptr<SchedulerTask> task) {
  auto const * taskPtr = task.get();
  eventList_.push(std::move(task));
  return taskPtr == eventList_.top().get();
}
</code>```

Body:
I am switching my design to use smart pointers and I've encountered a problem with std::priority_que

I had a method that inserts new task into queue and signalizes if new task landed at the top of it:

bool foo(SchedulerTask* task)
{
  eventList_.push(task);
  return task == eventList_.top();
}

After wrapping SchedulerTask into unique_ptr I met problem with checking its priority in container. After moving the object into queue I was not able to use it again for compare. I have end up with caching comparator member and comparing it with the top object:

bool foo(std::unique_ptr<SchedulerTask> task)
{
  const auto prio = task->getCycle(); // my priority_queue compares objects by getCycle() value

  eventList_.push(std::move(task));

  return prio >= eventList_.top()->getCycle();;
}

Can it be done better way?

Body:
As @Sam Varschavchik hinted at, you can compare to the raw pointer. I.e. you'd do something like:

bool foo (std::unique_ptr<SchedulerTask> task) {
  auto const * taskPtr = task.get();
  eventList_.push(std::move(task));
  return taskPtr == eventList_.top().get();
}


问:
Database design for email-style application
I'm looking for some advice on how to design a database for an email-style application, specifically how to handle sending a message to multiple users, and displaying what messages were sent to what users.

This is what I have so far:

Messages (Primary Key is Id)

Id (Identity)

SenderId (Foreign Key to Users.Id)

<message data>

ReceivedMessages (Primary key is MessageId + RecipientId)

MessageId (Foreign Key to Messages.Id)

RecipientId (Foreign Key to Users.Id)

IsRead

So for every message sent, there would be one row in Messages, with the data, and then one row for each recipient in ReceivedMessages.

But what if I want to view all the messages sent by a user, and who they were sent to? For each message, I'd need to find all the ReceivedMessages rows for that message, and join all of those with the user table, and then somehow concat all the names (something like this: Concatenate many rows into a single text string?). Might this cause scaling issues, or is it not really anything to worry about?

Any thoughts/suggestions? Thanks.

答:
Users change name and email, but not their login. Consider mimicking what happens in a unix-based mailbox (e.g. pine) instead:

```<code>received_messages (
  user_id,
  message_id,
  message_date,
  message_title,
  message_content,
  message_sender,
  message_recipient,
  message_is_read
)
</code>```

and sent_messages along the same lines, i.e. two "files" per user.

Or even merging the latter two with a sent/received flag.

Body:
Users change name and email, but not their login. Consider mimicking what happens in a unix-based mailbox (e.g. pine) instead:

received_messages (
  user_id,
  message_id,
  message_date,
  message_title,
  message_content,
  message_sender,
  message_recipient,
  message_is_read
)

and sent_messages along the same lines, i.e. two "files" per user.

Or even merging the latter two with a sent/received flag.


Title: converting probeID into genesymbol

Body:
guys. I'm here to ask for your help.

I have problem converting my probeID to Gene.Symbol

my data looks like this

               C1           C2           C3          C4          C5
200000_s_at 9.372446    9.299193    10.017991   9.181135    9.734582
200001_at   11.777132   11.692039   12.013986   11.936100   11.832065
200002_at   12.199002   12.544633   12.365026   12.026991   12.439448
200003_s_at 12.962001   12.445636   12.441083   12.809544   12.622457
200004_at   11.233249   10.961737   11.588765   11.206607   11.674372
200005_at   10.133455   10.438360   10.897712   10.653804   11.359433
200006_at   11.004593   10.584082   11.182127   11.375084   11.182136
200007_at   11.070449   10.949878   11.643648   11.581889   11.730024
200008_s_at 10.289446   10.304524   10.381671   10.136443   11.101463
200009_at   11.408603   11.114905   11.442766   11.448240   12.008252
200010_at   12.081858   11.927526   12.161929   12.299117   12.303224
200011_s_at 10.280210   10.026668   11.108151   10.371077   10.770123

and I'd like to change my row name(ID) to (Gene Symbol) if it matches this condition below.

Any help would be appreciated.

Body:
Let's say your annotation table looks like this:

ann_table = structure(list(ID = structure(c(9L, 8L, 16L, 6L, 4L, 12L, 3L,
10L, 5L, 13L, 2L, 11L, 1L, 7L, 15L, 17L, 14L), .Label = c("1557256_a_at",
"1557557_at", "1557770_at", "200000_s_at", "200001_at", "200002_at",
"200003_s_at", "200004_at", "200005_at", "200006_at", "200007_at",
"200008_s_at", "200009_at", "200010_at", "200011_s_at", "208010_s_at",
"235668_at"), class = "factor"), `Gene Symbol` = structure(c(3L,
4L, 12L, 15L, 11L, 6L, 7L, 9L, 2L, 6L, 8L, 16L, 5L, 14L, 1L,
10L, 13L), .Label = c("ARF3", "CAPNS1", "EIF3D", "EIF4G2", "GABRB1",
"GDI2", "IPO11", "MATN1-AS1", "PARK7", "PRDM1", "PRPF8", "PTPN22",
"RPL11", "RPL28", "RPL35", "SRP14"), class = "factor")), class = "data.frame", row.names = c("200005_at",
"200004_at", "208010_s_at", "200002_at", "200000_s_at", "200008_s_at",
"1557770_at", "200006_at", "200001_at", "200009_at", "1557557_at",
"200007_at", "1557256_a_at", "200003_s_at", "200011_s_at", "235668_at",
"200010_at"))

And the matrix you showed is:

mydata = structure(list(C1 = c(9.372446, 11.777132, 12.199002, 12.962001,
11.233249, 10.133455, 11.004593, 11.070449, 10.289446, 11.408603,
12.081858, 10.28021), C2 = c(9.299193, 11.692039, 12.544633,
12.445636, 10.961737, 10.43836, 10.584082, 10.949878, 10.304524,
11.114905, 11.927526, 10.026668), C3 = c(10.017991, 12.013986,
12.365026, 12.441083, 11.588765, 10.897712, 11.182127, 11.643648,
10.381671, 11.442766, 12.161929, 11.108151), C4 = c(9.181135,
11.9361, 12.026991, 12.809544, 11.206607, 10.653804, 11.375084,
11.581889, 10.136443, 11.44824, 12.299117, 10.371077), C5 = c(9.734582,
11.832065, 12.439448, 12.622457, 11.674372, 11.359433, 11.182136,
11.730024, 11.101463, 12.008252, 12.303224, 10.770123)), class = "data.frame", row.names = c("200000_s_at",
"200001_at", "200002_at", "200003_s_at", "200004_at", "200005_at",
"200006_at", "200007_at", "200008_s_at", "200009_at", "200010_at",
"200011_s_at"))

The gene symbols to corresponding rownames are:

as.character(ann_table[match(rownames(mydata),ann_table$ID),"Gene Symbol"])
 [1] "PRPF8"  "CAPNS1" "RPL35"  "RPL28"  "EIF4G2" "EIF3D"
 [7] "PARK7"  "SRP14"  "GDI2"   "GDI2"   "RPL11"  "ARF3"

Or you can use a library:

library(hgu133plus2.db)
mapIds(hgu133plus2.db,keys=rownames(mydata),column=c("SYMBOL"),keytype = "PROBEID")

But before you substitute the rownames of the matrix, you should check for NAs and duplicated SYMBOLS.


问:
I only have one key, but need to extract objects based on rating
Can I get synsets or words using rating even though it's all under one key? I've been trying to extract json objects based on if their rating is less than 1. However, all the syntax online searches based on key. But I only have one key. Can I search by the object attribute instead? </p>

<p>JSON document: </p>

```<code>"connections": [
        {
            "synset": 5995898,
            "rating": 1.0,
            "words": [
                "monetarism"
            ],
            "examples": []
        },
        {
            "synset": 1558749,
            "rating": 0.6,
            "words": [
                "driven",
                "impelled"
            ],
            "examples": [
                "felt impelled to take a stand against the issue"
            ]
        },
        {
            "synset": 1421122,
            "rating": 0.17204301075268819,
            "words": [
                "plug in",
                "plug into",
                "connect"
            ],
            "examples": [
                "Please plug in the toaster!",
                "Connect the TV so we can watch the football game tonight"
            ]
        },
</code>```

答:
Yes, you easily can do it with sorted and filter function, see examples in https://docs.python.org/3/howto/sorting.html.

import json

conns = json.loads(your_json_payload)["connections"]
filtered = [  # Do some filtering
    obj for obj in conns
    if (
        obj["rating"] <= 1 and
        "KeyPhrase" in obj["words"]
    )
]
sorted_by_rating = sorted(filtered, key=lambda x: x["rating"])
```

Body:
Can I get synsets or words using rating even though it's all under one key? I've been trying to extract json objects based on if their rating is less than 1. However, all the syntax online searches based on key. But I only have one key. Can I search by the object attribute instead?

JSON document:

"connections": [
        {
            "synset": 5995898,
            "rating": 1.0,
            "words": [
                "monetarism"
            ],
            "examples": []
        },
        {
            "synset": 1558749,
            "rating": 0.6,
            "words": [
                "driven",
                "impelled"
            ],
            "examples": [
                "felt impelled to take a stand against the issue"
            ]
        },
        {
            "synset": 1421122,
            "rating": 0.17204301075268819,
            "words": [
                "plug in",
                "plug into",
                "connect"
            ],
            "examples": [
                "Please plug in the toaster!",
                "Connect the TV so we can watch the football game tonight"
            ]
        },


问:
Laravel add variable for nested collections
I want to add variable to each object of collection inside collection. Here JSON response like this:

```<code>         {
         "id": 16,
          "survey_id": "8",
          "title": "How are you?",
          "created_at": "2020-02-06 04:21:44",
          "updated_at": "2020-02-06 04:21:44",
              "answers": [
</code>```

Here I want to add variable to each answer

```<code>{
            "id": 52,
            "question_id": "16",
            "text": "VERY GOOD",
            "created_at": "2020-02-06 04:21:44",
            "updated_at": "2020-02-06 04:21:44",
            "reports_count": "4",
            "responded": 2
        },
        {
            "id": 53,
            "question_id": "16",
            "text": "OK",
            "created_at": "2020-02-06 04:21:44",
            "updated_at": "2020-02-06 04:21:44",
            "reports_count": "4",
            "responded": 2
        },
        {
            "id": 54,
            "question_id": "16",
            "text": "BAD",
            "created_at": "2020-02-06 04:21:44",
            "updated_at": "2020-02-06 04:21:44",
            "reports_count": "2",
            "responded": 2
        }
    ]
},
</code>```

Overall, I want to add for every answers variable like $respond = $answer->reports()->count(); Help PLease!!

答:
You could do something like this, if you want to calculate it in the collection directly.

```<code>$yourCollection->transform(function($collectionItem) {
  $collectionItem['responded'] = $collectionItem->answers->count();
  return $collectionItem;
});
</code>```

But you could do this also on the sql side. I think it should be also the better way ;)

Body:
I want to add variable to each object of collection inside collection. Here JSON response like this:

         {
         "id": 16,
          "survey_id": "8",
          "title": "How are you?",
          "created_at": "2020-02-06 04:21:44",
          "updated_at": "2020-02-06 04:21:44",
              "answers": [

Here I want to add variable to each answer

{
            "id": 52,
            "question_id": "16",
            "text": "VERY GOOD",
            "created_at": "2020-02-06 04:21:44",
            "updated_at": "2020-02-06 04:21:44",
            "reports_count": "4",
            "responded": 2
        },
        {
            "id": 53,
            "question_id": "16",
            "text": "OK",
            "created_at": "2020-02-06 04:21:44",
            "updated_at": "2020-02-06 04:21:44",
            "reports_count": "4",
            "responded": 2
        },
        {
            "id": 54,
            "question_id": "16",
            "text": "BAD",
            "created_at": "2020-02-06 04:21:44",
            "updated_at": "2020-02-06 04:21:44",
            "reports_count": "2",
            "responded": 2
        }
    ]
},

Overall, I want to add for every answers variable like $respond = $answer->reports()->count(); Help PLease!!

Body:
You could do something like this, if you want to calculate it in the collection directly.

$yourCollection->transform(function($collectionItem) {
  $collectionItem['responded'] = $collectionItem->answers->count();
  return $collectionItem;
});

But you could do this also on the sql side. I think it should be also the better way ;)


问:
Kubernetes cluster recreated from snapshots issue
OVERVIEW:: I am studying for the Kubernetes Administrator certification. To complete the training course, I created a dual node Kubernetes cluster on Google Cloud, 1 master and 1 slave. As I don't want to leave the instances alive all the time, I took snapshots of them to deploy new instances with the Kubernetes cluster already setup. I am aware that I would need to update the ens4 ip used by kubectl, as this will have changed, which I did.

ISSUE:: When I run "kubectl get pods --all-namespaces" I get the error "The connection to the server localhost:8080 was refused - did you specify the right host or port?"

QUESTION:: Would anyone have had similar issues and know if its possible to recreate a Kubernetes cluster from snapshots?

Adding -v=10 to command, the url matches info in .kube/config file

kubectl get pods --all-namespaces -v=10
  I0214 17:11:35.317678    6246 loader.go:375] Config loaded from file:  /home/student/.kube/config
  I0214 17:11:35.321941    6246 round_trippers.go:423] curl -k -v -XGET  -H "User-Agent: kubectl/v1.16.1 (linux/amd64) kubernetes/d647ddb" -H "Accept: application/json, /" 'https://k8smaster:6443/api?timeout=32s'
  I0214 17:11:35.333308    6246 round_trippers.go:443] GET https://k8smaster:6443/api?timeout=32s  in 11 milliseconds
  I0214 17:11:35.333335    6246 round_trippers.go:449] Response Headers:
  I0214 17:11:35.333422    6246 cached_discovery.go:121] skipped caching discovery info due to Get https://k8smaster:6443/api?timeout=32s: dial tcp 10.128.0.7:6443: connect: connection refused
  I0214 17:11:35.333858    6246 round_trippers.go:423] curl -k -v -XGET  -H "Accept: application/json, /" -H "User-Agent: kubectl/v1.16.1 (linux/amd64) kubernetes/d647ddb" 'https://k8smaster:6443/api?timeout=32s'
  I0214 17:11:35.334234    6246 round_trippers.go:443] GET https://k8smaster:6443/api?timeout=32s  in 0 milliseconds
  I0214 17:11:35.334254    6246 round_trippers.go:449] Response Headers:
  I0214 17:11:35.334281    6246 cached_discovery.go:121] skipped caching discovery info due to Get https://k8smaster:6443/api?timeout=32s: dial tcp 10.128.0.7:6443: connect: connection refused
  I0214 17:11:35.334303    6246 shortcut.go:89] Error loading discovery information: Get https://k8smaster:6443/api?timeout=32s: dial tcp 10.128.0.7:6443: connect: connection refused

答:
I replicated you issue and wrote this step by step debugging process for you so you can see what was my thinking.

I created 2 node cluster (master + worker) with kubeadm and made a snapshot.
Then I deleted all nodes and recreated them from snapshots.

After recreating master node from snapshot I started seeing the same error you are seeing:

```<code>@kmaster ~]$ kubectl get po -v=10
I0217 11:04:38.397823    3372 loader.go:375] Config loaded from file:  /home/user/.kube/config
I0217 11:04:38.398909    3372 round_trippers.go:423] curl -k -v -XGET  -H "Accept: application/json, */*" -H "User-Agent: kubectl/v1.17.3 (linux/amd64) kubernetes/06ad960" 'https://10.156.0.20:6443/api?timeout=32s'
^C
</code>```

The connection was hanging so I interrupted it (ctrl+c).
First I noticed was that IP address of where kubectl was connecting was different than node ip, so I modified .kube/config file providing proper IP.

After doing this, here is what running kubectl showed:

```<code>$ kubectl get po -v=10
I0217 11:26:57.020744   15929 loader.go:375] Config loaded from file:  /home/user/.kube/config
...
I0217 11:26:57.025155   15929 helpers.go:221] Connection error: Get https://10.156.0.23:6443/api?timeout=32s: dial tcp 10.156.0.23:6443: connect: connection refused
F0217 11:26:57.025201   15929 helpers.go:114] The connection to the server 10.156.0.23:6443 was refused - did you specify the right host or port?
</code>```

As you see, connection to apiserver was beeing refused so I checked if apiserver was running:

```<code>$ sudo docker ps -a | grep apiserver
5e957ff48d11        90d27391b780             "kube-apiserver --ad…"   24 seconds ago      Exited (2) 3 seconds ago                           k8s_kube-apiserver_kube-apiserver-kmaster_kube-system_997514ff25ec38012de6a5be7c43b0ae_14
d78e179f1565        k8s.gcr.io/pause:3.1     "/pause"                 26 minutes ago      Up 26 minutes                                      k8s_POD_kube-apiserver-kmaster_kube-system_997514ff25ec38012de6a5be7c43b0ae_1
</code>```

api-server was exiting for some reason.
I checked its logs (I am only including relevant logs for readability):

```<code>$ sudo docker logs 5e957ff48d11
...
W0217 11:30:46.710541       1 clientconn.go:1120] grpc: addrConn.createTransport failed to connect to {https://127.0.0.1:2379 0  <nil>}. Err :connection error: desc = "transport: Error while dialing dial tcp 127.0.0.1:2379: connect: connection refused". Reconnecting...
panic: context deadline exceeded
</code>```

Notice apiserver was trying to connect to etcd (notice port: 2379) and receiving connection refused.
My first guess was etcd wasn't running, so I checked etcd container:

```<code>$ sudo docker ps -a | grep etcd
4a249cb0743b        303ce5db0e90             "etcd --advertise-cl…"   2 minutes ago        Exited (1) 2 minutes ago                           k8s_etcd_etcd-kmaster_kube-system_9018aafee02ebb028a7befd10063ec1e_19
b89b7e7227de        k8s.gcr.io/pause:3.1     "/pause"                 30 minutes ago       Up 30 minutes                                      k8s_POD_etcd-kmaster_kube-system_9018aafee02ebb028a7befd10063ec1e_1
</code>```

I was right: Exited (1) 2 minutes ago. I checked its logs:

```<code>$ sudo docker logs 4a249cb0743b
...
2020-02-17 11:34:31.493215 C | etcdmain: listen tcp 10.156.0.20:2380: bind: cannot assign requested address
</code>```

etcd was trying to bind with old IP address.

I modified /etc/kubernetes/manifests/etcd.yaml and changed old IP address to new IP everywhere in file.

Quick sudo docker ps | grep etcd showed its running.
After a while apierver also started running.

Then I tried running kubectl:

```<code>$ kubectl get po
Unable to connect to the server: x509: certificate is valid for 10.96.0.1, 10.156.0.20, not 10.156.0.23
</code>```

Invalid apiserver certificate. SSL certificate was genereated for old IP so that would mean I need to generate new certificate with new IP.

```<code>$ sudo kubeadm init phase certs apiserver
...
[certs] Using existing apiserver certificate and key on disk
</code>```

That's not what I expected. I wanted to generate new certificates, not use old ones.

I deleted old certificates:

```<code>$ sudo rm /etc/kubernetes/pki/apiserver.crt \
          /etc/kubernetes/pki/apiserver.key
</code>```

And tried to generate certificates one more time:

```<code>$ sudo kubeadm init phase certs apiserver
[certs] Generating "apiserver" certificate and key
[certs] apiserver serving cert is signed for DNS names [kmaster kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local] and IPs [10.96.0.1 10.156.0.23]
</code>```

Looks good. Now let's try using kubectl:

```<code>$ kubectl get no
NAME          STATUS   ROLES    AGE    VERSION
instance-21   Ready    master   102m   v1.17.3
instance-22   Ready    <none>   95m    v1.17.3
</code>```

As you can see now its working.

Body:
I replicated you issue and wrote this step by step debugging process for you so you can see what was my thinking.

I created 2 node cluster (master + worker) with kubeadm and made a snapshot.
Then I deleted all nodes and recreated them from snapshots.

After recreating master node from snapshot I started seeing the same error you are seeing:

@kmaster ~]$ kubectl get po -v=10
I0217 11:04:38.397823    3372 loader.go:375] Config loaded from file:  /home/user/.kube/config
I0217 11:04:38.398909    3372 round_trippers.go:423] curl -k -v -XGET  -H "Accept: application/json, */*" -H "User-Agent: kubectl/v1.17.3 (linux/amd64) kubernetes/06ad960" 'https://10.156.0.20:6443/api?timeout=32s'
^C

The connection was hanging so I interrupted it (ctrl+c).
First I noticed was that IP address of where kubectl was connecting was different than node ip, so I modified .kube/config file providing proper IP.

After doing this, here is what running kubectl showed:

$ kubectl get po -v=10
I0217 11:26:57.020744   15929 loader.go:375] Config loaded from file:  /home/user/.kube/config
...
I0217 11:26:57.025155   15929 helpers.go:221] Connection error: Get https://10.156.0.23:6443/api?timeout=32s: dial tcp 10.156.0.23:6443: connect: connection refused
F0217 11:26:57.025201   15929 helpers.go:114] The connection to the server 10.156.0.23:6443 was refused - did you specify the right host or port?

As you see, connection to apiserver was beeing refused so I checked if apiserver was running:

$ sudo docker ps -a | grep apiserver
5e957ff48d11        90d27391b780             "kube-apiserver --ad…"   24 seconds ago      Exited (2) 3 seconds ago                           k8s_kube-apiserver_kube-apiserver-kmaster_kube-system_997514ff25ec38012de6a5be7c43b0ae_14
d78e179f1565        k8s.gcr.io/pause:3.1     "/pause"                 26 minutes ago      Up 26 minutes                                      k8s_POD_kube-apiserver-kmaster_kube-system_997514ff25ec38012de6a5be7c43b0ae_1

api-server was exiting for some reason.
I checked its logs (I am only including relevant logs for readability):

$ sudo docker logs 5e957ff48d11
...
W0217 11:30:46.710541       1 clientconn.go:1120] grpc: addrConn.createTransport failed to connect to {https://127.0.0.1:2379 0  <nil>}. Err :connection error: desc = "transport: Error while dialing dial tcp 127.0.0.1:2379: connect: connection refused". Reconnecting...
panic: context deadline exceeded

Notice apiserver was trying to connect to etcd (notice port: 2379) and receiving connection refused.
My first guess was etcd wasn't running, so I checked etcd container:

$ sudo docker ps -a | grep etcd
4a249cb0743b        303ce5db0e90             "etcd --advertise-cl…"   2 minutes ago        Exited (1) 2 minutes ago                           k8s_etcd_etcd-kmaster_kube-system_9018aafee02ebb028a7befd10063ec1e_19
b89b7e7227de        k8s.gcr.io/pause:3.1     "/pause"                 30 minutes ago       Up 30 minutes                                      k8s_POD_etcd-kmaster_kube-system_9018aafee02ebb028a7befd10063ec1e_1

I was right: Exited (1) 2 minutes ago. I checked its logs:

$ sudo docker logs 4a249cb0743b
...
2020-02-17 11:34:31.493215 C | etcdmain: listen tcp 10.156.0.20:2380: bind: cannot assign requested address

etcd was trying to bind with old IP address.

I modified /etc/kubernetes/manifests/etcd.yaml and changed old IP address to new IP everywhere in file.

Quick sudo docker ps | grep etcd showed its running.
After a while apierver also started running.

Then I tried running kubectl:

$ kubectl get po
Unable to connect to the server: x509: certificate is valid for 10.96.0.1, 10.156.0.20, not 10.156.0.23

Invalid apiserver certificate. SSL certificate was genereated for old IP so that would mean I need to generate new certificate with new IP.

$ sudo kubeadm init phase certs apiserver
...
[certs] Using existing apiserver certificate and key on disk

That's not what I expected. I wanted to generate new certificates, not use old ones.

I deleted old certificates:

$ sudo rm /etc/kubernetes/pki/apiserver.crt \
          /etc/kubernetes/pki/apiserver.key

And tried to generate certificates one more time:

$ sudo kubeadm init phase certs apiserver
[certs] Generating "apiserver" certificate and key
[certs] apiserver serving cert is signed for DNS names [kmaster kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local] and IPs [10.96.0.1 10.156.0.23]

Looks good. Now let's try using kubectl:

$ kubectl get no
NAME          STATUS   ROLES    AGE    VERSION
instance-21   Ready    master   102m   v1.17.3
instance-22   Ready    <none>   95m    v1.17.3

As you can see now its working.


问:
Using one time series to predict another (unevenly spaced) with Python
My goal is to find a way to test whether the time serie (red) can explain or predict the time serie (blue).

I have never worked with this kind of times series which are measured on different times/dates.

I would like any ideas or suggestions to set me on the path of approaching this problem.

I am not asking for a certain code but just methods and ways for approaching this.

答:
How about get correlation between Red and Blue.
Or you can check correlation between Blue +/- some days and Red

Below link seems good example regarding time-series prediction
https://towardsdatascience.com/how-to-predict-a-time-series-part-1-6d7eb182b540


问:
SAP Hybris 6.7 Media Management
We have a requirement of restricting media format to jpeg and png for media upload.
Hybris version is 6.7.0.
Is there and OOTB feature that can be used to achieve the same?</p>

答: I would suggest to write a validation to achieve this. Let's say you have this requirement for the application storefront then you can validate/restrict the supported types using the JS & Server-side(validator) checks. I believe you can do the same for the backend cockpit as well.</p>

Title: SAP Hybris 6.7 Media Management


问:
Regex conditional positive lookahead
I'm playing around with regular expressions at the moment trying to grasp them better and have a scenario with which I seem to struggle right now since I don't know whether that is even achievable through regex or not.

I have strings of text something like this

```<code>$array['key']['FirstWord']
$array['key']['FirstWord SecondWord']
$array['key']['FirstWord SecondWord ThirdWord']
$array['key']['FirstWord SecondWord ThirdWord FourthWord']
</code>```

The list could be ongoing. I want to match (select) the whitespaces between the inner key words. So in second line it would be the whitespace between FirstWord and SecondWord.

With ^\$array\['key'\]\['(?:\w+ +)+ I'm able to match the lines that contain more than one word within the key. Putting the first part (?<=^\$array\['key'\]\[') as positive lookahead I'm able to put the "marker" Just before the key words would start and then I'm lost. I was thinking of using word boundaries and then select anything between them, but with no success so far. Any suggestions or pointers?

EDIT:
The assumption would be that there would be some other text between these lines also, so simple \bwould not work as a regular expression.

答:
If supported, you could make use of the \G anchor to get iterative matches asserting the position at the end of the previous match.

You match either ^\$array\['key'\]\[' or you match 1 more word characters and forget what is currently matched using \K

Then match 1 or more horizontal whitespace chars.

```<code>(?:^\$array\['key'\]\['(?=.*?'])\w+|\G(?!^))\w+\K\h+
</code>```

(?: Non capture group

^\$array\['key'\]\[' Match $array['key']['

(?=.*?']) Positive lookahead, assert '] on the right

\w+ Match 1+ word chars

| Or

\G(?!^) Assert position at the end of previous match, not at the start

) Close non capture group

\w+ Match 1+ word chars

\K Reset the starting point of the reported match (forget what was matched)

\h+ Match 1+ horizontal whitespace chars

Regex demo

Title: Regex conditional positive lookahead

Body:
I'm playing around with regular expressions at the moment trying to grasp them better and have a scenario with which I seem to struggle right now since I don't know whether that is even achievable through regex or not.

I have strings of text something like this

$array['key']['FirstWord']
$array['key']['FirstWord SecondWord']
$array['key']['FirstWord SecondWord ThirdWord']
$array['key']['FirstWord SecondWord ThirdWord FourthWord']

The list could be ongoing. I want to match (select) the whitespaces between the inner key words. So in second line it would be the whitespace between FirstWord and SecondWord.

With ^\$array\['key'\]\['(?:\w+ +)+ I'm able to match the lines that contain more than one word within the key. Putting the first part (?<=^\$array\['key'\]\[') as positive lookahead I'm able to put the "marker" Just before the key words would start and then I'm lost. I was thinking of using word boundaries and then select anything between them, but with no success so far. Any suggestions or pointers?

EDIT:
The assumption would be that there would be some other text between these lines also, so simple \bwould not work as a regular expression.

Body:
If supported, you could make use of the \G anchor to get iterative matches asserting the position at the end of the previous match.

You match either ^\$array\['key'\]\[' or you match 1 more word characters and forget what is currently matched using \K

Then match 1 or more horizontal whitespace chars.

(?:^\$array\['key'\]\['(?=.*?'])\w+|\G(?!^))\w+\K\h+

(?: Non capture group

^\$array\['key'\]\[' Match $array['key']['

(?=.*?']) Positive lookahead, assert '] on the right

\w+ Match 1+ word chars

| Or

\G(?!^) Assert position at the end of previous match, not at the start

) Close non capture group

\w+ Match 1+ word chars

\K Reset the starting point of the reported match (forget what was matched)

\h+ Match 1+ horizontal whitespace chars

Regex demo


问:
Thread freezing the application
I'm designing an application which reads DICOM data sets and visualizes them with volume rendering techniques by using VTK library. Anyway, the problem I'm dealing is volume rendering is really CPU-bounded process. If I handle the volume rendering in a single threaded process, application (GUI) freezes and passes to "not responding" state. I have written another thread for volume rendering process. However GUI still freezes, here are the codes.

```<code>private: System::Void volumeRenderButton_Click(System::Object^  sender, System::EventArgs^  e) {

             volumeRenderThread = gcnew System::Threading::Thread(gcnew System::Threading::ThreadStart(this, &Form1::volumeRender));
             volumeRenderThread->Priority = System::Threading::ThreadPriority::Lowest;
             volumeRenderThread->Start();
         }

private: void volumeRender()
         {
             threeDPictureBox->Invoke(gcnew volumeDelegate(this, &Form1::volumeDelegateMethod));

             /*
             if ( threeDPictureBox->InvokeRequired )
             {
                threeDPictureBox->Invoke(gcnew System::Action(this, &Form1::volumeRender));
             }
             else
             {
                 dicom->VolumeRender(threeDPictureBox, vrSettings);
             }
             */
         }
private: delegate void volumeDelegate();

private: void volumeDelegateMethod()
         {
             dicom->VolumeRender(threeDPictureBox, vrSettings);
         }

void Dicom::VolumeRender( Windows::Forms::PictureBox ^pictureBox, VRsettings *settings )
{
    renderer = vtkSmartPointer < vtkRenderer > :: New();
    renderWindow = vtkSmartPointer < vtkWin32OpenGLRenderWindow > :: New();
    renderWindow->AddRenderer(renderer);
    renderWindow->SetParentId((HWND)((pictureBox->Handle).ToPointer()));
    renderWindow->SetSize(pictureBox->Width, pictureBox->Height);
    renderWindow->Initialize();
    /* A lot of stuff here */
    ...
    ...
    renderWindow->Render();
    iren->Initialize();     // vtkWin32RenderWindowInteractor

}
</code>```

threeDPictureBox is a PictureBox component that I'm sending it to volumeRender method of dicom object. vrSettings is a struct for volume Rendering parameters.

When the volume Render button is clicked and click event handler fired, volumeRenderThread starts and freezes the application even I have set its priority Lowest! I have also tried the lines which is commented. None of them works. What's the point I'm missing?? Thanks for answers from now!!

答:
Your thread is invoked on a method that immediately jumps back onto the UI thread.

In other words, it has one action: tell the UI Thread to do the work.

Title: Thread freezing the application

Body:
I'm designing an application which reads DICOM data sets and visualizes them with volume rendering techniques by using VTK library. Anyway, the problem I'm dealing is volume rendering is really CPU-bounded process. If I handle the volume rendering in a single threaded process, application (GUI) freezes and passes to "not responding" state. I have written another thread for volume rendering process. However GUI still freezes, here are the codes.

private: System::Void volumeRenderButton_Click(System::Object^  sender, System::EventArgs^  e) {

             volumeRenderThread = gcnew System::Threading::Thread(gcnew System::Threading::ThreadStart(this, &Form1::volumeRender));
             volumeRenderThread->Priority = System::Threading::ThreadPriority::Lowest;
             volumeRenderThread->Start();
         }

private: void volumeRender()
         {
             threeDPictureBox->Invoke(gcnew volumeDelegate(this, &Form1::volumeDelegateMethod));

             /*
             if ( threeDPictureBox->InvokeRequired )
             {
                threeDPictureBox->Invoke(gcnew System::Action(this, &Form1::volumeRender));
             }
             else
             {
                 dicom->VolumeRender(threeDPictureBox, vrSettings);
             }
             */
         }
private: delegate void volumeDelegate();

private: void volumeDelegateMethod()
         {
             dicom->VolumeRender(threeDPictureBox, vrSettings);
         }

void Dicom::VolumeRender( Windows::Forms::PictureBox ^pictureBox, VRsettings *settings )
{
    renderer = vtkSmartPointer < vtkRenderer > :: New();
    renderWindow = vtkSmartPointer < vtkWin32OpenGLRenderWindow > :: New();
    renderWindow->AddRenderer(renderer);
    renderWindow->SetParentId((HWND)((pictureBox->Handle).ToPointer()));
    renderWindow->SetSize(pictureBox->Width, pictureBox->Height);
    renderWindow->Initialize();
    /* A lot of stuff here */
    ...
    ...
    renderWindow->Render();
    iren->Initialize();     // vtkWin32RenderWindowInteractor

}

threeDPictureBox is a PictureBox component that I'm sending it to volumeRender method of dicom object. vrSettings is a struct for volume Rendering parameters.

When the volume Render button is clicked and click event handler fired, volumeRenderThread starts and freezes the application even I have set its priority Lowest! I have also tried the lines which is commented. None of them works. What's the point I'm missing?? Thanks for answers from now!!


问:
How to get Row Values in a GRID field for a Submitted Form
We're sending Form responses to a webhook via a Google Apps Script attached to the form. Works great except when we use a GRID field type in the Form (eg see below)

we can only seem to get the column value for each row but not the row value.

So, in the grid field example we get an array as follows
(element 1) = OPPORTUNITY: OT Not Considered;
(element 2) = OPPORTUNITY: OT Considered

Is there a way we can also get the Row values?

Option 1 a second parallel array
(element 1) = OT 1;
(element 2) = OT 2

or Option 2
(element 1) = OT 1&&OPPORTUNITY: OT Not Considered;
(element 2) = OT 2&&OPPORTUNITY: OT Considered

Here's the GAS we're currently using to get the Form Submission

function onFormSubmit(e) {
 var data = {
      "id": e.source.getId(),
   "OTC_user" : Session.getActiveUser().getEmail(),
      "title": e.source.getTitle() ? e.source.getTitle() : "Untitled Form",
      "is_private": e.source.requiresLogin(),
      "is_published": e.source.isAcceptingResponses(),
      "id": e.response.getId(),
      "timestamp": e.response.getTimestamp(),
      "fields": e.response.getItemResponses().map(function(y) {
    return {
        h: y.getItem().getTitle(),
        k: y.getResponse()
    }
      }, this).reduce(function(r, y) {
    r[y.h] = y.k;
    return r
      }, {})
 };

 var options = {
  method: "post",
  payload: JSON.stringify(data, null, 2),
  contentType: "application/json; charset=utf-8",
 };

 UrlFetchApp.fetch("https://<WEBHOOK URL REMOVED", options);
};```

Thanks for any help

答:
Yes, there's a way to get the Row values. When you use the getItem(), which returns an interface item, you can specify that you want a GridItem using the method asGridItem(), in that way you will be able to get the Row values simply by calling the method getRows(). This is a small example code to give you a better idea about the privious explanation I wrote:

function onFormSubmit(e) {
  var itemVals = e.response.getItemResponses()[0].getItem().asGridItem();
  var rowVals = itemVals.getRows();
  var colVals = itemVals.getColumns();
  rowVals.forEach(function(e){Logger.log(e)});
  colVals.forEach(function(e){Logger.log(e)});
}
```

Body:
We're sending Form responses to a webhook via a Google Apps Script attached to the form. Works great except when we use a GRID field type in the Form (eg see below)

we can only seem to get the column value for each row but not the row value.

So, in the grid field example we get an array as follows
(element 1) = OPPORTUNITY: OT Not Considered;
(element 2) = OPPORTUNITY: OT Considered

Is there a way we can also get the Row values?

Option 1 a second parallel array
(element 1) = OT 1;
(element 2) = OT 2

or Option 2
(element 1) = OT 1&&OPPORTUNITY: OT Not Considered;
(element 2) = OT 2&&OPPORTUNITY: OT Considered

Here's the GAS we're currently using to get the Form Submission

function onFormSubmit(e) {
 var data = {
      "id": e.source.getId(),
   "OTC_user" : Session.getActiveUser().getEmail(),
      "title": e.source.getTitle() ? e.source.getTitle() : "Untitled Form",
      "is_private": e.source.requiresLogin(),
      "is_published": e.source.isAcceptingResponses(),
      "id": e.response.getId(),
      "timestamp": e.response.getTimestamp(),
      "fields": e.response.getItemResponses().map(function(y) {
    return {
        h: y.getItem().getTitle(),
        k: y.getResponse()
    }
      }, this).reduce(function(r, y) {
    r[y.h] = y.k;
    return r
      }, {})
 };

 var options = {
  method: "post",
  payload: JSON.stringify(data, null, 2),
  contentType: "application/json; charset=utf-8",
 };

 UrlFetchApp.fetch("https://<WEBHOOK URL REMOVED", options);
};

Thanks for any help


问:
Tomcat9 File Permissions Change
I have found that the file permissions have changed between Tomcat 8 and Tomcat 9 and I can't figure out how to get around it.

I had code like this where inputStream is something I feed this routine and redirectStream is a function that simply uses BufferedInput and BufferedOutput streams to read from one stream into another.

    Path path = "/some/example/path/to/a/file";
    Files.createDirectories(path.getParent());
    redirectStream(inputStream, new FileOutputStream(path.toFile());

After executing this bit of code in Tomcat8 the directories and file would have permissions matching the umask of the user (0022). That is the directories would have drwxr-xr-x and the files would have -rw-r--r--. As these files that it is writing are then accessible to the internet the global read flag is necessary.

But under Tomcat9, the same code gives, drwxr-x--- and -rw-r----- respectively, and thus are not visible to the internet. I have tried two things. One I have explicitly set the umask to 0022 in my tomcat startup script just to make sure that is what it is to no effect. The second is to explicitly set the permissions in code to try and force the issue. This fixed the file permissions but NOT not the directory permissions and below is the updated code.

```<code>Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_WRITE);
perms.add(PosixFilePermission.OWNER_EXECUTE);
perms.add(PosixFilePermission.GROUP_READ);
perms.add(PosixFilePermission.GROUP_WRITE);
perms.add(PosixFilePermission.GROUP_EXECUTE);
perms.add(PosixFilePermission.OTHERS_READ);
perms.add(PosixFilePermission.OTHERS_EXECUTE);
Files.createDirectories(path.getParent(), PosixFilePermissions.asFileAttribute(perms));

redirectStream(inputStream, new FileOutputStream(path.toFile());
perms = new HashSet<PosixFilePermission>();
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_WRITE);
perms.add(PosixFilePermission.GROUP_READ);
perms.add(PosixFilePermission.GROUP_WRITE);
perms.add(PosixFilePermission.OTHERS_READ);
Files.setPosixFilePermissions(fullPath, perms);
</code>```

Which actually fixes the file permission of the file but NOT the file permissions of the directories. I have tested the code outside of Tomcat and therefore know that it works. But for some reason Tomcat9's environment somehow makes it that the directories still get the restricted permissions.

Any ideas here?

答: The umask value can be directly changed from 0027 to 0022 in catalina.sh file itself if you don't have setenv.sh file.</p>

Title: Tomcat9 File Permissions Change

Body:
I have found that the file permissions have changed between Tomcat 8 and Tomcat 9 and I can't figure out how to get around it.

I had code like this where inputStream is something I feed this routine and redirectStream is a function that simply uses BufferedInput and BufferedOutput streams to read from one stream into another.

    Path path = "/some/example/path/to/a/file";
    Files.createDirectories(path.getParent());
    redirectStream(inputStream, new FileOutputStream(path.toFile());

After executing this bit of code in Tomcat8 the directories and file would have permissions matching the umask of the user (0022). That is the directories would have drwxr-xr-x and the files would have -rw-r--r--. As these files that it is writing are then accessible to the internet the global read flag is necessary.

But under Tomcat9, the same code gives, drwxr-x--- and -rw-r----- respectively, and thus are not visible to the internet. I have tried two things. One I have explicitly set the umask to 0022 in my tomcat startup script just to make sure that is what it is to no effect. The second is to explicitly set the permissions in code to try and force the issue. This fixed the file permissions but NOT not the directory permissions and below is the updated code.

Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_WRITE);
perms.add(PosixFilePermission.OWNER_EXECUTE);
perms.add(PosixFilePermission.GROUP_READ);
perms.add(PosixFilePermission.GROUP_WRITE);
perms.add(PosixFilePermission.GROUP_EXECUTE);
perms.add(PosixFilePermission.OTHERS_READ);
perms.add(PosixFilePermission.OTHERS_EXECUTE);
Files.createDirectories(path.getParent(), PosixFilePermissions.asFileAttribute(perms));

redirectStream(inputStream, new FileOutputStream(path.toFile());
perms = new HashSet<PosixFilePermission>();
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_WRITE);
perms.add(PosixFilePermission.GROUP_READ);
perms.add(PosixFilePermission.GROUP_WRITE);
perms.add(PosixFilePermission.OTHERS_READ);
Files.setPosixFilePermissions(fullPath, perms);

Which actually fixes the file permission of the file but NOT the file permissions of the directories. I have tested the code outside of Tomcat and therefore know that it works. But for some reason Tomcat9's environment somehow makes it that the directories still get the restricted permissions.

Any ideas here?


问:
MongoDB entries sinde my .bash_profile are not recognized (Mac OS)
I installed MongoDB on my Macbook (Catalina 10.15.3) and placed all the necessary entries in my .bash_profile. However, these entries are not recognized, so I have to manually enter the following again and again in order to start MongoDB (for each new terminal):

```<code>export MONGO_PATH=/Users/codehan/Desktop/MongoDB/mongodb-macos-x86_64-4.2.3
export PATH=$MONGO_PATH/bin:$PATH
</code>```

Otherwise I always get the following in the terminal:

```<code>zsh: command not found: mongo
</code>```

But as soon as I enter export MONGO_PATH=/Users/codehan/Desktop/MongoDB/mongodb-macos-x86_64-4.2.3 and export PATH=$MONGO_PATH/bin:$PATH in my terminal it works again.

How can I fix this problem?

答: With zsh, the configuration file is $HOME/.zshrc</p>

Body:
I installed MongoDB on my Macbook (Catalina 10.15.3) and placed all the necessary entries in my .bash_profile. However, these entries are not recognized, so I have to manually enter the following again and again in order to start MongoDB (for each new terminal):

export MONGO_PATH=/Users/codehan/Desktop/MongoDB/mongodb-macos-x86_64-4.2.3
export PATH=$MONGO_PATH/bin:$PATH

Otherwise I always get the following in the terminal:

zsh: command not found: mongo

But as soon as I enter export MONGO_PATH=/Users/codehan/Desktop/MongoDB/mongodb-macos-x86_64-4.2.3 and export PATH=$MONGO_PATH/bin:$PATH in my terminal it works again.

How can I fix this problem?