问:
How to connect Two Dark Mode buttons on the same Page?
I have been using two dark mode buttons on my Page. One at menu bar and the other on the Footer.

However, the problem is that whenver I switch to dark mode from any one button the other button doesn't toggles itself.

Say, if I switch the night Mode from Menu bar, then the footer button will keep showing that the Day Mode is enabled.

This is my Website Test Page.

Kindly help in solving my problem with code as well.

Thanks

Code for button on Menu Bar

```<code>
    <label class="switch" style="padding: 23px 0;">
        <input type="checkbox" onclick="themeToggle()" class="theme-switcher">
        <div>
            <span></span>
        </div>

</code>```

Code for button on Footer

```<code>
    <label class="switcher">
    <input type="checkbox" onclick="themeToggle()" class="theme-switcher-2">
    <div>
    <i class="fas fa-sun"></i>
    <i class="fas fa-arrow-left arrow"></i>
    <i class="fas fa-moon"></i>
    </div>
    </label>

</code>```

The js for both the buttons

```<code>
    var tSwitcher = document.getElementsByClassName('theme-switcher');
    let element = document.body;

    let onpageLoad = localStorage.getItem("theme") || "";
    if (onpageLoad != null && onpageLoad == 'dark-mode') {
            for(let i = 0; i<tSwitcher.length; i++){
                    tSwitcher[i].checked = true;
        }

    }

    if(onpageLoad) element.classList.add(onpageLoad);

    function themeToggle() {
        if (event.target.checked) {
          localStorage.setItem('theme', 'dark-mode');
          element.classList.add('dark-mode');
        } else {
          localStorage.setItem('theme', '');
          element.classList.remove('dark-mode');
        }
      }

</code>```

答:
To get both of checkboxes it's better to use querySelectorAll:

querySelectorAll('[class^=theme-switcher]')

LocalStorage doesn't work in snippet but you can check it on your staging site

var tSwitcher = document.querySelectorAll('[class^=theme-switcher]');
let element = document.body;
let onpageLoad = localStorage.getItem("theme") || "";
if (onpageLoad != null && onpageLoad == 'dark-mode') {
      for(let i = 0; i<tSwitcher.length; i++){
          tSwitcher[i].checked = true;
      }

}

if(onpageLoad) element.classList.add(onpageLoad);

