问:
"Member AutoSync Failure" using TPT, view and instead of insert trigger
Trying to use Linq2SQL with class inheritance using TPT pattern like this http://blogs.msdn.com/sbajaj/archive/2008/04/02/tpt-with-linq-to-sql.aspx

Sample application works fine. Here is my code:

Tables and views:

```CREATE TABLE [dbo].[social_event](
    [Id] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
    [Creator] [uniqueidentifier] NOT NULL FOREIGN KEY REFERENCES [dbo].[aspnet_Users](UserId),
    [EventDate] [datetime] NOT NULL)
GO

CREATE TABLE [dbo].[social_addfriendevent](
    [ID] [int] NOT NULL PRIMARY KEY FOREIGN KEY REFERENCES [dbo].[social_event](Id),
    [Friend] [uniqueidentifier] NOT NULL FOREIGN KEY REFERENCES [dbo].[aspnet_Users](UserId),
    [Added] [bit] NOT NULL DEFAULT((0)))
GO

CREATE VIEW [dbo].[event]
AS
SELECT t0.Id, t0.Creator, t0.EventDate, t1.Friend, t1.Added, 'AddFriendEvent' AS EventType
FROM  dbo.social_event AS t0 INNER JOIN
   dbo.social_addfriendevent AS t1 ON t0.Id = t1.Id
GO
```

 My "Instead of insert" trigger:

```CREATE TRIGGER [dbo].[trigger_update_event] ON [dbo].[event] INSTEAD OF INSERT
AS
    DECLARE @rc AS INT;
    SET @rc = @@ROWCOUNT;
    IF @rc = 0 RETURN;

    DECLARE @Id AS INT
    DECLARE @EventType AS NVARCHAR(50)
    DECLARE @Creator AS uniqueidentifier
    DECLARE @EventDate AS datetime
    DECLARE @Friend AS uniqueidentifier
    DECLARE @Added AS bit

    IF @rc = 1
        BEGIN
            SELECT @Id=Id,
   @EventType=EventType,
                 @Creator=Creator,
                 @EventDate = getdate(),
                 @Friend=Friend,
                 @Added=Added
            FROM INSERTED

            INSERT INTO dbo.social_event VALUES(@Creator, @EventDate)
            SELECT @Id = SCOPE_IDENTITY()
            IF @EventType = 'AddFriendEvent'
                INSERT INTO dbo.social_addfriendevent VALUES(@Id, @Friend, @Added)
        END
    ELSE
        BEGIN
            DECLARE cursor_inserted CURSOR FAST_FORWARD FOR
                SELECT EventType,
                     Creator,
                     EventDate,
                     Friend,
                     Added
                FROM INSERTED
            OPEN cursor_inserted;

            FETCH NEXT FROM cursor_inserted INTO @EventType,
                                             @Creator,
                                             @EventDate,
                                             @Friend,
                                             @Added;
            WHILE @@FETCH_STATUS = 0
            BEGIN
                INSERT INTO dbo.social_event VALUES(@Creator, @EventDate)
                SELECT @Id = SCOPE_IDENTITY()
                IF @EventType = 'AddFriendEvent'
                INSERT INTO dbo.social_addfriendevent VALUES(@Id, @Friend, @Added)
            END
            CLOSE cursor_inserted;
            DEALLOCATE cursor_inserted;
        END
```

My data classes with mappings:

```[InheritanceMapping(Code = "AddFriendEvent", Type = typeof(AddFriendEvent), IsDefault = true)]
 [Table(Name = "dbo.event")]
 public abstract class Event
 {
 private static int s_id;

 public Event()
 {
  this.Id = --Event.s_id;
 }

 public Event(string eventType)
  : this()
 {
  EventType = eventType;
 }

 [Column(IsPrimaryKey = true)]
 public int Id;

 [Column(Name = "Creator")]
 public Guid CreatorId;

 [Column(Name = "EventDate", DbType = "datetime")]
 public DateTime Date;

 [Column(IsDiscriminator = true, Name = "EventType")]
 public string EventType;
 }

 public class AddFriendEvent : Event
 {
 [Column(Name = "Added", CanBeNull = false)]
 public bool Added;

 [Column(Name = "Friend", CanBeNull = false)]
 public Guid Friend;

 public AddFriendEvent()
  : base("AddFriendEvent")
 {
 }
 }
```

When I try to create new "AddFriendEvent" and save it to database like here:

```DataContext dc = new DataContext(connectionString);
   Table<Event> allEvents = dc.GetTable<Event>();
   AddFriendEvent ev = new AddFriendEvent()
   {
    Added = true,
    CreatorId = Guid.Parse("379959D-58FE-4A57-BB02-559E3E855B8F"),
    Date = DateTime.Now,
    Friend = Guid.Parse("379959D-58FE-4A57-BB02-559E3E855B8F")
   };
   allEvents.InsertOnSubmit(ev);
   dc.SubmitChanges();
```

I got "Member AutoSync Failure". What's wrong?

答:
Currently my friend and me also had same problem. It is related to query generated by LinqtoSQL. When ever you are insert against view using trigger problem occur b'coz of scope_identity used by linq to sql.

Return @ID from trigger at last that you required. B'coz if do not do this it return NULL and that cause the problem.

Body:
Trying to use Linq2SQL with class inheritance using TPT pattern like this http://blogs.msdn.com/sbajaj/archive/2008/04/02/tpt-with-linq-to-sql.aspx

Sample application works fine. Here is my code:

Tables and views:

CREATE TABLE [dbo].[social_event](
    [Id] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
    [Creator] [uniqueidentifier] NOT NULL FOREIGN KEY REFERENCES [dbo].[aspnet_Users](UserId),
    [EventDate] [datetime] NOT NULL)
GO

CREATE TABLE [dbo].[social_addfriendevent](
    [ID] [int] NOT NULL PRIMARY KEY FOREIGN KEY REFERENCES [dbo].[social_event](Id),
    [Friend] [uniqueidentifier] NOT NULL FOREIGN KEY REFERENCES [dbo].[aspnet_Users](UserId),
    [Added] [bit] NOT NULL DEFAULT((0)))
GO

CREATE VIEW [dbo].[event]
AS
SELECT t0.Id, t0.Creator, t0.EventDate, t1.Friend, t1.Added, 'AddFriendEvent' AS EventType
FROM  dbo.social_event AS t0 INNER JOIN
   dbo.social_addfriendevent AS t1 ON t0.Id = t1.Id
GO

 My "Instead of insert" trigger:

CREATE TRIGGER [dbo].[trigger_update_event] ON [dbo].[event] INSTEAD OF INSERT
AS
    DECLARE @rc AS INT;
    SET @rc = @@ROWCOUNT;
    IF @rc = 0 RETURN;

    DECLARE @Id AS INT
    DECLARE @EventType AS NVARCHAR(50)
    DECLARE @Creator AS uniqueidentifier
    DECLARE @EventDate AS datetime
    DECLARE @Friend AS uniqueidentifier
    DECLARE @Added AS bit

    IF @rc = 1
        BEGIN
            SELECT @Id=Id,
   @EventType=EventType,
                 @Creator=Creator,
                 @EventDate = getdate(),
                 @Friend=Friend,
                 @Added=Added
            FROM INSERTED

            INSERT INTO dbo.social_event VALUES(@Creator, @EventDate)
            SELECT @Id = SCOPE_IDENTITY()
            IF @EventType = 'AddFriendEvent'
                INSERT INTO dbo.social_addfriendevent VALUES(@Id, @Friend, @Added)
        END
    ELSE
        BEGIN
            DECLARE cursor_inserted CURSOR FAST_FORWARD FOR
                SELECT EventType,
                     Creator,
                     EventDate,
                     Friend,
                     Added
                FROM INSERTED
            OPEN cursor_inserted;

            FETCH NEXT FROM cursor_inserted INTO @EventType,
                                             @Creator,
                                             @EventDate,
                                             @Friend,
                                             @Added;
            WHILE @@FETCH_STATUS = 0
            BEGIN
                INSERT INTO dbo.social_event VALUES(@Creator, @EventDate)
                SELECT @Id = SCOPE_IDENTITY()
                IF @EventType = 'AddFriendEvent'
                INSERT INTO dbo.social_addfriendevent VALUES(@Id, @Friend, @Added)
            END
            CLOSE cursor_inserted;
            DEALLOCATE cursor_inserted;
        END

My data classes with mappings:

[InheritanceMapping(Code = "AddFriendEvent", Type = typeof(AddFriendEvent), IsDefault = true)]
 [Table(Name = "dbo.event")]
 public abstract class Event
 {
 private static int s_id;

 public Event()
 {
  this.Id = --Event.s_id;
 }

 public Event(string eventType)
  : this()
 {
  EventType = eventType;
 }

 [Column(IsPrimaryKey = true)]
 public int Id;

 [Column(Name = "Creator")]
 public Guid CreatorId;

 [Column(Name = "EventDate", DbType = "datetime")]
 public DateTime Date;

 [Column(IsDiscriminator = true, Name = "EventType")]
 public string EventType;
 }

 public class AddFriendEvent : Event
 {
 [Column(Name = "Added", CanBeNull = false)]
 public bool Added;

 [Column(Name = "Friend", CanBeNull = false)]
 public Guid Friend;

 public AddFriendEvent()
  : base("AddFriendEvent")
 {
 }
 }

When I try to create new "AddFriendEvent" and save it to database like here:

DataContext dc = new DataContext(connectionString);
   Table<Event> allEvents = dc.GetTable<Event>();
   AddFriendEvent ev = new AddFriendEvent()
   {
    Added = true,
    CreatorId = Guid.Parse("379959D-58FE-4A57-BB02-559E3E855B8F"),
    Date = DateTime.Now,
    Friend = Guid.Parse("379959D-58FE-4A57-BB02-559E3E855B8F")
   };
   allEvents.InsertOnSubmit(ev);
   dc.SubmitChanges();

I got "Member AutoSync Failure". What's wrong?


来源: stackexchange

问:
How to rebase and push correctly in git using terminal
I was using VS Code git plugin for a while and now my new project is using the terminals to do the Gits and kid of new to the terminal mode.

Here is what I did so far, please suggest...

git clone http://remoteurl

git branch : output name is showing a branch name like 'stagingonly' ( not showing a name like master, let it be that)

git checkout -b X  : to create branch X

I did all the codings in X
: and now my team has alot new codes in the remote repo http://remoteurl , and adviced me to do rebase and push the code for code-review using terminal.

Please advice the missing step to do a rebase & remove conflicts and push the code ( remote repo is an azure devops repo)

Saw alot of steps in google, but thought of not messing with the client repos.

答:
you may just run git pull --rebase origin stagingonly to rebase all your commits onto latest state of remote version stagingonly branch. It will look like you just created your feature branch and put all you commits after latest ones from team branch.
For push git push --force-with-lease. --force-with-lease flag is needed, when commit's history on remote repo should be rewritten.

Note: local stagingonly branch will be behind origin/stagingonly link in your local repo. In order to update local stagingonly as well, you should run:

```<code> 1. git checkout stagingonly //switch onto local stagingonly
 2. git pull --rebase //get latest changes and update local copy
 3. git checkout featureBranch //switch onto your local featurebranch
 4. git pull --rebase //it is necessary, if someone else is working in your branch.
 5. git rebase staging only //rebase local featurebranch onto local staginonly
 6. git push --force-with-lease //
</code>```