function themeToggle() {
    if (event.target.checked) {
      localStorage.setItem('theme', 'dark-mode');
      tSwitcher.forEach(function(el){
          element.classList.add('dark-mode');
          el.checked = true;
      })
    } else {
      localStorage.setItem('theme', '');
      tSwitcher.forEach(function(el){
          element.classList.remove('dark-mode');
          el.checked = false;
       })
    }
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label class="switch" style="padding: 23px 0;">
        <input type="checkbox" onclick="themeToggle()" class="theme-switcher">
        <div>
            <span></span>
        </div>

    <label class="switcher">
    <input type="checkbox" onclick="themeToggle()" class="theme-switcher-2">
    <div>
    <i class="fas fa-sun"></i>
    <i class="fas fa-arrow-left arrow"></i>
    <i class="fas fa-moon"></i>
    </div>
    </label></code>```

Body:
I have been using two dark mode buttons on my Page. One at menu bar and the other on the Footer.

However, the problem is that whenver I switch to dark mode from any one button the other button doesn't toggles itself.

Say, if I switch the night Mode from Menu bar, then the footer button will keep showing that the Day Mode is enabled.

This is my Website Test Page.

Kindly help in solving my problem with code as well.

Thanks

Code for button on Menu Bar

        <input type="checkbox" onclick="themeToggle()" class="theme-switcher">

Code for button on Footer

    <input type="checkbox" onclick="themeToggle()" class="theme-switcher-2">

The js for both the buttons

    var tSwitcher = document.getElementsByClassName('theme-switcher');
    let element = document.body;

    let onpageLoad = localStorage.getItem("theme") || "";
    if (onpageLoad != null && onpageLoad == 'dark-mode') {
            for(let i = 0; i<tSwitcher.length; i++){
                    tSwitcher[i].checked = true;
        }

    }

    if(onpageLoad) element.classList.add(onpageLoad);

    function themeToggle() {
        if (event.target.checked) {
          localStorage.setItem('theme', 'dark-mode');
          element.classList.add('dark-mode');
        } else {
          localStorage.setItem('theme', '');
          element.classList.remove('dark-mode');
        }
      }

Body:
To get both of checkboxes it's better to use querySelectorAll:

querySelectorAll('[class^=theme-switcher]')

LocalStorage doesn't work in snippet but you can check it on your staging site

var tSwitcher = document.querySelectorAll('[class^=theme-switcher]');
let element = document.body;
let onpageLoad = localStorage.getItem("theme") || "";
if (onpageLoad != null && onpageLoad == 'dark-mode') {
      for(let i = 0; i<tSwitcher.length; i++){
          tSwitcher[i].checked = true;
      }

}

if(onpageLoad) element.classList.add(onpageLoad);

function themeToggle() {
    if (event.target.checked) {
      localStorage.setItem('theme', 'dark-mode');
      tSwitcher.forEach(function(el){
          element.classList.add('dark-mode');
          el.checked = true;
      })
    } else {
      localStorage.setItem('theme', '');
      tSwitcher.forEach(function(el){
          element.classList.remove('dark-mode');
          el.checked = false;
       })
    }
  }

<label class="switch" style="padding: 23px 0;">
        <input type="checkbox" onclick="themeToggle()" class="theme-switcher">
        <div>
            <span></span>
        </div>

    <label class="switcher">
    <input type="checkbox" onclick="themeToggle()" class="theme-switcher-2">
    <div>
    <i class="fas fa-sun"></i>
    <i class="fas fa-arrow-left arrow"></i>
    <i class="fas fa-moon"></i>
    </div>
    </label>


来源: stackexchange

问:
React - Substitute for `setState` Callback in Functional Components?
We have migrated to 'React Functional Components' instead of 'Class based Component'. I cannot find the substitute logic for setState callback function. I.e, I have a functional component with state, and I want to create an event handler function that mutates the state multiple times in sequence, the caveat being that I dont know the current value of state (it may be true/false). The following example may make more sense.

```<code>const Example = () => {
  const [ openDoor, setOpenDoor ] = useState(false);
  // the following handler should swich 'openDoor' state to inverse of
  // current state value. Then after setTimeout duration, inverse it again
  const toggleOpenDoor = () => {
  setOpenDoor(!openDoor);
  // within setTimeout below, '!openDoor' does not work because it still
  // receives the same value as above because of async nature of
  // state updates
  setTimeout(() => setOpenDoor(!openDoor), 500)
  }
  return(...);
}
</code>```

In class based components, we had callback argument which would update state after previous update. How do I achieve the same in the above functional component using state hook?

答:
You should just using setTimeout within useEffect callback:

```<code>const App = () => {
  const [openDoor, setOpenDoor] = useState(false);

  const toggle = () => setOpenDoor(prevOpen => !prevOpen);

  useEffect(() => {
    const id = setTimeout(() => toggle(), 1000);
    return () => clearTimeout(id);
  }, [openDoor]);

  return <Container>isOpen: {String(openDoor)}</Container>;
};
</code>```

ContentLicense: CC BY-SA 4.0

Body:
We have migrated to 'React Functional Components' instead of 'Class based Component'. I cannot find the substitute logic for setState callback function. I.e, I have a functional component with state, and I want to create an event handler function that mutates the state multiple times in sequence, the caveat being that I dont know the current value of state (it may be true/false). The following example may make more sense.

const Example = () => {
  const [ openDoor, setOpenDoor ] = useState(false);
  // the following handler should swich 'openDoor' state to inverse of
  // current state value. Then after setTimeout duration, inverse it again
  const toggleOpenDoor = () => {
  setOpenDoor(!openDoor);
  // within setTimeout below, '!openDoor' does not work because it still
  // receives the same value as above because of async nature of
  // state updates
  setTimeout(() => setOpenDoor(!openDoor), 500)
  }
  return(...);
}

In class based components, we had callback argument which would update state after previous update. How do I achieve the same in the above functional component using state hook?

Body:
You should just using setTimeout within useEffect callback:

const App = () => {
  const [openDoor, setOpenDoor] = useState(false);

  const toggle = () => setOpenDoor(prevOpen => !prevOpen);

  useEffect(() => {
    const id = setTimeout(() => toggle(), 1000);
    return () => clearTimeout(id);
  }, [openDoor]);

  return <Container>isOpen: {String(openDoor)}</Container>;
};


问:
Can a geometry shader access OpenGL culling and front face settings?
Is it possible for a OpenGL geometry shader to access the current settings for glFrontFace and glCullFace, and whether face culling is enabled? I have a geometry shader that renders normals for vertexes of triangles, and would like to render them only for triangles that will not be culled. What I would like to have is global variables, similar to built-in uniform variables, that tell whether glFrontFace was given GL_CCW or CL_CW, and whether glCullFace is set to GL_FRONT, GL_BACK, or GL_FRONT_AND_BACK, and whether face culling is enabled.

A workaround is for my C++ program to set the values as uniform variables in the shader program, but it would be more general, and make the shader program more easily usable, if it could query the status of culling, glFrontFace and glCullFace settings from OpenGL.

Please note, I do not want the gl_FrontFacing variable that is available to the fragment shader. Instead, the geometry shader needs to be able to access the values to know whether to generate a line representing a normal at the vertices of the triangle.

答: Think of functions that change OpenGL server's states as interfaces to their internal implementation's uniforms used by fixed pipeline shaders. As you implement your own pipeline, you have to implement your own uniforms. One of ways to switch from fixed pipeline to flexible one within preexisting code is to implement your own emulation of OpenGl functions, although it would not be very effective one.</p>


问:
JQuery Toggle InputBox based on if another Inputbox has value
I have a page that contains two input boxes. I need one input box to disappear and then reappear depending on if there is a value in the other one. I've read that using JQuery is the easiest way to do this however I have limited experience with it and can't find documentation on how to implement this. Here is the page:

```<code><label asp-for="Subject" class="control-label"></label>
<input asp-for="Subject" class="form-control" id="Subject"/>

<label asp-for="Header" class="control-label"></label>
<input asp-for="Header" class="form-control" id="Header"/>
</code>```

Here is the JQuery I have so far from my limited knowledge. The input box is gone at the start.

```<code><script type="text/javascript">
$("#Subject").val(function () {
    $("#Header").toggle(this.length > 0);
});
</code>```

I am not sure how to implement this where writing text in one textbox will make the other one disappear. The debugger is not supplying any error messages about the code.

答:
$("#Subject").on("input", function() {
  let $e = $("#Header");
  $(this).val() == "" ? $e.addClass("hidden"): $e.removeClass("hidden");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden {
  display: none !important;
}</code>```

<!DOCTYPE html>

<meta charset="UTF-8">
<title></title>

  <input asp-for="Subject" class="form-control" id="Subject"/>

  <input asp-for="Header" class="form-control hidden" id="Header"/>

```

Body:
I have a page that contains two input boxes. I need one input box to disappear and then reappear depending on if there is a value in the other one. I've read that using JQuery is the easiest way to do this however I have limited experience with it and can't find documentation on how to implement this. Here is the page:

<input asp-for="Subject" class="form-control" id="Subject"/>

<input asp-for="Header" class="form-control" id="Header"/>

Here is the JQuery I have so far from my limited knowledge. The input box is gone at the start.

Body:
$("#Subject").on("input", function() {
  let $e = $("#Header");
  $(this).val() == "" ? $e.addClass("hidden"): $e.removeClass("hidden");
});

.hidden {
  display: none !important;
}

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>
  <label asp-for="Subject" class="control-label"></label>
  <input asp-for="Subject" class="form-control" id="Subject"/>

  <label asp-for="Header" class="control-label"></label>
  <input asp-for="Header" class="form-control hidden" id="Header"/>
</body>

</html>


问:
How to create Azure Function based off Youtube API upload video code?
I am trying to convert this console app: (https://developers.google.com/youtube/v3/docs/videos/insert) , the contains the code to upload a video to YouTube using the YouTube API.
I am trying to place this code in to a Azure Function and use Azure Blob storage to store my YouTube files.

I started with a simple, Http trigger Azure functions and slowly started to insert more code in the function, but as I am doing, I an coming across various errors. Here is the code, I am trying to insert in my Azure Function:

```<code>using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;

using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;

namespace Google.Apis.YouTube.Samples
{
  /// <summary>
  /// YouTube Data API v3 sample: upload a video.
  /// Relies on the Google APIs Client Library for .NET, v1.7.0 or higher.
  /// See https://developers.google.com/api-client-library/dotnet/get_started
  /// </summary>
  internal class UploadVideo
  {
    [STAThread]
    static void Main(string[] args)
    {
      Console.WriteLine("YouTube Data API: Upload Video");
      Console.WriteLine("==============================");

      try
      {
        new UploadVideo().Run().Wait();
      }
      catch (AggregateException ex)
      {
        foreach (var e in ex.InnerExceptions)
        {
          Console.WriteLine("Error: " + e.Message);
        }
      }

      Console.WriteLine("Press any key to continue...");
      Console.ReadKey();
    }

    private async Task Run()
    {
      UserCredential credential;
      using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
      {
        credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(stream).Secrets,
            // This OAuth 2.0 access scope allows an application to upload files to the
            // authenticated user's YouTube channel, but doesn't allow other types of access.
            new[] { YouTubeService.Scope.YoutubeUpload },
            "user",
            CancellationToken.None
        );
      }

      var youtubeService = new YouTubeService(new BaseClientService.Initializer()
      {
        HttpClientInitializer = credential,
        ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
      });

      var video = new Video();
      video.Snippet = new VideoSnippet();
      video.Snippet.Title = "Default Video Title";
      video.Snippet.Description = "Default Video Description";
      video.Snippet.Tags = new string[] { "tag1", "tag2" };
      video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
      video.Status = new VideoStatus();
      video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
      var filePath = @"REPLACE_ME.mp4"; // Replace with path to actual movie file.

      using (var fileStream = new FileStream(filePath, FileMode.Open))
      {
        var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
        videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
        videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

        await videosInsertRequest.UploadAsync();
      }
    }

    void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
    {
      switch (progress.Status)
      {
        case UploadStatus.Uploading:
          Console.WriteLine("{0} bytes sent.", progress.BytesSent);
          break;

        case UploadStatus.Failed:
          Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
          break;
      }
    }

    void videosInsertRequest_ResponseReceived(Video video)
    {
      Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
    }
  }
}
</code>```

答:
Sharing the formatted source code wrapped inside the Azure function, however note that you wont be able to use it as-is since it is trying to access the file from the local path. You can refactor it further and pass accessible file path as input parameter.

Few nuget packages / dependencies you would need to install before you can compile is successfully

```<code>public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            log.LogInformation("YouTube Data API: Upload Video");
            log.LogInformation("==============================");

            try
            {
                await Run();
            }
            catch (AggregateException ex)
            {
                foreach (var e in ex.InnerExceptions)
                {
                    log.LogInformation("Error: " + e.Message);
                }
            }

            return new OkObjectResult($"Video Processed..");

        }

        private static async Task Run()
        {
            UserCredential credential;
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    // This OAuth 2.0 access scope allows an application to upload files to the
                    // authenticated user's YouTube channel, but doesn't allow other types of access.
                    new[] { YouTubeService.Scope.YoutubeUpload },
                    "user",
                    CancellationToken.None
                );
            }

            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
            });

            var video = new Video();
            video.Snippet = new VideoSnippet();
            video.Snippet.Title = "Default Video Title";
            video.Snippet.Description = "Default Video Description";
            video.Snippet.Tags = new string[] { "tag1", "tag2" };
            video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
            video.Status = new VideoStatus();
            video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
            var filePath = @"REPLACE_ME.mp4"; // Replace with path to actual movie file.

            using (var fileStream = new FileStream(filePath, FileMode.Open))
            {
                var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
                videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
                videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

                await videosInsertRequest.UploadAsync();
            }
        }

        private static void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
        {
            switch (progress.Status)
            {
                case UploadStatus.Uploading:
                    Console.WriteLine("{0} bytes sent.", progress.BytesSent);
                    break;

                case UploadStatus.Failed:
                    Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
                    break;
            }
        }

        private static void videosInsertRequest_ResponseReceived(Video video)
        {
            Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
        }
    }
</code>```

Body:
I am trying to convert this console app: (https://developers.google.com/youtube/v3/docs/videos/insert) , the contains the code to upload a video to YouTube using the YouTube API.
I am trying to place this code in to a Azure Function and use Azure Blob storage to store my YouTube files.

I started with a simple, Http trigger Azure functions and slowly started to insert more code in the function, but as I am doing, I an coming across various errors. Here is the code, I am trying to insert in my Azure Function:

using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;

using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;

namespace Google.Apis.YouTube.Samples
{
  ///
  /// YouTube Data API v3 sample: upload a video.
  /// Relies on the Google APIs Client Library for .NET, v1.7.0 or higher.
  /// See https://developers.google.com/api-client-library/dotnet/get_started
  ///
  internal class UploadVideo
  {
    [STAThread]
    static void Main(string[] args)
    {
      Console.WriteLine("YouTube Data API: Upload Video");
      Console.WriteLine("==============================");

      try
      {
        new UploadVideo().Run().Wait();
      }
      catch (AggregateException ex)
      {
        foreach (var e in ex.InnerExceptions)
        {
          Console.WriteLine("Error: " + e.Message);
        }
      }

      Console.WriteLine("Press any key to continue...");
      Console.ReadKey();
    }

    private async Task Run()
    {
      UserCredential credential;
      using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
      {
        credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(stream).Secrets,
            // This OAuth 2.0 access scope allows an application to upload files to the
            // authenticated user's YouTube channel, but doesn't allow other types of access.
            new[] { YouTubeService.Scope.YoutubeUpload },
            "user",
            CancellationToken.None
        );
      }

      var youtubeService = new YouTubeService(new BaseClientService.Initializer()
      {
        HttpClientInitializer = credential,
        ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
      });

      var video = new Video();
      video.Snippet = new VideoSnippet();
      video.Snippet.Title = "Default Video Title";
      video.Snippet.Description = "Default Video Description";
      video.Snippet.Tags = new string[] { "tag1", "tag2" };
      video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
      video.Status = new VideoStatus();
      video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
      var filePath = @"REPLACE_ME.mp4"; // Replace with path to actual movie file.

      using (var fileStream = new FileStream(filePath, FileMode.Open))
      {
        var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
        videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
        videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

        await videosInsertRequest.UploadAsync();
      }
    }

    void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
    {
      switch (progress.Status)
      {
        case UploadStatus.Uploading:
          Console.WriteLine("{0} bytes sent.", progress.BytesSent);
          break;

        case UploadStatus.Failed:
          Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
          break;
      }
    }

    void videosInsertRequest_ResponseReceived(Video video)
    {
      Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
    }
  }
}

Body:
Sharing the formatted source code wrapped inside the Azure function, however note that you wont be able to use it as-is since it is trying to access the file from the local path. You can refactor it further and pass accessible file path as input parameter.

Few nuget packages / dependencies you would need to install before you can compile is successfully

public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            log.LogInformation("YouTube Data API: Upload Video");
            log.LogInformation("==============================");

            try
            {
                await Run();
            }
            catch (AggregateException ex)
            {
                foreach (var e in ex.InnerExceptions)
                {
                    log.LogInformation("Error: " + e.Message);
                }
            }

            return new OkObjectResult($"Video Processed..");

        }

        private static async Task Run()
        {
            UserCredential credential;
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    // This OAuth 2.0 access scope allows an application to upload files to the
                    // authenticated user's YouTube channel, but doesn't allow other types of access.
                    new[] { YouTubeService.Scope.YoutubeUpload },
                    "user",
                    CancellationToken.None
                );
            }

            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
            });

            var video = new Video();
            video.Snippet = new VideoSnippet();
            video.Snippet.Title = "Default Video Title";
            video.Snippet.Description = "Default Video Description";
            video.Snippet.Tags = new string[] { "tag1", "tag2" };
            video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
            video.Status = new VideoStatus();
            video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
            var filePath = @"REPLACE_ME.mp4"; // Replace with path to actual movie file.

            using (var fileStream = new FileStream(filePath, FileMode.Open))
            {
                var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
                videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
                videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

                await videosInsertRequest.UploadAsync();
            }
        }

        private static void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
        {
            switch (progress.Status)
            {
                case UploadStatus.Uploading:
                    Console.WriteLine("{0} bytes sent.", progress.BytesSent);
                    break;

                case UploadStatus.Failed:
                    Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
                    break;
            }
        }

        private static void videosInsertRequest_ResponseReceived(Video video)
        {
            Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
        }
    }


问:
How to combine two values into a single key for a dictionary in python?
So, I have a dictionary in the following format. The key is a concatenated string and the value is a list of tuples.

```<code>dictionary = {'ABC|1':[(1,10),(5,16),(15,30)],
              'ABC|2':[(9,18),(78,10),(5,10)],
              'XYZ|1':[(45,56),(72,79),(81,98),(100,120)],
              'XYZ|2':[(11,26),(78,99),(105,119),(150,178)],..........}
</code>```

Now, I want to change the key from 'ABC|1' to 'ABC' and combining the two values of 'ABC|1' and 'ABC|2' into a single value for the key 'ABC'. Thus, the final_dict should look like this:

```<code>final_dict = {'ABC':[(1,10),(5,16),(15,30),(9,18),(78,10),(5,10)],
              'XYZ':[(45,56),(72,79),(81,98),(100,120),(11,26),(78,99),(105,119),(150,178)],....}
</code>```

The approach I am trying is as follows:

```<code>final_dict = dict()
for key in dictionary.keys():
  new_key = key.split('|')[0]
  if new_key not in final_dict:
    value = list()
  if new_key in key:
    value.append(dictionary[key])
</code>```

However, this is not working. Can anybody provide me a suggestion to do this? Without using pandas.

答:
this is a variant:

```<code>from collections import defaultdict

dct = defaultdict(list)
for key, value in dictionary.items():
    new_key = key.split('|')[0]
    dct[new_key].extend(value)
</code>```

where i  use collections.defaultdict.

your solution is close but judging from your desired output you want list.extend and not list.append.

Body:
So, I have a dictionary in the following format. The key is a concatenated string and the value is a list of tuples.

dictionary = {'ABC|1':[(1,10),(5,16),(15,30)],
              'ABC|2':[(9,18),(78,10),(5,10)],
              'XYZ|1':[(45,56),(72,79),(81,98),(100,120)],
              'XYZ|2':[(11,26),(78,99),(105,119),(150,178)],..........}

Now, I want to change the key from 'ABC|1' to 'ABC' and combining the two values of 'ABC|1' and 'ABC|2' into a single value for the key 'ABC'. Thus, the final_dict should look like this:

final_dict = {'ABC':[(1,10),(5,16),(15,30),(9,18),(78,10),(5,10)],
              'XYZ':[(45,56),(72,79),(81,98),(100,120),(11,26),(78,99),(105,119),(150,178)],....}

The approach I am trying is as follows:

final_dict = dict()
for key in dictionary.keys():
  new_key = key.split('|')[0]
  if new_key not in final_dict:
    value = list()
  if new_key in key:
    value.append(dictionary[key])

However, this is not working. Can anybody provide me a suggestion to do this? Without using pandas.

Body:
this is a variant:

from collections import defaultdict

dct = defaultdict(list)
for key, value in dictionary.items():
    new_key = key.split('|')[0]
    dct[new_key].extend(value)

where i  use collections.defaultdict.

your solution is close but judging from your desired output you want list.extend and not list.append.


问:
Use comma instead of semicolon for expression splitting in C
Give me an idea please, when one can use comma as a delimiter and when only semicolon:</p>

```<code>typedef struct k{int a,b;}*K;
main() {
  K z=(K)malloc(2*sizeof(int));
  z->a=1, // <- may be ; or , at the eol
  // This seems not like a multi-variables definition of same type vars, so why ',' is good?
  z->b=2;
  free(z);
  return 0;
}
</code>```

答:
I want to add that the comma operator allows for some IMHO quite beautiful code, such as:

```<code> if (a = foo(), a != -1) {
 }
</code>```

Instead of

```<code> if ((a = foo()) != -1) {
 }
</code>```

However, not many actually know about the comma operator, so you're perhaps better of not using it, sadly.

Body:
Give me an idea please, when one can use comma as a delimiter and when only semicolon:

typedef struct k{int a,b;}*K;
main() {
  K z=(K)malloc(2*sizeof(int));
  z->a=1, // <- may be ; or , at the eol
  // This seems not like a multi-variables definition of same type vars, so why ',' is good?
  z->b=2;
  free(z);
  return 0;
}

Body:
I want to add that the comma operator allows for some IMHO quite beautiful code, such as:

 if (a = foo(), a != -1) {
 }

Instead of

 if ((a = foo()) != -1) {
 }

However, not many actually know about the comma operator, so you're perhaps better of not using it, sadly.


问:
py.test use monkeypatch in custom funcargs
I use py.test and really like the funcarg approach to inject objects into test functions.
In my testing I need to work  with Mock objects, as I have a lot external dependencies. I use monkeypatch to replace certain attributes with the mock objects.

The problem I have is, that I will often end up with a bunch of tests that will use a certain funcarg and always require the same attributes patched. So far I replace the attributes in every test function.

Is there a way to use monkeypatch in my funcarg functions, and remove this duplicated code from the individual tests?

```<code>import sys
import pytest
from mock import Mock

#----------------------------------------------------------------------
def pytest_funcarg__api(request):
    """"""
    api = myclass()
    #do some initialisation...
    return api

#----------------------------------------------------------------------
def test_bla1(monkeypatch, api):
    """"""
    monkeypatch.setattr(api,"get_external_stuff",Mock())
    monkeypatch.setattr(api,"morestuff",Mock())

    api.do_something1()
    assert not api.a

#----------------------------------------------------------------------
def test_bla2(monkeypatch, api):
    """"""
    monkeypatch.setattr(api,"get_external_stuff",Mock())
    monkeypatch.setattr(api,"morestuff",Mock())

    api.do_something2()
    assert api.b

if __name__=='__main__':
    pytest.main(args=["-v",sys.argv[0]])
</code>```

答:
You can use the documented getfuncargvalue function to internally use a function argument from another function argument's factory:</p>

```<code>def pytest_funcarg__api(request):
    api = myclass()
    #do some initialisation...
    mp = request.getfuncargvalue("monkeypatch")
    mp.setattr(api,"get_external_stuff", Mock())
    mp.setattr(api,"morestuff", Mock())
    return api
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I use py.test and really like the funcarg approach to inject objects into test functions.
In my testing I need to work  with Mock objects, as I have a lot external dependencies. I use monkeypatch to replace certain attributes with the mock objects.