Hope, you'll find it helpful.

ContentLicense: CC BY-SA 4.0

Body:
you may just run git pull --rebase origin stagingonly to rebase all your commits onto latest state of remote version stagingonly branch. It will look like you just created your feature branch and put all you commits after latest ones from team branch.
For push git push --force-with-lease. --force-with-lease flag is needed, when commit's history on remote repo should be rewritten.

Note: local stagingonly branch will be behind origin/stagingonly link in your local repo. In order to update local stagingonly as well, you should run:

 1. git checkout stagingonly //switch onto local stagingonly
 2. git pull --rebase //get latest changes and update local copy
 3. git checkout featureBranch //switch onto your local featurebranch
 4. git pull --rebase //it is necessary, if someone else is working in your branch.
 5. git rebase staging only //rebase local featurebranch onto local staginonly
 6. git push --force-with-lease //

Hope, you'll find it helpful.


问:
Platform android already exists. Ionic cordova cannot add platform
I have run into an error when cordova build. So I decided to do a cordova clean and cordova build. But the error persists saying something wrong with aapt. Some answers online said it might be a google.support version problem. So I did ionic cordova rm android, and removed my android from my project.

But when I tried to ionic cordova add android. It always shows me Platform android already exists.. I have been searching online but could not find a similar question.

I tried to delete the platforms folder, and add platform again. Still the same error. But when I reopen that project. platforms folder will be added back automatically which this structure inside.

答:
I have the same error. In my case the solution was detect that process had catch the folder, (adb.exe).

Then I killed the process and I could execute ionic cordova platform rm android, and then add platform again.

If you can't detect the process, you can restar the pc and try again.


问:
Find mean of values in one column, that share a common value in two other columns
I have a dataset that looks like this:

```<code>   year month quarter measurement
1  2005     1       1          33
2  2005     2       1           5
3  2005     4       2           3
4  2005     5       2           7
5  2005     6       2          10
6  2005     7       3           4
7  2005    10       4           9
8  2005    10       4           6
9  2005    11       4           8
10 2005    11       4           9
11 2005    11       4           3
12 2005    11       4           9
13 2005    11       4           2
14 2006    11       4           1
15 2006    12       4           1
16 2006    12       4           6
17 2006     1       1           9
18 2006     1       1           1
19 2006     1       1          10
20 2006     7       3           2
21 2006     1       1           0
22 2007     4       2           3
23 2007     1       1           4
24 2007     2       1           5
25 2007     2       1           1
26 2007     8       3           5
27 2007     9       3           6
28 2007     2       4           6
</code>```

I'd like to take the mean of all the values that share the same year value (column 1) and quarter value (column 3). The mean calculations would be performed on the measurement values (column 4). The month column (column 2) can be ignored-- I included it to show why I may have multiple Quarter 1 values for a single year.

I don't think I can use a rolling average formula, as there's a different amount of Quarter values for different years.

I believe I'd like to format my data like this:

Thank you

Body:
I have a dataset that looks like this:

   year month quarter measurement
1  2005     1       1          33
2  2005     2       1           5
3  2005     4       2           3
4  2005     5       2           7
5  2005     6       2          10
6  2005     7       3           4
7  2005    10       4           9
8  2005    10       4           6
9  2005    11       4           8
10 2005    11       4           9
11 2005    11       4           3
12 2005    11       4           9
13 2005    11       4           2
14 2006    11       4           1
15 2006    12       4           1
16 2006    12       4           6
17 2006     1       1           9
18 2006     1       1           1
19 2006     1       1          10
20 2006     7       3           2
21 2006     1       1           0
22 2007     4       2           3
23 2007     1       1           4
24 2007     2       1           5
25 2007     2       1           1
26 2007     8       3           5
27 2007     9       3           6
28 2007     2       4           6

I'd like to take the mean of all the values that share the same year value (column 1) and quarter value (column 3). The mean calculations would be performed on the measurement values (column 4). The month column (column 2) can be ignored-- I included it to show why I may have multiple Quarter 1 values for a single year.

I don't think I can use a rolling average formula, as there's a different amount of Quarter values for different years.

I believe I'd like to format my data like this:

Thank you

Body:
We can use dcast from data.table

library(data.table)
dcast(setDT(df1), quarter ~ year, value.var = 'measurement', mean)

Or with pivot_wider from tidyr

library(tidyr)
library(dplyr)
df1 %>%
   select(-month) %>%
    pivot_wider(names_from = year, values_from = measurement,
           values_fn = list(measurement = mean))

data

df1 <- structure(list(year = c(2005L, 2005L, 2005L, 2005L, 2005L, 2005L,
2005L, 2005L, 2005L, 2005L, 2005L, 2005L, 2005L, 2006L, 2006L,
2006L, 2006L, 2006L, 2006L, 2006L, 2006L, 2007L, 2007L, 2007L,
2007L, 2007L, 2007L, 2007L), month = c(1L, 2L, 4L, 5L, 6L, 7L,
10L, 10L, 11L, 11L, 11L, 11L, 11L, 11L, 12L, 12L, 1L, 1L, 1L,
7L, 1L, 4L, 1L, 2L, 2L, 8L, 9L, 2L), quarter = c(1L, 1L, 2L,
2L, 2L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 1L, 1L, 1L,
3L, 1L, 2L, 1L, 1L, 1L, 3L, 3L, 4L), measurement = c(33L, 5L,
3L, 7L, 10L, 4L, 9L, 6L, 8L, 9L, 3L, 9L, 2L, 1L, 1L, 6L, 9L,
1L, 10L, 2L, 0L, 3L, 4L, 5L, 1L, 5L, 6L, 6L)), class = "data.frame",
row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24",
"25", "26", "27", "28"))


问:
Webpack directory appended at error after migrating to Angular9
I've recently upgraded my projet from angular 7 to angular 9.

When I run the tests (ng test), I always get http://localhost:9876/_karma_webpack_/ appendend to the error, hence in visual studio code, we can't click on the error to got directly to the file.

For the sake of testing, I've added expect(2).toEqual(1); in the app.component.spec.ts file

For example, with the angular 7 projet out of the box, I get this error with ng test:

```<code>Chrome 81.0.4044 (Windows 10.0.0) AppComponent should have as title 'angular7app' FAILED
        Expected 2 to equal 1.
            at UserContext.<anonymous> (src/app/app.component.spec.ts:23:12)
</code>```

as for the angular 9, I get this error:

```<code>Chrome 81.0.4044.122 (Windows 10) AppComponent should have as title 'untaire' FAILED
        Error: Expected 2 to be 1.
            at <Jasmine>
            at UserContext.<anonymous> (http://localhost:9877/_karma_webpack_/src/app/app.component.spec.ts:23:12)
</code>```

When I check the versions in the package.json, theses are the changes that affects Karma and jasmine:

```<code>"@types/jasmine": "~2.8.8"                    to "~3.5.0"
"@types/jasminewd2": "~2.0.3"                 to "~2.0.3" (no changes)
"jasmine-core": "~2.99.1"                     to "~3.5.0"
"jasmine-spec-reporter": "~4.2.1",            to "~4.2.1" (no changes)
"karma": "~4.0.0",                            to "~5.0.0"
"karma-chrome-launcher": "~2.2.0",            to "~3.1.0"
"karma-coverage-istanbul-reporter": "~2.0.1", to "~2.1.0"
"karma-jasmine": "~1.1.2",                    to "~3.0.1"
"karma-jasmine-html-reporter": "^0.2.2",      to "^1.4.2"
</code>```

I've checked and I didn't found anything about this new behavior on any of theses packages

答:
You can add to karma.conf.js configuration property formatError:

```<code>formatError: (msg) =>
  msg.replace(/http:\/\/localhost:9876\/_karma_webpack_\//g, '')
</code>```

But not sure that is the best practice, however I cannot search alternative change format output location error in documentation karma http://karma-runner.github.io/4.0/config/configuration-file.html

Body:
I've recently upgraded my projet from angular 7 to angular 9.

When I run the tests (ng test), I always get http://localhost:9876/_karma_webpack_/ appendend to the error, hence in visual studio code, we can't click on the error to got directly to the file.

For the sake of testing, I've added expect(2).toEqual(1); in the app.component.spec.ts file

For example, with the angular 7 projet out of the box, I get this error with ng test:

Chrome 81.0.4044 (Windows 10.0.0) AppComponent should have as title 'angular7app' FAILED
        Expected 2 to equal 1.
            at UserContext.<anonymous> (src/app/app.component.spec.ts:23:12)

as for the angular 9, I get this error:

Chrome 81.0.4044.122 (Windows 10) AppComponent should have as title 'untaire' FAILED
        Error: Expected 2 to be 1.
            at <Jasmine>
            at UserContext.<anonymous> (http://localhost:9877/_karma_webpack_/src/app/app.component.spec.ts:23:12)

When I check the versions in the package.json, theses are the changes that affects Karma and jasmine:

"@types/jasmine": "~2.8.8"                    to "~3.5.0"
"@types/jasminewd2": "~2.0.3"                 to "~2.0.3" (no changes)
"jasmine-core": "~2.99.1"                     to "~3.5.0"
"jasmine-spec-reporter": "~4.2.1",            to "~4.2.1" (no changes)
"karma": "~4.0.0",                            to "~5.0.0"
"karma-chrome-launcher": "~2.2.0",            to "~3.1.0"
"karma-coverage-istanbul-reporter": "~2.0.1", to "~2.1.0"
"karma-jasmine": "~1.1.2",                    to "~3.0.1"
"karma-jasmine-html-reporter": "^0.2.2",      to "^1.4.2"

I've checked and I didn't found anything about this new behavior on any of theses packages

Body:
You can add to karma.conf.js configuration property formatError:

formatError: (msg) =>
  msg.replace(/http:\/\/localhost:9876\/_karma_webpack_\//g, '')

But not sure that is the best practice, however I cannot search alternative change format output location error in documentation karma http://karma-runner.github.io/4.0/config/configuration-file.html


问:
Background DIV fades in and out based on Intersection Observer
Currently, my background div text changes based on which element is on screen.

Is there a way to make it so:

the text fades out as the user scrolls

then fades in and is at 100% when the div is in the center of screen

then fades out as user scrolls further

does the opposite when the user scrolls back up

I have seen solutions based on JQuery but I want to get this done with vanilla javascript.

const section = document.querySelectorAll('.check');
const bg = document.querySelector('.bg');

const observer = new IntersectionObserver((entries, observer) => {
  entries.forEach(entry => {
    className = entry.target.classList[1];
    console.log(className);
    if (entry.isIntersecting) {
      if (className === 'first') {
        bg.innerHTML = 'FIRST';
      } else if (className === 'second') {
        bg.innerHTML = 'SECOND';
      } else if (className === 'third') {
        bg.innerHTML = 'THIRD';
      } else if (className === 'fourth') {
        bg.innerHTML = 'FOURTH';
      } else if (className === 'fifth') {
        bg.innerHTML = 'FIFTH';
      } else if (className === 'sixth') {
        bg.innerHTML = 'SIXTH';
      }
    } else {
    }
  })
});

section.forEach(section => {
  observer.observe(section);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.check {
  width: 100px;
  height: 20px;
  background-color: red;
  color: white;
  padding: 20px;
}

.spacer {
  height: 100vh;
  width: 100px;
}

.bg {
  position: fixed;
  font-size: 100px;
  color: #c9c9c9;
  z-index: -100;
}

.fadeIn {
  opacity: 1;
}

.fadeOut {
  opacity: 0;
}</code>```

  BG

FIRST

SECOND

THIRD

FOURTH

FIFTH

SIXTH

```

答:
Not my finest work but kind of works

const section = document.querySelectorAll('.check');
const bgText = document.querySelector('.bg__text');

const capitalize = (value) => {
  const [firstChar, ...rest] = value;

  return firstChar.toUpperCase() + rest.join('').toLowerCase()
}

const checkpoints = Array.from(document.querySelectorAll(".check"))
  .map(element => ({
    id: element.classList[1],
    element,
    rect: element.getBoundingClientRect()
  }));

let currentElement = null;

window.addEventListener("scroll", () => {
  const scrollY = window.scrollY;
  const innerHeight= window.innerHeight;

  const distances = checkpoints.map(pr => ({
    ...pr,
    distance: Math.abs(pr.rect.y - scrollY)
  }));

  distances.sort((prev, next) => prev.distance > next.distance ? 1 : -1);

  const distance = distances.find(pr => pr.element === currentElement).distance;

  let opacity = distance / innerHeight;
  opacity = opacity > 0.5 ? 1 - opacity : opacity;
  bgText.style.opacity = opacity * 2;

})

const observer = new IntersectionObserver((entries, observer) => {
  entries.forEach(entry => {
    const element = entry.target;
    className = element.classList[1];

    if (!entry.isIntersecting) {
      return;
    }

    currentElement = element;
    bgText.textContent = capitalize(className);

  })
});

section.forEach(section => {
  observer.observe(section);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.check {
  width: 100px;
  height: 20px;
  background-color: red;
  color: white;
  padding: 20px;
}

.spacer {
  height: 100vh;
  width: 100px;
}

.bg {
  position: fixed;
  font-size: 100px;
  color: #c9c9c9;
  z-index: -100;
}

.fadeIn {
  opacity: 1;
}

.fadeOut {
  opacity: 0;
}</code>```

  FIRST

  SECOND

  THIRD

  FOURTH

  FIFTH

  SIXTH

```

Body:
Currently, my background div text changes based on which element is on screen.

Is there a way to make it so:

the text fades out as the user scrolls

then fades in and is at 100% when the div is in the center of screen

then fades out as user scrolls further

does the opposite when the user scrolls back up

I have seen solutions based on JQuery but I want to get this done with vanilla javascript.

const section = document.querySelectorAll('.check');
const bg = document.querySelector('.bg');

const observer = new IntersectionObserver((entries, observer) => {
  entries.forEach(entry => {
    className = entry.target.classList[1];
    console.log(className);
    if (entry.isIntersecting) {
      if (className === 'first') {
        bg.innerHTML = 'FIRST';
      } else if (className === 'second') {
        bg.innerHTML = 'SECOND';
      } else if (className === 'third') {
        bg.innerHTML = 'THIRD';
      } else if (className === 'fourth') {
        bg.innerHTML = 'FOURTH';
      } else if (className === 'fifth') {
        bg.innerHTML = 'FIFTH';
      } else if (className === 'sixth') {
        bg.innerHTML = 'SIXTH';
      }
    } else {
    }
  })
});

section.forEach(section => {
  observer.observe(section);
});

.check {
  width: 100px;
  height: 20px;
  background-color: red;
  color: white;
  padding: 20px;
}

.spacer {
  height: 100vh;
  width: 100px;
}

.bg {
  position: fixed;
  font-size: 100px;
  color: #c9c9c9;
  z-index: -100;
}

.fadeIn {
  opacity: 1;
}

.fadeOut {
  opacity: 0;
}

  BG

FIRST

SECOND

THIRD

FOURTH

FIFTH

SIXTH

Body:
Not my finest work but kind of works

const section = document.querySelectorAll('.check');
const bgText = document.querySelector('.bg__text');

const capitalize = (value) => {
  const [firstChar, ...rest] = value;

  return firstChar.toUpperCase() + rest.join('').toLowerCase()
}

const checkpoints = Array.from(document.querySelectorAll(".check"))
  .map(element => ({
    id: element.classList[1],
    element,
    rect: element.getBoundingClientRect()
  }));

let currentElement = null;

window.addEventListener("scroll", () => {
  const scrollY = window.scrollY;
  const innerHeight= window.innerHeight;

  const distances = checkpoints.map(pr => ({
    ...pr,
    distance: Math.abs(pr.rect.y - scrollY)
  }));

  distances.sort((prev, next) => prev.distance > next.distance ? 1 : -1);

  const distance = distances.find(pr => pr.element === currentElement).distance;

  let opacity = distance / innerHeight;
  opacity = opacity > 0.5 ? 1 - opacity : opacity;
  bgText.style.opacity = opacity * 2;

})

const observer = new IntersectionObserver((entries, observer) => {
  entries.forEach(entry => {
    const element = entry.target;
    className = element.classList[1];

    if (!entry.isIntersecting) {
      return;
    }

    currentElement = element;
    bgText.textContent = capitalize(className);

  })
});

section.forEach(section => {
  observer.observe(section);
});

.check {
  width: 100px;
  height: 20px;
  background-color: red;
  color: white;
  padding: 20px;
}

.spacer {
  height: 100vh;
  width: 100px;
}

.bg {
  position: fixed;
  font-size: 100px;
  color: #c9c9c9;
  z-index: -100;
}

.fadeIn {
  opacity: 1;
}

.fadeOut {
  opacity: 0;
}

<div class="bg">
  <div class="bg__text"></div>
</div>

<div class="check first">
  FIRST
</div>
<div class="spacer">
</div>

<div class="check second">
  SECOND
</div>
<div class="spacer">
</div>

<div class="check third">
  THIRD
</div>
<div class="spacer">
</div>

<div class="check fourth">
  FOURTH
</div>
<div class="spacer">
</div>

<div class="check fifth">
  FIFTH
</div>
<div class="spacer">
</div>

<div class="check sixth">
  SIXTH
</div>
<div class="spacer">
</div>


问:
Yesterday's date (validation)
I am stuck with my code. So, I want to create a validation for my dates. For example, today we are on 2020-05-31, if the user enters a previous date to today, for example -> 2020-05-30.

I should to get an error message.

My problem is that my error message isn't display.

Do have you an idea please?

I would like to stay faithful my code please. (I am beginner)

Thank you for your help and your time.

function validation()
{
    const date_start = document.getElementById('date_start').value;

    if(!date_start){
        document.getElementById('date_startError').innerHTML = " ** Empty ! ";
        return false;
    }

    const inputDate = new Date(date_start).getDate();
    const today = new Date().getDate();

    if (inputDate < today || !inputDate.valueOf()) {
        document.getElementById('date_startError').innerHTML = " ** Error date ! ";
        return false;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="#" onsubmit="return validation()" >
  <br>
  <label>Date start : </label>
  <br>
  <input type="date" name="date_start" id="date_start" placeholder="2020-05-28">
  <br>
  <span id="date_startError"></span>
  <br>
  <input type="submit" value="ok">
</form></code>```

答:
Your code needs a curly brace "}" for it to work, however the form will be submitted before you will be able to see the error message so to prevent that you will have to adjust your code and use e.preventDefault,
also consider consider comparing your dates differently because
lets assume tomorrow 1st of June the user enter the date of today, your function will compare the 1st June < 30 of October and so it will break the logic of what you are trying to achieve so perhaps try to use milliseconds

Title: Yesterday's date (validation)

Body:
I am stuck with my code. So, I want to create a validation for my dates. For example, today we are on 2020-05-31, if the user enters a previous date to today, for example -> 2020-05-30.

I should to get an error message.

My problem is that my error message isn't display.

Do have you an idea please?

I would like to stay faithful my code please. (I am beginner)

Thank you for your help and your time.

function validation()
{
    const date_start = document.getElementById('date_start').value;

    if(!date_start){
        document.getElementById('date_startError').innerHTML = " ** Empty ! ";
        return false;
    }

    const inputDate = new Date(date_start).getDate();
    const today = new Date().getDate();

    if (inputDate < today || !inputDate.valueOf()) {
        document.getElementById('date_startError').innerHTML = " ** Error date ! ";
        return false;
}

<form action="#" onsubmit="return validation()" >

  Date start :

  <input type="date" name="date_start" id="date_start" placeholder="2020-05-28">

  <input type="submit" value="ok">
</form>


问:
Base64 encoded JWT token validation using KONG
I have a java code which generates a JWT token using Jwts.builder().
However, the generated token is then again encoded using a Base64 encoder, e.g.

Base64.getEncoder().encodeToString(token.getBytes())

I have been able to setup kong to validate the generated JWT token but I can not find a way to validate the Base64 encoded version of the token.

Can you please suggest if there is a way to handle such a scenario.

Kind Regards,

答:
I am not aware of a ready-to-use solution, however you can:

either clone the original jwt plugin and adapt the code so you can handle the base64 encoded string

or write your own plugin base64 decoder to decode it properly and then use the original jwt-plugin. You can control the order of execution so your custom plugin runs before the jwt plugin and replaces the original double-encoded token with the single-coded (normal) jwt token

To stay close to the original plugin and avoid code duplication, I would recommend the second way.


问:
Will Flink finish the sink process when sent a stop command
Here is my question :
Will filnk finish the sink process and rename the .inprogress files to part-x-x files when sending a stop command?

I find my flink tasks(using flink-1.9.1) will not rename the .inprogress files to part-x-x files. But I read the source code, it says

org.apache.flink.client.program.ClusterClient#stopWithSavepoint:

```<code> * Stops a program on Flink cluster whose job-manager is configured in this client's configuration.
 * Stopping works only for streaming programs. Be aware, that the program might continue to run for
 * a while after sending the stop command, because after sources stopped to emit data all operators
 * need to finish processing.
</code>```

答:
The StreamingFileSink does have some limitations in this regard. See this thread from the user@flink.apache.org mailing list.

FLIP-46, which is being tracked as FLINK-13103, is needed in order to fix this. Until then, the StreamingFileSink will remain unable to transition unfinished files to the finished state when a job is stopped. This is described in the documentation as Important Note 2.

Body:
Here is my question :
Will filnk finish the sink process and rename the .inprogress files to part-x-x files when sending a stop command?

I find my flink tasks(using flink-1.9.1) will not rename the .inprogress files to part-x-x files. But I read the source code, it says

org.apache.flink.client.program.ClusterClient#stopWithSavepoint:

 * Stops a program on Flink cluster whose job-manager is configured in this client's configuration.
 * Stopping works only for streaming programs. Be aware, that the program might continue to run for
 * a while after sending the stop command, because after sources stopped to emit data all operators
 * need to finish processing.


问:
What is the behavior of calling np.random.multinomial many times?
When called, np.random.multinomial and other sampling functions give a certain number of independent samples from the chosen probability distribution.  For instance,

np.random.multinomial(20, [1/6.]*6, size=2)

represents throwing a die 20 times, and then 20 times again.

However, what happens if you call np.random.multinomial(1, [1/6.]*6, size=1) a thousand times in succession?  Will I get a thousand independent die rolls, i.e. does np.random.multinomial guarantee independent samples and correct distributions between successive calls?  Empirically, it looks like there is some significant correlation between calls.  Is it better to reset np.random.RandomState before every call?  This seems wrong somehow.

答:
Anyway, you could try to do 20 (or any N rolls) by sampling from multinoulli (categorical) distribution first and then sum he result.

Along the lines (Python 3.7, x64, Anaconda Windows 10)

```<code>import numpy as np

def mymultinomial(n: int, p):
    """Hand made multinomial"""

    q = np.random.multinomial(1, p, size=n)

    return np.sum(q, axis=0)
</code>```

Code above called with mymultinomial(20, 6*[1./6.]) will return one sampled vector of 20 dice throws. You could compare the result with calls to np.random.multinomial(20, 6*[1./6.]), my quick tests show no statistical difference.

You could sample via choice() as well, could put it to test as well (probably could be done faster vectorized)

```<code>def mymultinomial(n: int, p):
    """Hand made multinomial, choice"""

    r = np.zeros(len(p), dtype = np.int64)
    for _ in range(0, n):
        q = np.random.choice(len(p), size=1, replace=True, p=p)
        r[q] += 1

    return r
</code>```

Body:
Anyway, you could try to do 20 (or any N rolls) by sampling from multinoulli (categorical) distribution first and then sum he result.

Along the lines (Python 3.7, x64, Anaconda Windows 10)

import numpy as np

def mymultinomial(n: int, p):
    """Hand made multinomial"""

    q = np.random.multinomial(1, p, size=n)

    return np.sum(q, axis=0)

Code above called with mymultinomial(20, 6*[1./6.]) will return one sampled vector of 20 dice throws. You could compare the result with calls to np.random.multinomial(20, 6*[1./6.]), my quick tests show no statistical difference.

You could sample via choice() as well, could put it to test as well (probably could be done faster vectorized)

def mymultinomial(n: int, p):
    """Hand made multinomial, choice"""

    r = np.zeros(len(p), dtype = np.int64)
    for _ in range(0, n):
        q = np.random.choice(len(p), size=1, replace=True, p=p)
        r[q] += 1

    return r


问:
How can I display elements into each row?
currently I am trying to display countries into a Material-UI table. However, all the data is displaying into one row. Anyone know how to fix it? The country array contains elements per index.

```<code><TableCell component="th" id={labelId} scope="row" >
   {country}
</TableCell>
</code>```

答:
Try this</p>

```<code><Table >
   <TableBody>
      {generateRows()}
   </TableBody>
</Table>

</code>```

```<code>const countries =['india','usa']
const generateRows = (countries)=>{
     return countries.map(country=>{
          return (
           <TableRow>
              <TableCell component="th" scope="row">
                  {country}
              </TableCell>
           </TableRow >
          )
    })

}
</code>```

Body:
currently I am trying to display countries into a Material-UI table. However, all the data is displaying into one row. Anyone know how to fix it? The country array contains elements per index.

<TableCell component="th" id={labelId} scope="row" >
   {country}
</TableCell>

Body:
Try this

<Table >
   <TableBody>
      {generateRows()}
   </TableBody>
</Table>

const countries =['india','usa']
const generateRows = (countries)=>{
     return countries.map(country=>{
          return (
           <TableRow>
              <TableCell component="th" scope="row">
                  {country}
              </TableCell>
           </TableRow >
          )
    })

}


问:
How to handle streaming data using fetch?
I have used async for with great success in handling output streams from processes with node.js, but I'm struggling to get something that I was hoping could "just work" with the browser fetch API.

This works great to async'ly handle chunks of output streaming from a process:

```<code>for await (const out of proc.child.stdout) {
  ...
}
</code>```

(in an async function context here of course)

I tried to do something similar in a browser where I want to gain access to the data while it is being sent to me from the server.

```<code>for await (const chunk of (await fetch('/data.jsonl')).body) {
  console.log('got', chunk);
}
</code>```

This does not work in Chrome (Uncaught TypeError: (intermediate value).body is not async iterable).

For my use case this is not necessary, so I am simply using let data = await (await fetch(datapath)).text(); in my client code for now. This is analogous to the typical use of .json() instead of .text() on the awaited fetch, so no processing can begin until the entire response is received by the browser. This is not ideal for obvious reasons.

I was looking at Oboe.js (I think the relevant impl is somewhere near here) which pretty much deals with this but its internals are fairly ugly so it looks like that might be the only way to do this for now?

If async iteration isn't implemented (meaning async for cannot be used yet) isn't there another way to use the ReadableStream in a practical way?

答:
According to the spec, a ReadableStream such as the fetch-API's Response.body does have a getIterator method. For some reason it's not async-iterable itself, you explicitly have to call that method:

```<code>const response = await fetch('/data.json');
if (!response.ok)
    throw new Error(await response.text());
for await (const chunk of response.body.getIterator()) {
    console.log('got', chunk);
}
</code>```

Body:
I have used async for with great success in handling output streams from processes with node.js, but I'm struggling to get something that I was hoping could "just work" with the browser fetch API.

This works great to async'ly handle chunks of output streaming from a process:

for await (const out of proc.child.stdout) {
  ...
}

(in an async function context here of course)

I tried to do something similar in a browser where I want to gain access to the data while it is being sent to me from the server.

for await (const chunk of (await fetch('/data.jsonl')).body) {
  console.log('got', chunk);
}

This does not work in Chrome (Uncaught TypeError: (intermediate value).body is not async iterable).

For my use case this is not necessary, so I am simply using let data = await (await fetch(datapath)).text(); in my client code for now. This is analogous to the typical use of .json() instead of .text() on the awaited fetch, so no processing can begin until the entire response is received by the browser. This is not ideal for obvious reasons.

I was looking at Oboe.js (I think the relevant impl is somewhere near here) which pretty much deals with this but its internals are fairly ugly so it looks like that might be the only way to do this for now?

If async iteration isn't implemented (meaning async for cannot be used yet) isn't there another way to use the ReadableStream in a practical way?

Body:
According to the spec, a ReadableStream such as the fetch-API's Response.body does have a getIterator method. For some reason it's not async-iterable itself, you explicitly have to call that method:

const response = await fetch('/data.json');
if (!response.ok)
    throw new Error(await response.text());
for await (const chunk of response.body.getIterator()) {
    console.log('got', chunk);
}


问:
Python question -- lambda version of a recursive combinations function
Okay so I have the following simple Python 3 function that does exactly what it's supposed to do:

```<code>def comb(a):
    if len(a)==0:
        return[[]]
    else:
        p=[]
        for c in comb(a[1:]):
            p+=[c,c+a[:1]]
        return p
</code>```

which correctly produces

```<code>>>> comb([1,2,3])
[[], [1], [2], [2, 1], [3], [3, 1], [3, 2], [3, 2, 1]]

</code>```

Motivated by nothing other than a desire to better my own understanding of recursive functions, I tried to see if I could turn this simple function into a lambda.  First thing I tried was various versions of:

```<code>comb=lambda a:[[]]if len(a)==0 else[[c,c+a[:1]]for c in comb(a[1:])]
</code>```

Which, obviously, didn't work.  Then I took a step back and just tried to change the syntax of the original function like:

```<code>def comb(a):
    return[[]]if len(a)==0 else[p for p in[[c,c+a[:1]]for c in comb(a[1:])]]
</code>```

Which also doesn't work, like at all.  I tried all kinds of different arrangements but to no avail.  Obviously the original function is the most useful and easiest to read, I'm only asking about this to better my own python understanding. I'm normally pretty good at this game when recursion isn't involved so I'm just trying to understand what it is I'm missing here.

答:
Your problem is with the list comprehension.

[[c,c+a[:1]]for c in l]  is a list of length len(l) whose elements are lists are with 2 elements.  What you want is a list of length 2*len(l), which is the flattened version of this.

comb=lambda a:[[]]if len(a)==0 else[c+a[:1]for c in comb(a[1:])] + comb(a[1:])
```

Works but can probably be improved because it makes 2 calls to comb each time, when only 1 is needed.

Body:
Okay so I have the following simple Python 3 function that does exactly what it's supposed to do:

def comb(a):
    if len(a)==0:
        return[[]]
    else:
        p=[]
        for c in comb(a[1:]):
            p+=[c,c+a[:1]]
        return p

which correctly produces

>>> comb([1,2,3])
[[], [1], [2], [2, 1], [3], [3, 1], [3, 2], [3, 2, 1]]

Motivated by nothing other than a desire to better my own understanding of recursive functions, I tried to see if I could turn this simple function into a lambda.  First thing I tried was various versions of:

comb=lambda a:[[]]if len(a)==0 else[[c,c+a[:1]]for c in comb(a[1:])]

Which, obviously, didn't work.  Then I took a step back and just tried to change the syntax of the original function like:

def comb(a):
    return[[]]if len(a)==0 else[p for p in[[c,c+a[:1]]for c in comb(a[1:])]]

Which also doesn't work, like at all.  I tried all kinds of different arrangements but to no avail.  Obviously the original function is the most useful and easiest to read, I'm only asking about this to better my own python understanding. I'm normally pretty good at this game when recursion isn't involved so I'm just trying to understand what it is I'm missing here.

Body:
Your problem is with the list comprehension.

[[c,c+a[:1]]for c in l]  is a list of length len(l) whose elements are lists are with 2 elements.  What you want is a list of length 2*len(l), which is the flattened version of this.

comb=lambda a:[[]]if len(a)==0 else[c+a[:1]for c in comb(a[1:])] + comb(a[1:])

Works but can probably be improved because it makes 2 calls to comb each time, when only 1 is needed.


答:
If your goal is to rewrite the function to lambda one-liner, you can do it using sum() for example:

```<code>comb = lambda a: [[]] if len(a)==0 else sum(([c,c+a[:1]] for c in comb(a[1:])), [])

print(comb([1, 2, 3]))
</code>```

Prints:

```<code>[[], [1], [2], [2, 1], [3], [3, 1], [3, 2], [3, 2, 1]]
</code>```

NOTE: The above solution is not very readable. The classic function is better.

Thanks @Chris_Rands, solution with itertools.chain:

```<code>from itertools import chain

comb = lambda a: [[]] if len(a)==0 else [*chain.from_iterable([c,c+a[:1]] for c in comb(a[1:]))]
</code>```

Title: Python question -- lambda version of a recursive combinations function

Body:
If your goal is to rewrite the function to lambda one-liner, you can do it using sum() for example:

comb = lambda a: [[]] if len(a)==0 else sum(([c,c+a[:1]] for c in comb(a[1:])), [])

print(comb([1, 2, 3]))

Prints:

[[], [1], [2], [2, 1], [3], [3, 1], [3, 2], [3, 2, 1]]

NOTE: The above solution is not very readable. The classic function is better.

Thanks @Chris_Rands, solution with itertools.chain:

from itertools import chain

comb = lambda a: [[]] if len(a)==0 else [*chain.from_iterable([c,c+a[:1]] for c in comb(a[1:]))]


问:
Going through a JSON file and displaying all elements
So I have a JSON file that I am fetching from github. And I have certain problems. My JSON file:

```<code>{    "Data" :
[
{"Name": "Widget", "Price": "25.00", "Quantity": "5" },
{"Name": "Thing", "Price": "15.00", "Quantity": "5" },
{"Name": "Doodad", "Price": "5.00", "Quantity": "10" }
] }
</code>```

Now, I am writing in a .html file and have a script section in which I want to write a JavaScript function that will allow me to go through Data from JSON and for example display the names of all the products that are there:

```<code> <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
    <body>
        <div>
            <form id="form1">
                What product do you want? <input name="name" type="text" size="20">
            </form>
            <button onclick="outputprodus()">Submit
            </button>
            <button id="fetchUserDataBtn">Cauta</button>
        </div>
        <hr>
        <div id="response"></div>
        <script>
            document.getElementById('fetchUserDataBtn').addEventListener('click', fetchUserData);

            function fetchUserData(){
                fetch('Vlad.json')
                    .then(response => response.json())
                    .then(Data => {
                        console.log("salut");
                        let output = "Lista produselor din stoc"
                        output += '<ul>';
                        Data.forEach(function(Data) {
                            output += `
                                <li>
                                    ${Data.Name}
                                </li>
                            `;
                        });
                        output += '</ul>'
                        document.getElementById("response").innerHTML = output;
                    });
            }
    </script>
    </body>
</html>
</code>```

When I run it, I get the error "Data.forEach is not a function". Funny enough is that when I write my JSON file without the initial "{"Data:" and just begin immediately writing the name for all objects, this problem does not occur and I can get a list of all the names of the products using the script above. However I want to use a loop to identify certain objects using a user input I will later add. Can anyone elucidate this for me?

答:
forEach is a method for arrays, not objects. What your code does is that it tries to forEach through the JSON itself. So you need to get the objects "Data" value which is the acutal array
 You can acheiv that throught objectName.propertyName or objectName["propertyName"]

so your code should look this this:

```<code>Data.Data.forEach(function(Data) {
  output += `<li>${Data.Name}</li>`;
});
</code>```

or

```<code>Data["Data"].forEach(function(Data) {
  output += `<li>${Data.Name}</li>`;
});
</code>```

objectName["propertyName"] can be useful when trying to access keys that look this this: "Data-new"

Body:
So I have a JSON file that I am fetching from github. And I have certain problems. My JSON file:

{    "Data" :
[
{"Name": "Widget", "Price": "25.00", "Quantity": "5" },
{"Name": "Thing", "Price": "15.00", "Quantity": "5" },
{"Name": "Doodad", "Price": "5.00", "Quantity": "10" }
] }

Now, I am writing in a .html file and have a script section in which I want to write a JavaScript function that will allow me to go through Data from JSON and for example display the names of all the products that are there:

 <!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

            <form id="form1">
                What product do you want? <input name="name" type="text" size="20">
            </form>
            <button onclick="outputprodus()">Submit
            </button>
            <button id="fetchUserDataBtn">Cauta</button>

When I run it, I get the error "Data.forEach is not a function". Funny enough is that when I write my JSON file without the initial "{"Data:" and just begin immediately writing the name for all objects, this problem does not occur and I can get a list of all the names of the products using the script above. However I want to use a loop to identify certain objects using a user input I will later add. Can anyone elucidate this for me?

Body:
forEach is a method for arrays, not objects. What your code does is that it tries to forEach through the JSON itself. So you need to get the objects "Data" value which is the acutal array
 You can acheiv that throught objectName.propertyName or objectName["propertyName"]

so your code should look this this:

Data.Data.forEach(function(Data) {
  output += `<li>${Data.Name}</li>`;
});

or

Data["Data"].forEach(function(Data) {
  output += `<li>${Data.Name}</li>`;
});

objectName["propertyName"] can be useful when trying to access keys that look this this: "Data-new"


问:
Finding two non-subsequent elements in array which sum is maximal - interview question
The question is similar to here, besides:

We are looking for the maximum.

The answer can contain the first or last element of the array (but not both - because we consider them as adjacent).

My attempt:

I think of using the same idea of RomCoo in the link above, but adjust it to this problem:

Find the largest number.

Find the second largest that is not a neighbour of the first. Then build the sum.

Calculate the sum of both neighbours of the first number. Check if its larger then the first sum.
If not: take the first sum, otherwise take the second one.

I believe that the pairs on steps (2) and (3) are the only ones who can make the largest sum, but I can't formally prove it.

If this correct how can you formally prove it?

And if not, how do you solve it?

答:
I guess the question is "somewhat" similar to 1031 LeetCode question, which you can see it in this link:

Python

class Solution:
    def maxSumTwoNoOverlap(self, nums, l, m):
        for index in range(1, len(nums)):
            nums[index] += nums[index - 1]
        largest = nums[l + m - 1]
        l_max, m_max = nums[l - 1], nums[m - 1]
        for index in range(l + m, len(nums)):
            l_max = max(l_max, nums[index - m] - nums[index - l - m])
            m_max = max(m_max, nums[index - l] - nums[index - l - m])
            largest = max(largest, l_max + nums[index] - nums[index - m], m_max + nums[index] - nums[index - l])

        return largest

```
<h3>Java</h3>
<pre class="lang-java prettyprint-override"><code>class Solution {
    public int maxSumTwoNoOverlap(int[] nums, int l, int m) {
        for (int index = 1; index < nums.length; index++)
            nums[index] += nums[index - 1];

        int largest = nums[l + m - 1];
        int lMax = nums[l - 1];
        int mMax = nums[m - 1];

        for (int index = l + m; index < nums.length; index++) {
            lMax = Math.max(lMax, nums[index - m] - nums[index - l - m]);
            mMax = Math.max(mMax, nums[index - l] - nums[index - l - m]);
            largest = Math.max(largest, Math.max(lMax + nums[index] - nums[index - m], mMax + nums[index] - nums[index - l]));
        }

        return largest;
    }
}
</code>```

For your question, you are gonna have to keep a minimum distance of 2 as you scan your array so that the neighboring section would be addressed. For instance, you maximize for index and index + 2 as you scan or index - 2 and index.

Reference

Here is lee215's answer in Java/Python/C++

Body:
I guess the question is "somewhat" similar to 1031 LeetCode question, which you can see it in this link:

Python

class Solution:
    def maxSumTwoNoOverlap(self, nums, l, m):
        for index in range(1, len(nums)):
            nums[index] += nums[index - 1]
        largest = nums[l + m - 1]
        l_max, m_max = nums[l - 1], nums[m - 1]
        for index in range(l + m, len(nums)):
            l_max = max(l_max, nums[index - m] - nums[index - l - m])
            m_max = max(m_max, nums[index - l] - nums[index - l - m])
            largest = max(largest, l_max + nums[index] - nums[index - m], m_max + nums[index] - nums[index - l])

        return largest

Java

class Solution {
    public int maxSumTwoNoOverlap(int[] nums, int l, int m) {
        for (int index = 1; index < nums.length; index++)
            nums[index] += nums[index - 1];

        int largest = nums[l + m - 1];
        int lMax = nums[l - 1];
        int mMax = nums[m - 1];

        for (int index = l + m; index < nums.length; index++) {
            lMax = Math.max(lMax, nums[index - m] - nums[index - l - m]);
            mMax = Math.max(mMax, nums[index - l] - nums[index - l - m]);
            largest = Math.max(largest, Math.max(lMax + nums[index] - nums[index - m], mMax + nums[index] - nums[index - l]));
        }

        return largest;
    }
}

For your question, you are gonna have to keep a minimum distance of 2 as you scan your array so that the neighboring section would be addressed. For instance, you maximize for index and index + 2 as you scan or index - 2 and index.

Reference

Here is lee215's answer in Java/Python/C++


问:
Change table data in 2nd table in same view upon selecting the row in 1st table
I wanted to know how can we change the cell.textLabel.text of the second table, when we select the row of the first table.. P.S : Both the tables are in the same View..so i cant push another view controller to cover up the present view.

Example : I have some 10 rows of data in the first table, upon selecting 1st row in table 1 it should display "table1, row1 " or any other string.. in the first row of the second table., when I select 2nd row of first table.., the first row of the second table should now display as "table1,row2"

Thanks in advance

答:
```<code>Try something likethis....
Have a string NSString *str=[[NSString alloc]init];

    for the first table

         didSelectRowAtindexPath
            {
            if(indexpath.row==1)
            str=@"1 row 1 table";
            if(indexpath.row==2)
            str=@"2 row 1 table");
            [table2 reloadData];
            }
        In table2
        cellforRowAtindexPath
        {
        cell.textLabel.text=str;
        }
</code>```

ContentLicense: CC BY-SA 3.0


问:
how can i control frames in opencv?
how can i control frames in opencv?
here you insert the url of a video in the internet/local and this streams it to you.but voice and video are not Coordinated.video is faster than voice :/</p>

```<code>import cv2
import numpy as np
from ffpyplayer.player import MediaPlayer

def getVideoSource(source, width, height):
    cap = cv2.VideoCapture(source)
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
    return cap

def main():
    url=input('enter url: ')
    sourcePath = url
    camera = getVideoSource(sourcePath, 720, 480)
    player = MediaPlayer(sourcePath)

    while True:

        ret, frame = camera.read()
        audio_frame, val = player.get_frame()

        if (ret == 0):
            print("End of video")
            break

        frame = cv2.resize(frame, (720, 480))
        cv2.imshow('Camera', frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

        if val != 'eof' and audio_frame is not None:
            frame, t = audio_frame
            print("Frame:" + str(frame) + " T: " + str(t))

    camera.release()
    cv2.destroyAllWindows()

if __name__ == "__main__":
    main()

</code>```

答:
It seems you can't control when to play audio because it uses SDL to play it in separated thread but get_frame() gives tuple (frame, val) and frame is (image, time_when_to_display_image) and you should use this time_when_to_display_image to control when to display image.

And all this code doesn't need cv2.VideoCapture() to get frame.

I use cv2 only to display it but you can use any GUI to create window to display it.

I use current_time to get next frame without using time.sleep() because video wasn't smooth.

BTW: You can use player.set_size(720, 480) to resize frame.

```<code>from ffpyplayer.player import MediaPlayer
import cv2
import numpy as np
import time

filename = 'video.mp4'

player = MediaPlayer(filename)
player.set_size(720, 480)  # resize it
#player.set_size(400, 300)

start_time = time.time()
frame_time = start_time + 0

while True:
    current_time = time.time()

    # check if it is time to get next frame
    if current_time >= frame_time:

        # get next frame
        frame, val = player.get_frame()

        if val != 'eof' and frame is not None:
            image, pts = frame
            w, h = image.get_size()

            # convert to array width, height
            img = np.asarray(image.to_bytearray()[0]).reshape(h,w,3)

            # convert RGB to BGR because `cv2` need it to display it
            img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)

            cv2.imshow('video', img)

            frame_time = start_time + pts

    if cv2.waitKey(1) & 0xff == ord('q'):
        break

cv2.destroyAllWindows()
player.close_player()
</code>```

EDIT: I found that get_frame() gives (frame, val) and this val can be used in time.sleep(val). And probably it should sleep before displaying frame, not after displaying it.

```<code>from ffpyplayer.player import MediaPlayer
import cv2
import numpy as np
import time

filename = 'video.mp4'

player = MediaPlayer(filename)
player.set_size(720, 480)
#player.set_size(400, 300)

while True:
    frame, val = player.get_frame()
    if val != 'eof' and frame is not None:
        image, pts = frame
        w, h = image.get_size()

        # convert to array width, height
        img = np.asarray(image.to_bytearray()[0]).reshape(h,w,3)

        # convert RGB to BGR because `cv2` need it to display it
        img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)

        time.sleep(val)
        cv2.imshow('video', img)

    if cv2.waitKey(1) & 0xff == ord('q'):
        break

cv2.destroyAllWindows()
player.close_player()
</code>```

EDIT: Code using tkinter to display it.

```<code>from ffpyplayer.player import MediaPlayer
import tkinter as tk
from PIL import Image, ImageTk
import time

# -- functions ---

def update_frame():
    global photo  # solution for BUG in PhotoImage

    frame, val = player.get_frame()
    if val != 'eof' and frame is not None:
        image, pts = frame
        w, h = image.get_size()

        data = image.to_bytearray()[0]
        img = Image.frombytes("RGB", (w,h), bytes(data))
        photo = ImageTk.PhotoImage(img)

        time.sleep(val)
        label['image'] = photo

    root.after(1, update_frame)  # again after `1ms` without blocking `mainloop()`

# --- main ---

filename = 'video.mp4'

player = MediaPlayer(filename)
player.set_size(720, 480)
#player.set_size(400, 300)

root = tk.Tk()

label = tk.Label(root)
label.pack()

root.bind('q', lambda event:root.destroy())

update_frame()

root.mainloop()
player.close_player()
</code>```

Title: how can i control frames in opencv?

Body:
how can i control frames in opencv?
here you insert the url of a video in the internet/local and this streams it to you.but voice and video are not Coordinated.video is faster than voice :/

import cv2
import numpy as np
from ffpyplayer.player import MediaPlayer

def getVideoSource(source, width, height):
    cap = cv2.VideoCapture(source)
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
    return cap

def main():
    url=input('enter url: ')
    sourcePath = url
    camera = getVideoSource(sourcePath, 720, 480)
    player = MediaPlayer(sourcePath)

    while True:

        ret, frame = camera.read()
        audio_frame, val = player.get_frame()

        if (ret == 0):
            print("End of video")
            break

        frame = cv2.resize(frame, (720, 480))
        cv2.imshow('Camera', frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

        if val != 'eof' and audio_frame is not None:
            frame, t = audio_frame
            print("Frame:" + str(frame) + " T: " + str(t))

    camera.release()
    cv2.destroyAllWindows()

if __name__ == "__main__":
    main()

Body:
It seems you can't control when to play audio because it uses SDL to play it in separated thread but get_frame() gives tuple (frame, val) and frame is (image, time_when_to_display_image) and you should use this time_when_to_display_image to control when to display image.

And all this code doesn't need cv2.VideoCapture() to get frame.

I use cv2 only to display it but you can use any GUI to create window to display it.

I use current_time to get next frame without using time.sleep() because video wasn't smooth.

BTW: You can use player.set_size(720, 480) to resize frame.

from ffpyplayer.player import MediaPlayer
import cv2
import numpy as np
import time

filename = 'video.mp4'

player = MediaPlayer(filename)
player.set_size(720, 480)  # resize it
#player.set_size(400, 300)

start_time = time.time()
frame_time = start_time + 0

while True:
    current_time = time.time()

    # check if it is time to get next frame
    if current_time >= frame_time:

        # get next frame
        frame, val = player.get_frame()

        if val != 'eof' and frame is not None:
            image, pts = frame
            w, h = image.get_size()

            # convert to array width, height
            img = np.asarray(image.to_bytearray()[0]).reshape(h,w,3)

            # convert RGB to BGR because `cv2` need it to display it
            img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)

            cv2.imshow('video', img)

            frame_time = start_time + pts

    if cv2.waitKey(1) & 0xff == ord('q'):
        break

cv2.destroyAllWindows()
player.close_player()

EDIT: I found that get_frame() gives (frame, val) and this val can be used in time.sleep(val). And probably it should sleep before displaying frame, not after displaying it.

from ffpyplayer.player import MediaPlayer
import cv2
import numpy as np
import time

filename = 'video.mp4'

player = MediaPlayer(filename)
player.set_size(720, 480)
#player.set_size(400, 300)

while True:
    frame, val = player.get_frame()
    if val != 'eof' and frame is not None:
        image, pts = frame
        w, h = image.get_size()

        # convert to array width, height
        img = np.asarray(image.to_bytearray()[0]).reshape(h,w,3)

        # convert RGB to BGR because `cv2` need it to display it
        img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)

        time.sleep(val)
        cv2.imshow('video', img)

    if cv2.waitKey(1) & 0xff == ord('q'):
        break

cv2.destroyAllWindows()
player.close_player()

EDIT: Code using tkinter to display it.

from ffpyplayer.player import MediaPlayer
import tkinter as tk
from PIL import Image, ImageTk
import time

# -- functions ---

def update_frame():
    global photo  # solution for BUG in PhotoImage

    frame, val = player.get_frame()
    if val != 'eof' and frame is not None:
        image, pts = frame
        w, h = image.get_size()

        data = image.to_bytearray()[0]
        img = Image.frombytes("RGB", (w,h), bytes(data))
        photo = ImageTk.PhotoImage(img)

        time.sleep(val)
        label['image'] = photo

    root.after(1, update_frame)  # again after `1ms` without blocking `mainloop()`

# --- main ---

filename = 'video.mp4'

player = MediaPlayer(filename)
player.set_size(720, 480)
#player.set_size(400, 300)

root = tk.Tk()

label = tk.Label(root)
label.pack()

root.bind('q', lambda event:root.destroy())

update_frame()

root.mainloop()
player.close_player()


问:
error problem with 1582 Incorrect parameter count in the call to native function 'ISNULL'
i have 2 tables one (visits) and other one (patients) with relationship by mysql (patients) is with PK as patients.pid and visits.pid as index
and i wanted to use code in my vb.net app to get the last datetime record to check the patient if still inside the hospital admitted or discharge
so far i have this code with help of you guys

SELECT a.pid,MAX(ISNULL(b.sdat,'1901-01-01')),MAX(ISNULL(b.edat,'1901-01-01')) from patients a left join visits b on a.pid=b.pid Where ddatediff(now(),b.edat) <=365 group by a.pid```

but when i execute in sql builder using php myadmin  or another app i get error
(1582 - Incorrect parameter count in the call to native function 'ISNULL')
i tried to find out the error cause but no luck until now

答:
MySQL's ISNULL() is a comparison function, that takes a single argument and returns 1 if it is NULL. I think that you meant IFNULL() - or the more standard COALESCE().

I would also suggest moving the check outside of the aggregate function, for better efficiency:

```<code>COALESCE(MAX(b.sdat),'1901-01-01'),
COALESCE(MAX(b.edat),'1901-01-01')
</code>```

Body:
i have 2 tables one (visits) and other one (patients) with relationship by mysql (patients) is with PK as patients.pid and visits.pid as index
and i wanted to use code in my vb.net app to get the last datetime record to check the patient if still inside the hospital admitted or discharge
so far i have this code with help of you guys

SELECT a.pid,MAX(ISNULL(b.sdat,'1901-01-01')),MAX(ISNULL(b.edat,'1901-01-01')) from patients a left join visits b on a.pid=b.pid Where ddatediff(now(),b.edat) <=365 group by a.pid

but when i execute in sql builder using php myadmin  or another app i get error
(1582 - Incorrect parameter count in the call to native function 'ISNULL')
i tried to find out the error cause but no luck until now

Body:
MySQL's ISNULL() is a comparison function, that takes a single argument and returns 1 if it is NULL. I think that you meant IFNULL() - or the more standard COALESCE().

I would also suggest moving the check outside of the aggregate function, for better efficiency:

COALESCE(MAX(b.sdat),'1901-01-01'),
COALESCE(MAX(b.edat),'1901-01-01')


问:
Is there a different way to count repetitions in a string except count?
I'm doing CS50 DNA problem, and the python count function keeps returning off values, and I'm not sure why. I tried using find, but my implementation was wrong

```<code>import csv, sys
#check if all arguments are provided
if len(sys.argv) != 3:
    print("Usage: python dna.py data.csv sequence.txt")
    exit()

#sets database to first argument
databaseFile = sys.argv[1]

#sequence is second file
sequenceFile = sys.argv[2]

#make list for data
data = []
database = []

#open csv file
with open(databaseFile, 'r') as csvfile:

    #make reader
    csvreader = csv.reader(csvfile)

    #read in the headers
    fields = next(csvreader)
    fields.remove("name")

    #read in the rows of data in database
    for row in csvreader:
        #add data, with names and database with just numbers
        data.append(row)
        database.append([int(i) for i in row[1:]])

#open sequence
sequence = open(sequenceFile, 'r').readline()

results = []
#for add repetitions to results
for field in fields:
    results.append(sequence.count(field))

print(results)
found = False
for i in database:
    if (results == i):
        print(data[i])
        found = True
if not found:
    print("No match")
</code>```

Which other method can i use to count the repetitions of 'field' in sequence
for example when i load:

python dna.py databases/large.csv sequences/19.txt
I get results as:
[47, 40, 34, 11, 24, 31, 60, 26]
No match

instead of fred
which is: [37, 40, 10, 6, 5, 10, 28, 8]

problem can be found at: https://cs50.harvard.edu/x/2020/psets/6/dna/

答:
Using a regular expression to find consecutive matches.

```<code>import re

s = 'AGTCAGTCAGTCTTTTAGCTAGTC'
STR = 'AGTC'

strands = re.findall(f'(?:{STR})+', s)
print(strands) # prints `['AGTCAGTCAGTC', 'AGTC']`

my_max = max(map(len, strands))//len(STR)
print(my_max)
</code>```

Prints 3 which is correct as it appears 3 times consecutively (and once more at the end of the sequence).

I hope this snippet can help for this portion of your problems.

Body:
I'm doing CS50 DNA problem, and the python count function keeps returning off values, and I'm not sure why. I tried using find, but my implementation was wrong

import csv, sys
#check if all arguments are provided
if len(sys.argv) != 3:
    print("Usage: python dna.py data.csv sequence.txt")
    exit()

#sets database to first argument
databaseFile = sys.argv[1]

#sequence is second file
sequenceFile = sys.argv[2]

#make list for data
data = []
database = []

#open csv file
with open(databaseFile, 'r') as csvfile:

    #make reader
    csvreader = csv.reader(csvfile)

    #read in the headers
    fields = next(csvreader)
    fields.remove("name")

    #read in the rows of data in database
    for row in csvreader:
        #add data, with names and database with just numbers
        data.append(row)
        database.append([int(i) for i in row[1:]])

#open sequence
sequence = open(sequenceFile, 'r').readline()

results = []
#for add repetitions to results
for field in fields:
    results.append(sequence.count(field))

print(results)
found = False
for i in database:
    if (results == i):
        print(data[i])
        found = True
if not found:
    print("No match")

Which other method can i use to count the repetitions of 'field' in sequence
for example when i load:

python dna.py databases/large.csv sequences/19.txt
I get results as:
[47, 40, 34, 11, 24, 31, 60, 26]
No match

instead of fred
which is: [37, 40, 10, 6, 5, 10, 28, 8]

problem can be found at: https://cs50.harvard.edu/x/2020/psets/6/dna/

Body:
Using a regular expression to find consecutive matches.

import re

s = 'AGTCAGTCAGTCTTTTAGCTAGTC'
STR = 'AGTC'

strands = re.findall(f'(?:{STR})+', s)
print(strands) # prints `['AGTCAGTCAGTC', 'AGTC']`

my_max = max(map(len, strands))//len(STR)
print(my_max)

Prints 3 which is correct as it appears 3 times consecutively (and once more at the end of the sequence).

I hope this snippet can help for this portion of your problems.


问:
Let a container use the OpenJDK and libraries of an existing container
I am doing some experiments with my thesis involving the cold start problem that occurs with containers. My test application is a spring boot application that is build on the openjdk image. The first thing I want to try to resolve the problem of cold start, is the following:

Have a container ready, in the container is the openjdk and the libraries that the springboot app uses. I start my other container, using the ipc and networknamespace of the already existing container, and then be able to use the openjdk and the libraries of this container to run the jar file.

I am not exactly sure on how to achieve this? Can i achieve this by using volumes or should i be looking for a completely different approach?

On a another note, if i want x containers to run, i will make sure there are x pre-existing containers running. This is to make sure that every container has its own specific librarycontainer to work with. Would this be okay ?

In short, any way that I can speed up the spring boot application by using a second containers that is connected through ipc/net; would be helpfull to my problem.

答:
To answer your first question:

I am not exactly sure on how to achieve this? Can I achieve this by using volumes or should I be looking for a completely different approach?

This has to be balanced with the actually capabilities of your infrastructure.

One could have a full optical fibre cable network, a Docker repository in this network and so a bandwidth than can allow for "big" images

One could have a poor connection to its Docker repository, and so need extra small images but a quick connection with the libraries repositories

One could have a blue/green deployment technique and care about neither the size of the images and layer nor the boot time

One thing is, if you care about image and layer size this is good and this is definitely a good practice advised by Docker, but all depends of your needs. The recommendation about keeping images and layers small if for images that you'll distribute. If this is your own image for your own application, then, you should act upon your needs.

Here is for a little bit of my own experience: in a company I was working on, we need the database to be synchronised back from the production to user acceptance test and developer environment.

Because of the size of the production environment, importing the data from an SQL file in the entrypoint of the container took around twenty minutes. This might have been alright for the UAT environment, but, was not for the developer's one.

So after trying all sort of minor improvement in the SQL file (like disabling foreign keys checks and the like), I came up with a totally new approach: I created a big fatty image, in a nightly build that would contain the database already. This is, indeed, against all good practice of Docker, but the bandwidth at the office allowed the container to start in a matter of 5 minutes at worse, compared to the twenty that was before.

So I indeed ended up with a build time of my Docker SQL image being humongous, but a download time acceptable, considering the bandwidth available and a run time reduced to the maximum.

This is taking the advantage of the fact that the build of an image only happens for once, while the start time will happens for all the containers derivating from this image.

To answer your second question:

On a another note, if I want x containers to run, I will make sure there are x pre-existing containers running. This is to make sure that every container has its own specific librarycontainer to work with. Would this be okay?

I would say the answer is: no.

Even in a micro services architecture, each service should be able to do something. As I understand it, you actual not-library-container are unable to do anything because they are tightly coupled to the pre-existence of another container.

This said there are two things that might be of interest to you:

First: remember that you can always build from another pre-existing image, even your own.

Given this would be your library-container Dockerfile

FROM: openjdk:8-jdk-alpine
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","/app.jar"]
```
<p><sup><em>Credits: https://spring.io/guides/topicals/spring-boot-docker/#_a_basic_dockerfile</em></sup></p>
<p>And that you build it via</p>
<pre class="lang-sh prettyprint-override"><code>docker build -t my/spring-boot .
</code>```

Then you can have another container build on top of that image:

```<code>FROM: my/spring-boot
COPY some-specific-lib lib.jar
</code>```

Secondly: there is a nice technique in Docker to deal with libraries that is called multi-stage builds and that can be used exactly for your case.

FROM openjdk:8-jdk-alpine as build
WORKDIR /workspace/app

COPY mvnw .
COPY .mvn .mvn
COPY pom.xml .
COPY src src

RUN ./mvnw install -DskipTests
RUN mkdir -p target/dependency && (cd target/dependency; jar -xf ../*.jar)

FROM openjdk:8-jdk-alpine
VOLUME /tmp
ARG DEPENDENCY=/workspace/app/target/dependency
COPY --from=build ${DEPENDENCY}/BOOT-INF/lib /app/lib
COPY --from=build ${DEPENDENCY}/META-INF /app/META-INF
COPY --from=build ${DEPENDENCY}/BOOT-INF/classes /app
ENTRYPOINT ["java","-cp","app:app/lib/*","hello.Application"]
```

Credits: https://spring.io/guides/topicals/spring-boot-docker/#_multi_stage_build

And as you can see in the credits of this multi-stage build, there is even a reference to this technique in the guide of the Spring website.

Body:
To answer your first question:

I am not exactly sure on how to achieve this? Can I achieve this by using volumes or should I be looking for a completely different approach?

This has to be balanced with the actually capabilities of your infrastructure.

One could have a full optical fibre cable network, a Docker repository in this network and so a bandwidth than can allow for "big" images

One could have a poor connection to its Docker repository, and so need extra small images but a quick connection with the libraries repositories

One could have a blue/green deployment technique and care about neither the size of the images and layer nor the boot time

One thing is, if you care about image and layer size this is good and this is definitely a good practice advised by Docker, but all depends of your needs. The recommendation about keeping images and layers small if for images that you'll distribute. If this is your own image for your own application, then, you should act upon your needs.

Here is for a little bit of my own experience: in a company I was working on, we need the database to be synchronised back from the production to user acceptance test and developer environment.

Because of the size of the production environment, importing the data from an SQL file in the entrypoint of the container took around twenty minutes. This might have been alright for the UAT environment, but, was not for the developer's one.

So after trying all sort of minor improvement in the SQL file (like disabling foreign keys checks and the like), I came up with a totally new approach: I created a big fatty image, in a nightly build that would contain the database already. This is, indeed, against all good practice of Docker, but the bandwidth at the office allowed the container to start in a matter of 5 minutes at worse, compared to the twenty that was before.

So I indeed ended up with a build time of my Docker SQL image being humongous, but a download time acceptable, considering the bandwidth available and a run time reduced to the maximum.

This is taking the advantage of the fact that the build of an image only happens for once, while the start time will happens for all the containers derivating from this image.

To answer your second question:

On a another note, if I want x containers to run, I will make sure there are x pre-existing containers running. This is to make sure that every container has its own specific librarycontainer to work with. Would this be okay?

I would say the answer is: no.

Even in a micro services architecture, each service should be able to do something. As I understand it, you actual not-library-container are unable to do anything because they are tightly coupled to the pre-existence of another container.

This said there are two things that might be of interest to you:

First: remember that you can always build from another pre-existing image, even your own.

Given this would be your library-container Dockerfile

FROM: openjdk:8-jdk-alpine
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","/app.jar"]

Credits: https://spring.io/guides/topicals/spring-boot-docker/#_a_basic_dockerfile

And that you build it via

docker build -t my/spring-boot .

Then you can have another container build on top of that image:

FROM: my/spring-boot
COPY some-specific-lib lib.jar

Secondly: there is a nice technique in Docker to deal with libraries that is called multi-stage builds and that can be used exactly for your case.

FROM openjdk:8-jdk-alpine as build
WORKDIR /workspace/app

COPY mvnw .
COPY .mvn .mvn
COPY pom.xml .
COPY src src

RUN ./mvnw install -DskipTests
RUN mkdir -p target/dependency && (cd target/dependency; jar -xf ../*.jar)

FROM openjdk:8-jdk-alpine
VOLUME /tmp
ARG DEPENDENCY=/workspace/app/target/dependency
COPY --from=build ${DEPENDENCY}/BOOT-INF/lib /app/lib
COPY --from=build ${DEPENDENCY}/META-INF /app/META-INF
COPY --from=build ${DEPENDENCY}/BOOT-INF/classes /app
ENTRYPOINT ["java","-cp","app:app/lib/*","hello.Application"]

Credits: https://spring.io/guides/topicals/spring-boot-docker/#_multi_stage_build

And as you can see in the credits of this multi-stage build, there is even a reference to this technique in the guide of the Spring website.


问:
Simple Banking Application in Visual Basic
I hope that someone can point me in the right direction, as I am new to programming.

I made a basic banking application. It displays a balance for the account, has a textbox for the user to enter the amount, and 2 buttons: one for depositing an amount into the account and one for withdrawing an amount. If the user tries to deposit or withdraw a negative number or "0" then it gives an error that it isn't a valid amount. If the user tries to withdraw more than is in the account, it gives an error that they cannot withdraw more money than is in the account.

My problem is that all the error messages are working for the deposit button, but not for the withdraw button. I used nested If structure, output to a label at the bottom.

I tried using breakpoints to examine my variables, but didn't find any issues.

I don't really want the answer, just some help to understand why the Deposit button will give the error but the Withdraw button won't show either error.

```<code>Public Class Form1
    ' Prologue
    ' This is a simple banking application.
    ' It displays a balance for the account, calculates deposits and withdraws, and gives errors for invalid amounts and overdraws

    ' Modular Declarations
    Dim mdecBalance As Decimal = 1000

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' Output
        lblBalance.Text = mdecBalance.ToString("c")
    End Sub

    Private Sub btnDeposit_Click(sender As Object, e As EventArgs) Handles btnDeposit.Click
        ' Declarations
        Dim decDeposit As Decimal
        Dim strDepProblem As String

        ' Input
        decDeposit = txtAmount.Text

        ' Processing
        If decDeposit > 0 Then
            mdecBalance = mdecBalance + decDeposit
        Else
            If decDeposit <= 0 Then
                strDepProblem = "That is not a valid amount to deposit"
            End If
        End If

        ' Output
        lblBalance.Text = mdecBalance.ToString("c")
        lblMessage.Text = strDepProblem

    End Sub

    Private Sub btnWithdraw_Click(sender As Object, e As EventArgs) Handles btnWithdraw.Click
        ' Declarations
        Dim decWithdraw As Decimal
        Dim strWithdrawNegative As String
        Dim strWithdrawMoreThan As String

        ' Input
        decWithdraw = txtAmount.Text

        ' Processing
        If decWithdraw > 0 Then
            mdecBalance = mdecBalance - decWithdraw
        Else
            If decWithdraw <= 0 Then
                strWithdrawNegative = "Cannot use 0 or negative numbers"
            Else
                If decWithdraw > mdecBalance Then
                    strWithdrawMoreThan = "Cannot withdraw more than you have"
                End If
            End If
        End If

        ' Output
        lblBalance.Text = mdecBalance.ToString("c")
        lblMessage.Text = strWithdrawNegative
        lblMessage.Text = strWithdrawMoreThan
    End Sub
End Class
</code>```

答:
You're trying to do too much in too complex a way. Write your functions so they have this pattern:

```<code>If something is no good Then
  Say it's no good
  Stop processing

If something else is no good Then
  Say this other thing is no good
  Stop processing

Now that you've checked every possible error condition, we're all good to go
Do the work
</code>```

This means you write your code like:

```<code>     Private Sub btnDeposit_Click(sender As Object, e As EventArgs) Handles btnDeposit.Click

        lblMessage.Text = "" 'be optimistic; nothing will go wrong

        Dim decDeposit = Convert.ToDecimal(txtAmount.Text) 'be explicit when converting data. Turn on Option Strict and Option Explicit

        If decDeposit = 0 Then
          lblMessage.Text = "Cannot deposit 0"
          Return 'stop processing
        End If

        If decDeposit < 0 Then
          errorLabel.Text = "Cannot deposit negative"
          Return 'stop processing
        End If

        mdecBalance = mdecBalance + decDeposit

        lblBalance.Text = mdecBalance.ToString("c")
        lblMessage.Text = "Deposit ok"

    End Sub
</code>```

If you're having multiple nested If If If .. you're headed for trouble. This simplified workflow of checking and making sure everything is OK right at the start and only proceeding if it is is generally a simpler way to work.

If you want to tell the user every mistake they made all in one go, you can work like this:

```<code>
    lblMessage.Text = ""

    If testForBad1 Then lblMessage.Text &= "Bad thing 1 happened"

    If testForBad2 Then lblMessage.Text &= "Bad thing 2 happened"

    If testForBad3 Then lblMessage.Text &= "Bad thing 3 happened"

    If lblMessage.Text <> "" Then Return 'any errors will put a text

</code>```

We still have only one nest level here; very simple and easy to follow code

Body:
I hope that someone can point me in the right direction, as I am new to programming.

I made a basic banking application. It displays a balance for the account, has a textbox for the user to enter the amount, and 2 buttons: one for depositing an amount into the account and one for withdrawing an amount. If the user tries to deposit or withdraw a negative number or "0" then it gives an error that it isn't a valid amount. If the user tries to withdraw more than is in the account, it gives an error that they cannot withdraw more money than is in the account.

My problem is that all the error messages are working for the deposit button, but not for the withdraw button. I used nested If structure, output to a label at the bottom.

I tried using breakpoints to examine my variables, but didn't find any issues.

I don't really want the answer, just some help to understand why the Deposit button will give the error but the Withdraw button won't show either error.

Public Class Form1
    ' Prologue
    ' This is a simple banking application.
    ' It displays a balance for the account, calculates deposits and withdraws, and gives errors for invalid amounts and overdraws

    ' Modular Declarations
    Dim mdecBalance As Decimal = 1000

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' Output
        lblBalance.Text = mdecBalance.ToString("c")
    End Sub

    Private Sub btnDeposit_Click(sender As Object, e As EventArgs) Handles btnDeposit.Click
        ' Declarations
        Dim decDeposit As Decimal
        Dim strDepProblem As String

        ' Input
        decDeposit = txtAmount.Text

        ' Processing
        If decDeposit > 0 Then
            mdecBalance = mdecBalance + decDeposit
        Else
            If decDeposit <= 0 Then
                strDepProblem = "That is not a valid amount to deposit"
            End If
        End If

        ' Output
        lblBalance.Text = mdecBalance.ToString("c")
        lblMessage.Text = strDepProblem

    End Sub

    Private Sub btnWithdraw_Click(sender As Object, e As EventArgs) Handles btnWithdraw.Click
        ' Declarations
        Dim decWithdraw As Decimal
        Dim strWithdrawNegative As String
        Dim strWithdrawMoreThan As String

        ' Input
        decWithdraw = txtAmount.Text

        ' Processing
        If decWithdraw > 0 Then
            mdecBalance = mdecBalance - decWithdraw
        Else
            If decWithdraw <= 0 Then
                strWithdrawNegative = "Cannot use 0 or negative numbers"
            Else
                If decWithdraw > mdecBalance Then
                    strWithdrawMoreThan = "Cannot withdraw more than you have"
                End If
            End If
        End If

        ' Output
        lblBalance.Text = mdecBalance.ToString("c")
        lblMessage.Text = strWithdrawNegative
        lblMessage.Text = strWithdrawMoreThan
    End Sub
End Class

Body:
You're trying to do too much in too complex a way. Write your functions so they have this pattern:

If something is no good Then
  Say it's no good
  Stop processing

If something else is no good Then
  Say this other thing is no good
  Stop processing

Now that you've checked every possible error condition, we're all good to go
Do the work

This means you write your code like:

     Private Sub btnDeposit_Click(sender As Object, e As EventArgs) Handles btnDeposit.Click

        lblMessage.Text = "" 'be optimistic; nothing will go wrong

        Dim decDeposit = Convert.ToDecimal(txtAmount.Text) 'be explicit when converting data. Turn on Option Strict and Option Explicit

        If decDeposit = 0 Then
          lblMessage.Text = "Cannot deposit 0"
          Return 'stop processing
        End If

        If decDeposit < 0 Then
          errorLabel.Text = "Cannot deposit negative"
          Return 'stop processing
        End If

        mdecBalance = mdecBalance + decDeposit

        lblBalance.Text = mdecBalance.ToString("c")
        lblMessage.Text = "Deposit ok"

    End Sub

If you're having multiple nested If If If .. you're headed for trouble. This simplified workflow of checking and making sure everything is OK right at the start and only proceeding if it is is generally a simpler way to work.

If you want to tell the user every mistake they made all in one go, you can work like this:

    lblMessage.Text = ""

    If testForBad1 Then lblMessage.Text &= "Bad thing 1 happened"

    If testForBad2 Then lblMessage.Text &= "Bad thing 2 happened"

    If testForBad3 Then lblMessage.Text &= "Bad thing 3 happened"

    If lblMessage.Text <> "" Then Return 'any errors will put a text

We still have only one nest level here; very simple and easy to follow code


问:
How to check if any application is running in docker container?
How to check if any application is running in docker container ? What is the command for it.</p>

答:
In only on line:

```<code>docker exec -it <name-of-your-container> pgrep -fl <application-name-here>
</code>```

pgrep - look up or signal processes based on name and other attributes

Body:
In only on line:

docker exec -it <name-of-your-container> pgrep -fl <application-name-here>

pgrep - look up or signal processes based on name and other attributes


问:
Replace words in the body text
Is there a way to replace the normal text within a table element that is placed within the body of the HTML?

Like replacing "hello" with "hi"?

Please only use JavaScript without jQuery.

答:
Sometimes changing document.body.innerHTML breaks some JS scripts on page. Here is version, that only changes content of text elements:

function replaceRecursively(element, from, to) {
    if (element.childNodes.length) {
        element.childNodes.forEach(child => replaceRecursively(child, from, to));
    } else {
        const cont = element.textContent;
        if (cont) element.textContent = cont.replace(from, to);
    }
};

replaceRecursively(document.body, new RegExp("hello", "g"), "hi");
```

Title: Replace words in the body text


问:
Database Filter Issue On Laravel
I am Using Laravel

below mentioned is one of my db table columns
:

```<code>{ "body": { "age": { "dob": "1960-01-28", "age_in_years": 60, "dob_computed": false }, "gender": "female", "address": { "street": "No.341,KC De silvapura", "country": "LK", "locality": "Thimbirigaskatuwa", "postcode": "N/A" }, "comment": "", "id_type": "NID", "id_number": 869000000000, "last_name": "Dayawansa", "member_id": "", "first_name": "jj", "preferred_name": "", "contact_details": { "email": "", "phone_number_alternate": "", "phone_number_preferred": 716900761 }, "consent_obtained": true, "alternate_contacts_details": { "name": "", "email": "", "phone_alternate": "", "phone_preferred": "" } }, "meta": { "end_time": "2019-09-06", "start_time": "2019-09-06", "registered_by": "24f57630-a102-11ea-a415-23a06eeb8904" } }
</code>```

my code is
My controller
:

```<code> $start_date = $request->has('startDate') ? $request->get('startDate') : Carbon::now()->subDays(30)->format('m/d/Y');
 $end_date = $request->has('endDate') ? Carbon::parse($request->get('endDate'))->addDays(1)->format('m/d/Y') : Carbon::now()->addDays(1)->format('m/d/Y');
</code>```

if i use created at it works

```<code>$participants = Participant::Where('created_at', '>=', $start_date)
        ->where('created_at', '<=', $end_date);
</code>```

if is use start_time which is inside a array it returns empty

```<code>$participants = Participant::Where('data->meta->start_time', '>=', $start_date)
        ->where('data->meta->start_time', '<=', $end_date);
</code>```

this isn't working
any suggestion where am i wrong ?

答:
I have tested your code and I think you should change your date format and you should receive startDate and endDate in the same format form request as your column value has. Like, you have the start_time something like that "start_time": "2019-09-06" in your DB. So, use the same date format when you will compare it.

Test your code in this way.

```<code>$start_date =  Carbon::parse('2019-09-06')->format('Y-m-d');
$end_date = Carbon::parse('2019-09-10')->format('Y-m-d');
</code>```

You will get a response but if you use the below format then you will not receive any response.

```<code>$start_date =  Carbon::parse('2019-09-06')->format('m/d/Y');
$end_date = Carbon::parse('2019-09-10')->format('m/d/Y');
</code>```

Your query is fine. Just make sure that your json column name is data.

```<code>$participants = Participant::where('data->meta->start_time', '>=', $start_date)
                ->where('data->meta->start_time', '<=', $end_date)->get();
</code>```

Title: Database Filter Issue On Laravel

Body:
I am Using Laravel

below mentioned is one of my db table columns
:

{ "body": { "age": { "dob": "1960-01-28", "age_in_years": 60, "dob_computed": false }, "gender": "female", "address": { "street": "No.341,KC De silvapura", "country": "LK", "locality": "Thimbirigaskatuwa", "postcode": "N/A" }, "comment": "", "id_type": "NID", "id_number": 869000000000, "last_name": "Dayawansa", "member_id": "", "first_name": "jj", "preferred_name": "", "contact_details": { "email": "", "phone_number_alternate": "", "phone_number_preferred": 716900761 }, "consent_obtained": true, "alternate_contacts_details": { "name": "", "email": "", "phone_alternate": "", "phone_preferred": "" } }, "meta": { "end_time": "2019-09-06", "start_time": "2019-09-06", "registered_by": "24f57630-a102-11ea-a415-23a06eeb8904" } }

my code is
My controller
:

 $start_date = $request->has('startDate') ? $request->get('startDate') : Carbon::now()->subDays(30)->format('m/d/Y');
 $end_date = $request->has('endDate') ? Carbon::parse($request->get('endDate'))->addDays(1)->format('m/d/Y') : Carbon::now()->addDays(1)->format('m/d/Y');

if i use created at it works

$participants = Participant::Where('created_at', '>=', $start_date)
        ->where('created_at', '<=', $end_date);

if is use start_time which is inside a array it returns empty

$participants = Participant::Where('data->meta->start_time', '>=', $start_date)
        ->where('data->meta->start_time', '<=', $end_date);

this isn't working
any suggestion where am i wrong ?

Body:
I have tested your code and I think you should change your date format and you should receive startDate and endDate in the same format form request as your column value has. Like, you have the start_time something like that "start_time": "2019-09-06" in your DB. So, use the same date format when you will compare it.

Test your code in this way.

$start_date =  Carbon::parse('2019-09-06')->format('Y-m-d');
$end_date = Carbon::parse('2019-09-10')->format('Y-m-d');

You will get a response but if you use the below format then you will not receive any response.

$start_date =  Carbon::parse('2019-09-06')->format('m/d/Y');
$end_date = Carbon::parse('2019-09-10')->format('m/d/Y');

Your query is fine. Just make sure that your json column name is data.

$participants = Participant::where('data->meta->start_time', '>=', $start_date)
                ->where('data->meta->start_time', '<=', $end_date)->get();