The problem I have is, that I will often end up with a bunch of tests that will use a certain funcarg and always require the same attributes patched. So far I replace the attributes in every test function.

Is there a way to use monkeypatch in my funcarg functions, and remove this duplicated code from the individual tests?

import sys
import pytest
from mock import Mock

#----------------------------------------------------------------------
def pytest_funcarg__api(request):
    """"""
    api = myclass()
    #do some initialisation...
    return api

#----------------------------------------------------------------------
def test_bla1(monkeypatch, api):
    """"""
    monkeypatch.setattr(api,"get_external_stuff",Mock())
    monkeypatch.setattr(api,"morestuff",Mock())

    api.do_something1()
    assert not api.a

#----------------------------------------------------------------------
def test_bla2(monkeypatch, api):
    """"""
    monkeypatch.setattr(api,"get_external_stuff",Mock())
    monkeypatch.setattr(api,"morestuff",Mock())

    api.do_something2()
    assert api.b

if __name__=='__main__':
    pytest.main(args=["-v",sys.argv[0]])

Body:
You can use the documented getfuncargvalue function to internally use a function argument from another function argument's factory:

def pytest_funcarg__api(request):
    api = myclass()
    #do some initialisation...
    mp = request.getfuncargvalue("monkeypatch")
    mp.setattr(api,"get_external_stuff", Mock())
    mp.setattr(api,"morestuff", Mock())
    return api


问:
Slick Slider Vertical Center Slide Issue
I am using center mode in the vertical slider of a slick slider in my project. The demo on their website is always active in the center slide and they have 3 slides in total. But in my case, I have 9 slides and when I apply their setting and make the slides 9, it again actives the second one but I need it to active the center which will e 5th slide.
I am attaching my project screenshot and my code

Javascript Code

```<code>$('.slider-for').slick(
{
    slidesToShow: 1,
    slidesToScroll: 1,
    arrows: false,
    fade: false,
    adaptiveHeight: true,
    infinite: false,
    useTransform: true,
    speed: 400,
});

$('.slider-nav').slick(
{
    slidesToShow: 9,
    slidesToScroll: 1,
    asNavFor: '.slider-for',
    dots: false,
    arrows: false,
    centerMode: true,
    focusOnSelect: true,
    vertical: true
});
</code>```

答:
On there site, In center mode they have six slides but showing 3 slides at a time and scrolling 1 slide per click.
Therfore, *slideToShow * must be the value how many slide you want to show in their case it's 3. not how many slide you have.

I think, you can try putting
slideToShow: 3

Body:
I am using center mode in the vertical slider of a slick slider in my project. The demo on their website is always active in the center slide and they have 3 slides in total. But in my case, I have 9 slides and when I apply their setting and make the slides 9, it again actives the second one but I need it to active the center which will e 5th slide.
I am attaching my project screenshot and my code

Javascript Code

$('.slider-for').slick(
{
    slidesToShow: 1,
    slidesToScroll: 1,
    arrows: false,
    fade: false,
    adaptiveHeight: true,
    infinite: false,
    useTransform: true,
    speed: 400,
});

$('.slider-nav').slick(
{
    slidesToShow: 9,
    slidesToScroll: 1,
    asNavFor: '.slider-for',
    dots: false,
    arrows: false,
    centerMode: true,
    focusOnSelect: true,
    vertical: true
});


问:
Send messages to the temporary queue with MassTransit
I have the following scenario, where i can not respond directly to the request of a MassTransit RequestClient

Request Service 1 implementing a RequestClient and calling GetResponse

Another service 2 have the consumer of the request that just save the request information (messageId, requestId ...) to some storage and not send a response back.

Based on an API call in service 2, we can find the saved request information and send back the response to the RequestClient. I could achive this by sending the response to the temporaty queue of the RequestClient bus but the message ends up in the skipped queue of the temporary queue and GetResponse never gets the message.

How can i make the message arrives to the main temporary queue, and that the GetResponse consumer find it.

答: If anyone has a similar scenario. We achived this by implementing an event waiter mechanism in the consumer. When the external API call is made in service 2, an internal event is fired then consumer who is waiting for it through ResetEvent continue by gathering the response and send it back through out of the box RespondAsync.</p>


问:
The <* syntax in Haskell
I'm given the following code

```<code> newtype Parser a = Parser { parse :: String -> Maybe (a,String) }

   instance Applicative Parser where
   pure a = Parser $ \s -> Just (a,s)
   f <*> a = Parser $ \s ->
     case parse f s of
       Just (g,s') -> parse (fmap g a) s'
       Nothing -> Nothing

    instance Alternative Parser where
      empty = Parser $ \s -> Nothing
      l <|> r = Parser $ \s -> parse l s <|> parse r s

    satisfy :: (Char -> Bool) -> Parser Char
    satisfy p = Parser f
       where f [] = Nothing
             f (x:xs) = if p x then Just (x,xs) else Nothing

    ws :: Parser ()
    ws = pure () <* many (satisfy isSpace)
</code>```

I know that ws parser removes leading spaces. But I need an explanation how exactly this is done. I don't understand the <* syntax  ( I know <*>). Can some help me understand  the syntax and why it is working ?

答:
No fear! It's easy, when we go by small steps, and see where it leads us. Next time, try doing it yourself.

(<*) = liftA2 const and liftA2 f x = (<*>) (fmap f x), so

```<code>ws :: Parser ()
ws = pure () <* many (satisfy isSpace)
     = {- (<*) = liftA2 const -}
     liftA2 const (pure ()) (many $ satisfy isSpace)
     = {- liftA2 f x = (<*>) (fmap f x) -}
     fmap const (pure ()) <*> many (satisfy isSpace)
     = {- by Applicative laws -}
     (pure const <*> pure ()) <*> many (satisfy isSpace)
     = {- by homomorphism law of Applicatives -}
     pure (const ()) <*> many (satisfy isSpace)
     = {- with Applicative Do -}
     do { f <- pure (const ())
        ; r <- many (satisfy isSpace)
        ; pure (f r) }
     = {- by Law of `pure` being the identity, i.e. no-op, effects-wise -}
     do { let f = const ()
        ; r <- many (satisfy isSpace)
        ; pure (f r) }
     = {- by substitution -}
     do { r <- many (satisfy isSpace)
        ; pure (const () r) }
     =
     do { _ <- many (satisfy isSpace)
        ; pure () }
     =
     do { many (satisfy isSpace)
        ; pure () }
     = {- Monad Comprehension illustration -}
     [ () | _ <- many (satisfy isSpace) ]
</code>```

(with the Applicative Do notation; to get the feeling for what this does. The Applicative Laws are enumerated at the above link as well.)

So it does what many (satisfy isSpace) does, except the computed value it returns is always ().

In pure functions, f a = () would completely ignore its second argument. We could call it as f (1 / 0) and it wouldn't care. But Applicative Functors express computations, and <*> combines computations fully known prior to the combination so that each one gets performed, whether its computed value is later used or not.

Title: The <* syntax in Haskell

Body:
I'm given the following code

 newtype Parser a = Parser { parse :: String -> Maybe (a,String) }

   instance Applicative Parser where
   pure a = Parser $ \s -> Just (a,s)
   f <*> a = Parser $ \s ->
     case parse f s of
       Just (g,s') -> parse (fmap g a) s'
       Nothing -> Nothing

    instance Alternative Parser where
      empty = Parser $ \s -> Nothing
      l <|> r = Parser $ \s -> parse l s <|> parse r s

    satisfy :: (Char -> Bool) -> Parser Char
    satisfy p = Parser f
       where f [] = Nothing
             f (x:xs) = if p x then Just (x,xs) else Nothing

    ws :: Parser ()
    ws = pure () <* many (satisfy isSpace)

I know that ws parser removes leading spaces. But I need an explanation how exactly this is done. I don't understand the <* syntax  ( I know <*>). Can some help me understand  the syntax and why it is working ?

Body:
No fear! It's easy, when we go by small steps, and see where it leads us. Next time, try doing it yourself.

(<*) = liftA2 const and liftA2 f x = (<*>) (fmap f x), so

ws :: Parser ()
ws = pure () <* many (satisfy isSpace)
     = {- (<*) = liftA2 const -}
     liftA2 const (pure ()) (many $ satisfy isSpace)
     = {- liftA2 f x = (<*>) (fmap f x) -}
     fmap const (pure ()) <*> many (satisfy isSpace)
     = {- by Applicative laws -}
     (pure const <*> pure ()) <*> many (satisfy isSpace)
     = {- by homomorphism law of Applicatives -}
     pure (const ()) <*> many (satisfy isSpace)
     = {- with Applicative Do -}
     do { f <- pure (const ())
        ; r <- many (satisfy isSpace)
        ; pure (f r) }
     = {- by Law of `pure` being the identity, i.e. no-op, effects-wise -}
     do { let f = const ()
        ; r <- many (satisfy isSpace)
        ; pure (f r) }
     = {- by substitution -}
     do { r <- many (satisfy isSpace)
        ; pure (const () r) }
     =
     do { _ <- many (satisfy isSpace)
        ; pure () }
     =
     do { many (satisfy isSpace)
        ; pure () }
     = {- Monad Comprehension illustration -}
     [ () | _ <- many (satisfy isSpace) ]

(with the Applicative Do notation; to get the feeling for what this does. The Applicative Laws are enumerated at the above link as well.)

So it does what many (satisfy isSpace) does, except the computed value it returns is always ().

In pure functions, f a = () would completely ignore its second argument. We could call it as f (1 / 0) and it wouldn't care. But Applicative Functors express computations, and <*> combines computations fully known prior to the combination so that each one gets performed, whether its computed value is later used or not.


问:
React Js can't Run using npm start
I want to run my project, but  npm start error -_-</p>

```<code>npm ERR! errno 1
npm ERR! breednder-project@0.1.0 start: `react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the breednder-project@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/aziz/.npm/_logs/2020-02-15T09_11_32_000Z-debug.log```
</code>```

答:
I had this issue before so I will share what my issue was:

in package.json just verify the integrity of you start command.  Also try npm run start (add run to it)

```<code>"scripts": {
  "start": "react-scripts start",
  "build": "react-scripts build",
  "test": "react-scripts test",
  "eject": "react-scripts eject"
},
</code>```

Title: React Js can't Run using npm start

Body:
I want to run my project, but  npm start error -_-

npm ERR! errno 1
npm ERR! breednder-project@0.1.0 start: `react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the breednder-project@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/aziz/.npm/_logs/2020-02-15T09_11_32_000Z-debug.log```

Body:
I had this issue before so I will share what my issue was:

in package.json just verify the integrity of you start command.  Also try npm run start (add run to it)

"scripts": {
  "start": "react-scripts start",
  "build": "react-scripts build",
  "test": "react-scripts test",
  "eject": "react-scripts eject"
},


问:
Extract data from sql using python, do transformations and write back to sql table
I have a scenario where I need to extract data from different sql tables, use that data to transform it in python and next I need to write back the result to a SQL table.

Is this possible?

Is it an efficient way? Or would you recommend using different tools?

How can I automate the python script to run it automatically from a server?

Many thanks!

答:
Of course it's possible.

I think it depends on what kind of transformations you want to apply and your knowledge on python and SQL. I mean if the transformation is something like replacing and simple math functions you can do this using SQL codes but in case of complex functions and maybe lack of SQL code knowledge you should use python. And I suggest using Pandas.

You can simply run it in shell and use cron-job if you need to run it on specific schedule.


问:
Getting JSON parsing error (MismatchedInputException) in Spring Rest Controller
I am quite new to Spring. I am having a JSON parsing error when I try a POST method in Postman. Basically, I have a class that I want to call in another one in the form of a list.

I have an abstract entity that I use for classes, then I have a tag class;

```<code>@Entity
@Data
@EqualsAndHashCode(callSuper = true)
public class Tag extends AbstractEntity {

    @Column (nullable = false)
    private String tag;
</code>```

And I have a question class:

```<code>@Entity
@Data
@EqualsAndHashCode(callSuper = true)
public class Question extends AbstractEntity {

    @Column (nullable = false)
    private String title;
    @Column (nullable = false)
    private String content;
    @OneToMany
    @Column (nullable = false)
    private List<Tag> tag;
</code>```

Here is my controller:

```<code>@RestController
@RequestMapping("v1/enquiry")
public class EnquiryController {

    @Autowired
    private QuestionRepository questionRepository;

    @PostMapping
    public ResponseEntity<Question> createEnquiry(@RequestBody Question question) {
        if (question.getTitle() == null | question.getContent() == null) {
            throw new BadRequest("Please fill in the required fields!");
        }

        Question enq = questionRepository.save(question);
        return ResponseEntity.ok().body(enq);
    }
</code>```

When I do a POST method with:

```<code>{
   "title": "question",
   "content": "cogito",
   "tag": ["java", "rest"]
}
</code>```

I get the following error. I quite tried all of the suggestions to similar conditions posted around. None of them worked. What am I doing wrong?

"message": "JSON parse error: Cannot construct instance of com.mockup.mockupapi.model.Tag (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('java'); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of com.mockup.mockupapi.model.Tag (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('java')\n at [Source: (PushbackInputStream); line: 4, column: 10] (through reference chain: com.mockup.mockupapi.model.Question[\"tag\"]->java.util.ArrayList[0])",

SOLVED

Thanks to clues in the commentary, I changed the array format in JSON, and added CascadeType to OneToMany call. I used .PERSIST, however, .ALL works as well.

The JSON format:

```<code>{
   "title": "question",
   "content": "cogito",
   "tag": [{"tag":"java"},{"tag": "rest"}]
}
</code>```

The Question class:

```<code>@Entity
@Data
@EqualsAndHashCode(callSuper = true)
public class Question extends AbstractEntity {

    @Column (nullable = false)
    private String title;
    @Column (nullable = false)
    private String content;
    @OneToMany(cascade = CascadeType.PERSIST)
    @Column (nullable = false)
    private List<Tag> tag;
</code>```

答:
Please change your JSON structure.

```<code>{ "title": "question", "content": "cogito", "tag": [{"tag":"java"},{"tag": "rest"}] }
</code>```

Also add cascade in your mapping.

```<code>@OneToMany (cascade = CascadeType.ALL)
 @Column (nullable = false)
 private List<Tag> tag;
</code>```

Body:
I am quite new to Spring. I am having a JSON parsing error when I try a POST method in Postman. Basically, I have a class that I want to call in another one in the form of a list.

I have an abstract entity that I use for classes, then I have a tag class;

@Entity
@Data
@EqualsAndHashCode(callSuper = true)
public class Tag extends AbstractEntity {

    @Column (nullable = false)
    private String tag;

And I have a question class:

@Entity
@Data
@EqualsAndHashCode(callSuper = true)
public class Question extends AbstractEntity {

    @Column (nullable = false)
    private String title;
    @Column (nullable = false)
    private String content;
    @OneToMany
    @Column (nullable = false)
    private List<Tag> tag;

Here is my controller:

@RestController
@RequestMapping("v1/enquiry")
public class EnquiryController {

    @Autowired
    private QuestionRepository questionRepository;

    @PostMapping
    public ResponseEntity<Question> createEnquiry(@RequestBody Question question) {
        if (question.getTitle() == null | question.getContent() == null) {
            throw new BadRequest("Please fill in the required fields!");
        }

        Question enq = questionRepository.save(question);
        return ResponseEntity.ok().body(enq);
    }

When I do a POST method with:

{
   "title": "question",
   "content": "cogito",
   "tag": ["java", "rest"]
}

I get the following error. I quite tried all of the suggestions to similar conditions posted around. None of them worked. What am I doing wrong?

"message": "JSON parse error: Cannot construct instance of com.mockup.mockupapi.model.Tag (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('java'); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of com.mockup.mockupapi.model.Tag (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('java')\n at [Source: (PushbackInputStream); line: 4, column: 10] (through reference chain: com.mockup.mockupapi.model.Question[\"tag\"]->java.util.ArrayList[0])",

SOLVED

Thanks to clues in the commentary, I changed the array format in JSON, and added CascadeType to OneToMany call. I used .PERSIST, however, .ALL works as well.

The JSON format:

{
   "title": "question",
   "content": "cogito",
   "tag": [{"tag":"java"},{"tag": "rest"}]
}

The Question class:

@Entity
@Data
@EqualsAndHashCode(callSuper = true)
public class Question extends AbstractEntity {

    @Column (nullable = false)
    private String title;
    @Column (nullable = false)
    private String content;
    @OneToMany(cascade = CascadeType.PERSIST)
    @Column (nullable = false)
    private List<Tag> tag;

Body:
Please change your JSON structure.

{ "title": "question", "content": "cogito", "tag": [{"tag":"java"},{"tag": "rest"}] }

Also add cascade in your mapping.

@OneToMany (cascade = CascadeType.ALL)
 @Column (nullable = false)
 private List<Tag> tag;


问:
How to require a field if a particular checkbox is checked in laravel?
I am new to Laravel, I have three checkboxes: WhatsApp, Email and SMS

What I want to accomplish in my validation CustomerRequest, is to require the Email field if the Checkbox for email is checked:

Below is a sample of my rules:

```<code>public function rules()
    {
        return [
            'choix' => 'required',
            'tel' => 'required|max:25',
            'contract' => 'required|numeric|max:9',
            'nom' => 'required|max:255',
            'email' => 'required|max:50',
            'language' => 'required|max:2',
            'g-recaptcha-response' => 'required|captcha',
            'conditionAccepted' => 'accepted',
        ];
    }
</code>```

Below is my checkbox field:

```<code> <div class="form-group row">
                    <div class="col-md-12 " style="text-align : left; margin-left:20px;" ><label class="checkbox-inline check"> <input type="checkbox" class="checkbox" name="choix[]" value="WHA">
                            <span style="margin-top:10px; margin-left:20px; position: absolute;">WhatsApp</span></label></div>
                    <div class="col-md-12 " style="text-align : left; margin-left:20px;" ><label class="checkbox-inline check"> <input type="checkbox" class="checkbox" name="choix[]" value="SMS">
                            <span style="margin-top:10px; margin-left:20px; position: absolute;">SMS</span></label></div>
                    <div class="col-md-12 " style="text-align : left; margin-left:20px;" ><label class="checkbox-inline check"> <input type="checkbox" class="checkbox" name="choix[]" value="MAIL">
                            <span style="margin-top:10px; margin-left:20px; position: absolute;">Email</span></label></div>

                </div>
</code>```

Appreciate guidance

答: You can use required_with validation rule. Check the whole list in the docs, there are many helpful validation rules https://laravel.com/docs/5.8/validation#rule-required-unless

Body:
I am new to Laravel, I have three checkboxes: WhatsApp, Email and SMS

What I want to accomplish in my validation CustomerRequest, is to require the Email field if the Checkbox for email is checked:

Below is a sample of my rules:

public function rules()
    {
        return [
            'choix' => 'required',
            'tel' => 'required|max:25',
            'contract' => 'required|numeric|max:9',
            'nom' => 'required|max:255',
            'email' => 'required|max:50',
            'language' => 'required|max:2',
            'g-recaptcha-response' => 'required|captcha',
            'conditionAccepted' => 'accepted',
        ];
    }

Below is my checkbox field:

 <input type="checkbox" class="checkbox" name="choix[]" value="WHA">
                            WhatsApp

 <input type="checkbox" class="checkbox" name="choix[]" value="SMS">
                            SMS

 <input type="checkbox" class="checkbox" name="choix[]" value="MAIL">
                            Email

Appreciate guidance


问:
Static variable in Python?
In C++ we have static keyword which in loops is something like this:

```<code>for(int x=0; x<10; x++)
    {
      for(int y=0; y<10; y++)
      {
        static int number_of_times = 0;
        number_of_times++;
      }
    }
</code>```

static here makes number_of_times initialized once. How can I do same thing in python 3.x?

EDIT: Since most of the people got confused I would like to point out that the code I gave is just example of static usage in C++. My real problem is that I want to initialize only ONE time variable in function since I dont want it to be global(blah!) or default parameter..

答:
Use defaultdict:

```<code>from collections import defaultdict

static = defaultdict(lambda: 0)

def myfunc():
    for x in range(10):
        for y in range(10):
            static['number_of_times'] += 1
</code>```

Title: Static variable in Python?

Body:
In C++ we have static keyword which in loops is something like this:

for(int x=0; x<10; x++)
    {
      for(int y=0; y<10; y++)
      {
        static int number_of_times = 0;
        number_of_times++;
      }
    }

static here makes number_of_times initialized once. How can I do same thing in python 3.x?

EDIT: Since most of the people got confused I would like to point out that the code I gave is just example of static usage in C++. My real problem is that I want to initialize only ONE time variable in function since I dont want it to be global(blah!) or default parameter..

Body:
Use defaultdict:

from collections import defaultdict

static = defaultdict(lambda: 0)

def myfunc():
    for x in range(10):
        for y in range(10):
            static['number_of_times'] += 1


问:
Validating multiple inputs in a p:dataTable or p:treeTable using OmniFaces o:validateMultiple
I have a UI that looks like this:

There must not be duplicate jersey numbers for a game, so I want a validator for all UIInputs in that column.

I immediately came up with using OmniFaces' o:validateMultiple.

However, that doesn't seem to work. Submitting the form by clicking the button results in:

```<code>22:30:20,917 SEVERE [javax.enterprise.resource.webcontainer.jsf.context] (default task-7) java.lang.IllegalArgumentException: ValidateMultiple attribute 'components' must refer existing client IDs. Client ID ':score-input-form:home-box-score-table:0:jersey-nbr-input' cannot be found.
    at org.omnifaces.component.validator.ValidateMultipleFields.findInputComponent(ValidateMultipleFields.java:324)
    at org.omnifaces.component.validator.ValidateMultipleFields.collectComponents(ValidateMultipleFields.java:248)
    at org.omnifaces.component.validator.ValidateMultipleFields.validateComponents(ValidateMultipleFields.java:205)
    at org.omnifaces.component.validator.ValidatorFamily.processValidators(ValidatorFamily.java:68)
    at javax.faces.component.UIForm.processValidators(UIForm.java:269)
    at com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:632)
    at com.sun.faces.component.visit.PartialVisitContext.invokeVisitCallback(PartialVisitContext.java:183)
    at javax.faces.component.UIForm.visitTree(UIForm.java:405)
    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1747)
    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1747)
    at com.sun.faces.context.PartialViewContextImpl.processComponents(PartialViewContextImpl.java:424)
    at com.sun.faces.context.PartialViewContextImpl.processPartial(PartialViewContextImpl.java:285)
    at org.primefaces.context.PrimePartialViewContext.processPartial(PrimePartialViewContext.java:65)
    at javax.faces.context.PartialViewContextWrapper.processPartial(PartialViewContextWrapper.java:252)
    at org.omnifaces.context.OmniPartialViewContext.processPartial(OmniPartialViewContext.java:122)
    at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1330)
    at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:77)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:100)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:201)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:670)
    at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)
    at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
    at io.opentracing.contrib.jaxrs2.server.SpanFinishingFilter.doFilter(SpanFinishingFilter.java:55)
    at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
    at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
    at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
    at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
    at io.undertow.servlet.handlers.ServletChain$1.handleRequest(ServletChain.java:68)
    at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
    at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:132)
    at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
    at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
    at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
    at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
    at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
    at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler.handleRequest(GlobalRequestControllerHandler.java:68)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
    at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
    at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
    at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
    at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
    at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
    at org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
    at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
    at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
    at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
    at io.undertow.server.Connectors.executeRootHandler(Connectors.java:360)
    at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:830)
    at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
    at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1985)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1487)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1378)
    at java.lang.Thread.run(Thread.java:748)
</code>```

Here's my code example...

Bean:

```<code>@Named
@ViewScoped
public class DebugTableValidateMultipleManager implements Serializable
{
    private static final long serialVersionUID = 1L;

    private SimpleScore selectedEntity;

    private TreeNode rootNode;

    @PostConstruct
    public void init()
    {
        this.selectedEntity = new SimpleScore();

        List<SimplePlayerStat> playerStats = Arrays.asList( new SimplePlayerStat( "Michael Jordan", 23 ), new SimplePlayerStat( "Dirk Nowitzki", 41 ) );

        this.selectedEntity.setPlayerStats( playerStats );
    }

    public SimpleScore getSelectedEntity()
    {
        return selectedEntity;
    }

    public void setSelectedEntity( SimpleScore selectedEntity )
    {
        this.selectedEntity = selectedEntity;
    }

    public void save()
    {
        System.out.println( "Saving simple score: " + selectedEntity );

        FacesContext.getCurrentInstance().addMessage( "score-button-form:growl", new FacesMessage( "Score successfully saved." ) );
    }

    public TreeNode getRootNode()
    {
        // System.out.println( "------- getRootNode(): " + rootNode );

        if ( rootNode == null )
        {
            System.out.println( getClass().getSimpleName() + ": -------------------------------------- Selected score: " + selectedEntity );

            // init navigation tree
            rootNode = new DefaultTreeNode( selectedEntity, null );

            List<SimplePlayerStat> playerStats = selectedEntity.getPlayerStats();

            for ( SimplePlayerStat playerStat : playerStats )
            {
                // player stats: jersey nbr, starter, DNP
                TreeNode playerStatNode = new DefaultTreeNode( SimplePlayerStat.class.getSimpleName(), playerStat, rootNode );
                playerStatNode.setExpanded( true );
            }
        }

        return rootNode;
    }

    public void setRootNode( TreeNode rootNode )
    {
        this.rootNode = rootNode;
    }

    // validation

    public void validateJerseyNbrs( FacesContext context, List<UIInput> components, List<Object> values )
    {
        // get home or away score entity
        SimpleScore score = selectedEntity;

        List<Integer> jerseyNbrs = score.getPlayerStats().stream().map( SimplePlayerStat::getJerseyNbr ).collect( Collectors.toList() );

        // determine frequencies of jersey nbrs
        Map<Integer, Long> frequencies = jerseyNbrs.stream().collect( Collectors.groupingBy( j -> j, Collectors.counting() ) );

        System.out.println( "Frequencies:\n" + frequencies );

//        if ( players.contains( player ) )
        {
            throw new ValidatorException( FacesMsgUtils.newErrorMessage( "There are " + frequencies + " of jersey numbers in this!" ) );
        }
    }

    public String getValidatorIds()
    {
        IntStream indices = IntStream.range( 0, selectedEntity.getPlayerStats().size() );

        List<String> ids = indices.mapToObj( id -> ":score-input-form:home-box-score-table:" + id + ":jersey-nbr-input" ).collect( Collectors.toList() );

        String idString = ids.stream().collect( Collectors.joining( " " ) );

        System.out.println( "Validator IDs: " + idString );

        return idString;
    }

    public class SimpleScore implements Serializable
    {
        private static final long serialVersionUID = 1L;

        private List<SimplePlayerStat> playerStats;

        public List<SimplePlayerStat> getPlayerStats()
        {
            return playerStats;
        }

        public void setPlayerStats( List<SimplePlayerStat> playerStats )
        {
            this.playerStats = playerStats;
        }
    }

    public class SimplePlayerStat implements Serializable
    {
        private static final long serialVersionUID = 1L;

        private String name;
        private Integer jerseyNbr;

        public SimplePlayerStat( String name, Integer jerseyNbr )
        {
            this.name = name;
            this.jerseyNbr = jerseyNbr;
        }

        public String getName()
        {
            return name;
        }

        public void setName(String name)
        {
            this.name = name;
        }

        public Integer getJerseyNbr()
        {
            return jerseyNbr;
        }

        public void setJerseyNbr(Integer jerseyNbr)
        {
            this.jerseyNbr = jerseyNbr;
        }
    }
}
</code>```

Facelet:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:f="http://xmlns.jcp.org/jsf/core"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
      xmlns:o="http://omnifaces.org/ui"
      xmlns:of="http://omnifaces.org/functions"
      xmlns:p="http://primefaces.org/ui">

    <f:view>

        <h:head>
        </h:head>

        <h:body>

            <div style="margin-left: auto; margin-right: auto; width: 500px; font-size: 0.8em;">

                <h1>Game Manager</h1>

                <h:form id="score-input-form">

                    <!--p:treeTable id="home-box-score-table"
                                 value="#{debugTableValidateMultipleManager.rootNode}"
                                 var="obj"
                                 nodeVar="node"
                                 styleClass="box-score-tree-table">

                        <f:facet name="header">
                            Home Team
                        </f:facet>

                        <p:column id="name"
                                  headerText="Player"
                                  styleClass="width-30 text-left">
                            <h:outputText value="#{obj.name}" />
                        </p:column>

                        <p:column id="jersey-nbr"
                                  headerText="Jersey Number"
                                  styleClass="width-10 text-right">
                            <p:inputNumber id="jersey-nbr-input"
                                           value="#{obj.jerseyNbr}"
                                           required="true"
                                           requiredMessage="Jersey number is required."
                                           maxlength="2"
                                           decimalPlaces="0"
                                           styleClass="" />
                        </p:column>

                    </p:treeTable-->

                    <p:dataTable id="home-box-score-table"
                                 value="#{debugTableValidateMultipleManager.rootNode.data.playerStats}"
                                 var="obj"
                                 styleClass="box-score-tree-table">

                        <f:facet name="header">
                            Home Team
                        </f:facet>

                        <p:column id="name"
                                  headerText="Player"
                                  styleClass="width-30 text-left">
                            <h:outputText value="#{obj.name}" />
                        </p:column>

                        <p:column id="jersey-nbr"
                                  headerText="Jersey Number"
                                  styleClass="width-10 text-right">
                            <p:inputNumber id="jersey-nbr-input"
                                           value="#{obj.jerseyNbr}"
                                           required="true"
                                           requiredMessage="Jersey number is required."
                                           maxlength="2"
                                           decimalPlaces="0"
                                           styleClass="" />
                        </p:column>

                    </p:dataTable>

                    <div class="clear-both" />

                    <o:validateMultiple id="home-validator"
                                        components=":score-input-form:home-box-score-table:0:jersey-nbr-input :score-input-form:home-box-score-table:1:jersey-nbr-input"
                                       omponents="@form:home-box-score-table:0:jersey-nbr-input"
                                       mponents="#{debugTableValidateMultipleManager.validatorIds}"
                                        validator="#{debugTableValidateMultipleManager.validateJerseyNbrs}" />

                    <p:messages severity="error" />

                    <p:commandButton id="save-button"
                                     icon="fa fa-save"
                                     value="Save"
                                     action="#{debugTableValidateMultipleManager.save()}"
                                     process="@form"
                                     update="@form"
                                     style="margin-top: 10px;" />

                </h:form>

            </div>

        </h:body>

    </f:view>

</html>
</code>```

QUESTION:

Why isn't it working?

Is it a bug/missing feature in OmniFaces?

Looking at the OmniFaces code in ValidateMultipleFields class

```<code>private UIInput findInputComponent(UIComponent parent, String clientId, PropertyKeys property) {

    UIComponent found = parent.findComponent(clientId);     <-- results in null!

    if (found == null) {
        throw new IllegalArgumentException(format(
            ERROR_UNKNOWN_COMPONENT, getClass().getSimpleName(), property, clientId));
    }
    else if (!(found instanceof UIInput)) {
        throw new IllegalArgumentException(format(
            ERROR_INVALID_COMPONENT, getClass().getSimpleName(), property, clientId, found.getClass().getName()));
    }

    return (UIInput) found;
}
</code>```

and looking at the generated HTML...

... the IDs I'm using seem to be right and the search policy parent.findComponent(clientId) might not be working for iterative components like p:dataTable and p:treeTable... ♂

I'd be glad if someone could have a look at this.

Maybe there's another solution for this, but I simple cannot see it, so if there's another way to validate multiple inputs in a p:dataTable or p:treeTable please let me know.

EDIT:

I used p:dataTable to explain my problem, however I didn't know that this component has a completely different inheritance hierarchy. p:dataTable extends from UIData, while p:treeTable extends from UITree.

Obviously, hierarchical data is of course more complex.

Here's the real UI I am using:

This results in an exception using o:validateUniqueColumn:

```<code>00:02:17,223 SEVERE [javax.enterprise.resource.webcontainer.jsf.context] (default task-2) java.lang.IllegalArgumentException: Parent component of o:validateUniqueColumn must be enclosed in an UIData component.
    at org.omnifaces.taghandler.ValidateUniqueColumn.apply(ValidateUniqueColumn.java:114)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:161)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:203)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:135)
    at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:96)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:161)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:203)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:135)
    at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:96)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:161)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:203)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:135)
    at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:96)
    at com.sun.faces.facelets.tag.ui.CompositionHandler.apply(CompositionHandler.java:195)
    at com.sun.faces.facelets.compiler.NamespaceHandler.apply(NamespaceHandler.java:94)
    at com.sun.faces.facelets.compiler.EncodingHandler.apply(EncodingHandler.java:88)
</code>```

答:
The <o:validateMultiple> isn't (yet?) intented to be used this way, targeting a single component within a repeater component. It works only on physically multiple components defined in XHTML source code, not on virtually multiple components produced in HTML output.

For now, just use <o:validateUniqueColumn> instead. It's designed for exactly your use case. It's a taghandler not a component, so just nest it directly in the single input component as below. No need for other configuration.

```<code><p:column>
    <p:inputNumber>
        <o:validateUniqueColumn />
    </p:inputNumber>
</p:column>
</code>```

Body:
I have a UI that looks like this:

There must not be duplicate jersey numbers for a game, so I want a validator for all UIInputs in that column.

I immediately came up with using OmniFaces' o:validateMultiple.

However, that doesn't seem to work. Submitting the form by clicking the button results in:

22:30:20,917 SEVERE [javax.enterprise.resource.webcontainer.jsf.context] (default task-7) java.lang.IllegalArgumentException: ValidateMultiple attribute 'components' must refer existing client IDs. Client ID ':score-input-form:home-box-score-table:0:jersey-nbr-input' cannot be found.
    at org.omnifaces.component.validator.ValidateMultipleFields.findInputComponent(ValidateMultipleFields.java:324)
    at org.omnifaces.component.validator.ValidateMultipleFields.collectComponents(ValidateMultipleFields.java:248)
    at org.omnifaces.component.validator.ValidateMultipleFields.validateComponents(ValidateMultipleFields.java:205)
    at org.omnifaces.component.validator.ValidatorFamily.processValidators(ValidatorFamily.java:68)
    at javax.faces.component.UIForm.processValidators(UIForm.java:269)
    at com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:632)
    at com.sun.faces.component.visit.PartialVisitContext.invokeVisitCallback(PartialVisitContext.java:183)
    at javax.faces.component.UIForm.visitTree(UIForm.java:405)
    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1747)
    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1747)
    at com.sun.faces.context.PartialViewContextImpl.processComponents(PartialViewContextImpl.java:424)
    at com.sun.faces.context.PartialViewContextImpl.processPartial(PartialViewContextImpl.java:285)
    at org.primefaces.context.PrimePartialViewContext.processPartial(PrimePartialViewContext.java:65)
    at javax.faces.context.PartialViewContextWrapper.processPartial(PartialViewContextWrapper.java:252)
    at org.omnifaces.context.OmniPartialViewContext.processPartial(OmniPartialViewContext.java:122)
    at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1330)
    at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:77)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:100)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:201)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:670)
    at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)
    at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
    at io.opentracing.contrib.jaxrs2.server.SpanFinishingFilter.doFilter(SpanFinishingFilter.java:55)
    at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
    at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
    at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
    at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
    at io.undertow.servlet.handlers.ServletChain$1.handleRequest(ServletChain.java:68)
    at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
    at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:132)
    at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
    at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
    at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
    at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
    at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
    at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler.handleRequest(GlobalRequestControllerHandler.java:68)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
    at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
    at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
    at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
    at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
    at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
    at org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
    at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
    at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
    at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
    at io.undertow.server.Connectors.executeRootHandler(Connectors.java:360)
    at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:830)
    at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
    at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1985)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1487)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1378)
    at java.lang.Thread.run(Thread.java:748)

Here's my code example...

Bean:

@Named
@ViewScoped
public class DebugTableValidateMultipleManager implements Serializable
{
    private static final long serialVersionUID = 1L;

    private SimpleScore selectedEntity;

    private TreeNode rootNode;

    @PostConstruct
    public void init()
    {
        this.selectedEntity = new SimpleScore();

        List<SimplePlayerStat> playerStats = Arrays.asList( new SimplePlayerStat( "Michael Jordan", 23 ), new SimplePlayerStat( "Dirk Nowitzki", 41 ) );

        this.selectedEntity.setPlayerStats( playerStats );
    }

    public SimpleScore getSelectedEntity()
    {
        return selectedEntity;
    }

    public void setSelectedEntity( SimpleScore selectedEntity )
    {
        this.selectedEntity = selectedEntity;
    }

    public void save()
    {
        System.out.println( "Saving simple score: " + selectedEntity );

        FacesContext.getCurrentInstance().addMessage( "score-button-form:growl", new FacesMessage( "Score successfully saved." ) );
    }

    public TreeNode getRootNode()
    {
        // System.out.println( "------- getRootNode(): " + rootNode );

        if ( rootNode == null )
        {
            System.out.println( getClass().getSimpleName() + ": -------------------------------------- Selected score: " + selectedEntity );

            // init navigation tree
            rootNode = new DefaultTreeNode( selectedEntity, null );

            List<SimplePlayerStat> playerStats = selectedEntity.getPlayerStats();

            for ( SimplePlayerStat playerStat : playerStats )
            {
                // player stats: jersey nbr, starter, DNP
                TreeNode playerStatNode = new DefaultTreeNode( SimplePlayerStat.class.getSimpleName(), playerStat, rootNode );
                playerStatNode.setExpanded( true );
            }
        }

        return rootNode;
    }

    public void setRootNode( TreeNode rootNode )
    {
        this.rootNode = rootNode;
    }

    // validation

    public void validateJerseyNbrs( FacesContext context, List<UIInput> components, List<Object> values )
    {
        // get home or away score entity
        SimpleScore score = selectedEntity;

        List<Integer> jerseyNbrs = score.getPlayerStats().stream().map( SimplePlayerStat::getJerseyNbr ).collect( Collectors.toList() );

        // determine frequencies of jersey nbrs
        Map<Integer, Long> frequencies = jerseyNbrs.stream().collect( Collectors.groupingBy( j -> j, Collectors.counting() ) );

        System.out.println( "Frequencies:\n" + frequencies );

//        if ( players.contains( player ) )
        {
            throw new ValidatorException( FacesMsgUtils.newErrorMessage( "There are " + frequencies + " of jersey numbers in this!" ) );
        }
    }

    public String getValidatorIds()
    {
        IntStream indices = IntStream.range( 0, selectedEntity.getPlayerStats().size() );

        List<String> ids = indices.mapToObj( id -> ":score-input-form:home-box-score-table:" + id + ":jersey-nbr-input" ).collect( Collectors.toList() );

        String idString = ids.stream().collect( Collectors.joining( " " ) );

        System.out.println( "Validator IDs: " + idString );

        return idString;
    }

    public class SimpleScore implements Serializable
    {
        private static final long serialVersionUID = 1L;

        private List<SimplePlayerStat> playerStats;

        public List<SimplePlayerStat> getPlayerStats()
        {
            return playerStats;
        }

        public void setPlayerStats( List<SimplePlayerStat> playerStats )
        {
            this.playerStats = playerStats;
        }
    }

    public class SimplePlayerStat implements Serializable
    {
        private static final long serialVersionUID = 1L;

        private String name;
        private Integer jerseyNbr;

        public SimplePlayerStat( String name, Integer jerseyNbr )
        {
            this.name = name;
            this.jerseyNbr = jerseyNbr;
        }

        public String getName()
        {
            return name;
        }

        public void setName(String name)
        {
            this.name = name;
        }

        public Integer getJerseyNbr()
        {
            return jerseyNbr;
        }

        public void setJerseyNbr(Integer jerseyNbr)
        {
            this.jerseyNbr = jerseyNbr;
        }
    }
}

Facelet:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>

    <f:view>

        <h:head>
        </h:head>

        <h:body>

Game Manager

                <h:form id="score-input-form">

                        <f:facet name="header">
                            Home Team
                        </f:facet>

                            <h:outputText value="#{obj.name}" />

                    <o:validateMultiple id="home-validator"
                                        components=":score-input-form:home-box-score-table:0:jersey-nbr-input :score-input-form:home-box-score-table:1:jersey-nbr-input"
                                       omponents="@form:home-box-score-table:0:jersey-nbr-input"
                                       mponents="#{debugTableValidateMultipleManager.validatorIds}"
                                        validator="#{debugTableValidateMultipleManager.validateJerseyNbrs}" />

                </h:form>

        </h:body>

    </f:view>

QUESTION:

Why isn't it working?

Is it a bug/missing feature in OmniFaces?

Looking at the OmniFaces code in ValidateMultipleFields class

private UIInput findInputComponent(UIComponent parent, String clientId, PropertyKeys property) {

    UIComponent found = parent.findComponent(clientId);     <-- results in null!

    if (found == null) {
        throw new IllegalArgumentException(format(
            ERROR_UNKNOWN_COMPONENT, getClass().getSimpleName(), property, clientId));
    }
    else if (!(found instanceof UIInput)) {
        throw new IllegalArgumentException(format(
            ERROR_INVALID_COMPONENT, getClass().getSimpleName(), property, clientId, found.getClass().getName()));
    }

    return (UIInput) found;
}

and looking at the generated HTML...

... the IDs I'm using seem to be right and the search policy parent.findComponent(clientId) might not be working for iterative components like p:dataTable and p:treeTable... ♂

I'd be glad if someone could have a look at this.

Maybe there's another solution for this, but I simple cannot see it, so if there's another way to validate multiple inputs in a p:dataTable or p:treeTable please let me know.

EDIT:

I used p:dataTable to explain my problem, however I didn't know that this component has a completely different inheritance hierarchy. p:dataTable extends from UIData, while p:treeTable extends from UITree.

Obviously, hierarchical data is of course more complex.

Here's the real UI I am using:

This results in an exception using o:validateUniqueColumn:

00:02:17,223 SEVERE [javax.enterprise.resource.webcontainer.jsf.context] (default task-2) java.lang.IllegalArgumentException: Parent component of o:validateUniqueColumn must be enclosed in an UIData component.
    at org.omnifaces.taghandler.ValidateUniqueColumn.apply(ValidateUniqueColumn.java:114)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:161)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:203)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:135)
    at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:96)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:161)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:203)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:135)
    at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:96)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:161)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:203)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:135)
    at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:96)
    at com.sun.faces.facelets.tag.ui.CompositionHandler.apply(CompositionHandler.java:195)
    at com.sun.faces.facelets.compiler.NamespaceHandler.apply(NamespaceHandler.java:94)
    at com.sun.faces.facelets.compiler.EncodingHandler.apply(EncodingHandler.java:88)

Body:
The <o:validateMultiple> isn't (yet?) intented to be used this way, targeting a single component within a repeater component. It works only on physically multiple components defined in XHTML source code, not on virtually multiple components produced in HTML output.

For now, just use <o:validateUniqueColumn> instead. It's designed for exactly your use case. It's a taghandler not a component, so just nest it directly in the single input component as below. No need for other configuration.

<p:column>
    <p:inputNumber>
        <o:validateUniqueColumn />
    </p:inputNumber>
</p:column>


问:
Flutter ListView in StateLess Widget
as I learned , in StateLessWidget we can't call any thing like setState to rebuild the widget tree and so on.

but when we scroll a listVeiw , the position and ... will change.
but as we in StatelessWidget , I don't know why it is possible to change the State of STL because the ListView has its own offset state and it can change and reflected in User Interface .

答:
ListView is a stateful widget.
Just because you wrap it in a stateless widget does not mean it also becomes stateless.

That's the whole magic, you can have many stateful and stateless widgets wrapped in stateful and stateless widgets...

Title: Flutter ListView in StateLess Widget