问:
MVC Core, Web Sockets and threading
I am working on a solution that uses web socket protocol to notify client (web browser) when some event happened on the server (MVC Core web app). I use Microsoft.AspNetCore.WebSockets nuget.

Here is my client-side code:

```<code>  $(function () {
    var socket = new WebSocket("ws://localhost:61019/data/openSocket");

    socket.onopen = function () {
      $(".socket-status").css("color", "green");
    }

    socket.onmessage = function (message) {
      $("body").append(document.createTextNode(message.data));
    }

    socket.onclose = function () {
      $(".socket-status").css("color", "red");
    }
  });
</code>```

When this view is loaded the socket request is immediately sent to the MVC Core application. Here is the controller action:

```<code>[Route("data")]
public class DataController : Controller
{
    [Route("openSocket")]
    [HttpGet]
    public ActionResult OpenSocket()
    {
        if (HttpContext.WebSockets.IsWebSocketRequest)
        {
            WebSocket socket = HttpContext.WebSockets.AcceptWebSocketAsync().Result;

            if (socket != null && socket.State == WebSocketState.Open)
            {
                while (!HttpContext.RequestAborted.IsCancellationRequested)
                {
                    var response = string.Format("Hello! Time {0}", System.DateTime.Now.ToString());
                    var bytes = System.Text.Encoding.UTF8.GetBytes(response);

                    Task.Run(() => socket.SendAsync(new System.ArraySegment<byte>(bytes),
                        WebSocketMessageType.Text, true, CancellationToken.None));
                    Thread.Sleep(3000);
                }
            }
        }
        return new StatusCodeResult(101);
    }
}
</code>```

This code works very well. WebSocket here is used exclusively for sending and doesn't receive anything. The problem, however, is that the while loop keeps holding the DataController thread until cancellation request is detected.

Web socket here is bound to the HttpContext object. As soon as HttpContext for the web request is destroyed the socket connection is immediately closed.

Question 1: Is there any way that socket can be preserved outside of the controller thread?
I tried putting it into a singleton that lives in the MVC Core Startup class that is running on the main application thread. Is there any way to keep the socket open or establish connection again from within the main application thread rather than keep holding the controller thread with a while loop?
Even if it is deemed to be OK to hold up controller thread for socket connection to remain open, I cannot think of any good code to put inside the OpenSocket's while loop. What do you think about having a manual reset event in the controller and wait for it to be set inside the while loop within OpenSocket action?

Question 2: If it is not possible to separate HttpContext and WebSocket objects in MVC, what other alternative technologies or development patterns can be utilized to achieve socket connection reuse? If anyone thinks that SignalR or a similar library has some code allowing to have socket independent from HttpContext, please share some example code. If someone thinks there is a better alternative to MVC for this particular scenario, please provide an example, I do not mind switching to pure ASP.NET or Web API, if MVC does not have capabilities to handle independent socket communication.

Question 3: The requirement is to keep socket connection alive or be able to reconnect until explicit timeout or cancel request by the user. The idea is that some independent event happens on the server that triggers established socket to send data.
If you think that some technology other than web sockets would be more useful for this scenario (like HTML/2 or streaming), could you please describe the pattern and frameworks you would use?

P.S. Possible solution would be to send AJAX requests every second to ask if there was new data on the server. This is the last resort.

答:
After lengthy research I ended up going with a custom middleware solution. Here is my middleware class:

```<code>        public class SocketMiddleware
    {
        private static ConcurrentDictionary<string, SocketMiddleware> _activeConnections = new ConcurrentDictionary<string, SocketMiddleware>();
        private string _packet;

        private ManualResetEvent _send = new ManualResetEvent(false);
        private ManualResetEvent _exit = new ManualResetEvent(false);
        private readonly RequestDelegate _next;

        public SocketMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public void Send(string data)
        {
            _packet = data;
            _send.Set();
        }

        public async Task Invoke(HttpContext context)
        {
            if (context.WebSockets.IsWebSocketRequest)
            {
                string connectionName = context.Request.Query["connectionName"]);
                if (!_activeConnections.Any(ac => ac.Key == connectionName))
                {
                    WebSocket socket = await context.WebSockets.AcceptWebSocketAsync();
                    if (socket == null || socket.State != WebSocketState.Open)
                    {
                        await _next.Invoke(context);
                        return;
                    }
                    Thread sender = new Thread(() => StartSending(socket));
                    sender.Start();

                    if (!_activeConnections.TryAdd(connectionName, this))
                    {
                        _exit.Set();
                        await _next.Invoke(context);
                        return;
                    }

                    while (true)
                    {
                        WebSocketReceiveResult result = socket.ReceiveAsync(new ArraySegment<byte>(new byte[1]), CancellationToken.None).Result;
                        if (result.CloseStatus.HasValue)
                        {
                            _exit.Set();
                            break;
                        }
                    }

                    SocketHandler dummy;
                    _activeConnections.TryRemove(key, out dummy);
                }
            }

            await _next.Invoke(context);

            string data = context.Items["Data"] as string;
            if (!string.IsNullOrEmpty(data))
            {
                string name = context.Items["ConnectionName"] as string;
                SocketMiddleware connection = _activeConnections.Where(ac => ac.Key == name)?.Single().Value;
                if (connection != null)
                {
                    connection.Send(data);
                }
            }
        }

        private void StartSending(WebSocket socket)
        {
            WaitHandle[] events = new WaitHandle[] { _send, _exit };
            while (true)
            {
                if (WaitHandle.WaitAny(events) == 1)
                {
                    break;
                }

                if (!string.IsNullOrEmpty(_packet))
                {
                    SendPacket(socket, _packet);
                }
                _send.Reset();
            }
        }

        private void SendPacket(WebSocket socket, string packet)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(packet);
            ArraySegment<byte> segment = new ArraySegment<byte>(buffer);
            Task.Run(() => socket.SendAsync(segment, WebSocketMessageType.Text, true, CancellationToken.None));
        }
    }
</code>```

This middleware is going to run on every request. When Invoke is called it checks if it is a web socket request. If it is, the middleware checks if such connection was already opened and if it wasn't, the handshake is accepted and the middleware adds it to the dictionary of connections. It's important that the dictionary is static so that it is created only once during application lifetime.

Now if we stop here and move up the pipeline, HttpContext will eventually get destroyed and, since the socket is not properly encapsulated, it will be closed too. So we must keep the middleware thread running. It is done by asking socket to receive some data.

You may ask why we need to receive anything if the requirement is just to send? The answer is that it is the only way to reliably detect client disconnecting. HttpContext.RequestAborted.IsCancellationRequested works only if you constantly send within the while loop. If you need to wait for some server event on a WaitHandle, cancellation flag is never true. I tried to wait for HttpContext.RequestAborted.WaitHandle as my exit event, but it is never set either. So we ask socket to receive something and if that something sets CloseStatus.HasValue to true, we know that client disconnected. If we receive something else (client side code is unsafe) we will ignore it and start receiving again.

Sending is done in a separate thread. The reason is the same, it's not possible to detect disconnection if we wait on the main middleware thread. To notify the sender thread that client disconnected we use _exit synchronization variable. Remember, it is fine to have private members here since SocketMiddleware instances are saved in a static container.

Now, how do we actually send anything with this set up? Let's say an event occurs on the server and some data becomes available. For simplicity sake, lets assume this data arrives inside normal http request to some controller action. SocketMiddleware will run for every request, but since it is not web socket request, _next.Invoke(context) is called and the request reaches controller action which may look something like this:

```<code>[Route("ProvideData")]
[HttpGet]
public ActionResult ProvideData(string data, string connectionName)
{
    if (!string.IsNullOrEmpty(data) && !string.IsNullOrEmpty(connectionName))
    {
        HttpContext.Items.Add("ConnectionName", connectionName);
        HttpContext.Items.Add("Data", data);
    }
        return Ok();
}
</code>```

Controller populates Items collection which is used to share data between components. Then the pipeline returns to the SocketMiddleware again where we check whether there is anything interesting inside the context.Items. If there is we select respective connection from the dictionary and call its Send() method that sets data string and sets _send event and allows single run of the while loop inside the sender thread.

And voila, we a have socket connection that sends on server side event. This example is very primitive and is there just to illustrate the concept. Of course, to use this middleware you will need to add the following lines in your Startup class before you add MVC:

```<code>app.UseWebSockets();
app.UseMiddleware<SocketMiddleware>();
</code>```

Code is very strange and hopefully we'll be able to write something much nicer when SignalR for dotnetcore is finally out. Hopefully this example will be useful for someone. Comments and suggestions are welcome.

Title: MVC Core, Web Sockets and threading

Body:
I am working on a solution that uses web socket protocol to notify client (web browser) when some event happened on the server (MVC Core web app). I use Microsoft.AspNetCore.WebSockets nuget.

Here is my client-side code:

  $(function () {
    var socket = new WebSocket("ws://localhost:61019/data/openSocket");

    socket.onopen = function () {
      $(".socket-status").css("color", "green");
    }

    socket.onmessage = function (message) {
      $("body").append(document.createTextNode(message.data));
    }

    socket.onclose = function () {
      $(".socket-status").css("color", "red");
    }
  });

When this view is loaded the socket request is immediately sent to the MVC Core application. Here is the controller action:

[Route("data")]
public class DataController : Controller
{
    [Route("openSocket")]
    [HttpGet]
    public ActionResult OpenSocket()
    {
        if (HttpContext.WebSockets.IsWebSocketRequest)
        {
            WebSocket socket = HttpContext.WebSockets.AcceptWebSocketAsync().Result;

            if (socket != null && socket.State == WebSocketState.Open)
            {
                while (!HttpContext.RequestAborted.IsCancellationRequested)
                {
                    var response = string.Format("Hello! Time {0}", System.DateTime.Now.ToString());
                    var bytes = System.Text.Encoding.UTF8.GetBytes(response);

                    Task.Run(() => socket.SendAsync(new System.ArraySegment<byte>(bytes),
                        WebSocketMessageType.Text, true, CancellationToken.None));
                    Thread.Sleep(3000);
                }
            }
        }
        return new StatusCodeResult(101);
    }
}

This code works very well. WebSocket here is used exclusively for sending and doesn't receive anything. The problem, however, is that the while loop keeps holding the DataController thread until cancellation request is detected.

Web socket here is bound to the HttpContext object. As soon as HttpContext for the web request is destroyed the socket connection is immediately closed.

Question 1: Is there any way that socket can be preserved outside of the controller thread?
I tried putting it into a singleton that lives in the MVC Core Startup class that is running on the main application thread. Is there any way to keep the socket open or establish connection again from within the main application thread rather than keep holding the controller thread with a while loop?
Even if it is deemed to be OK to hold up controller thread for socket connection to remain open, I cannot think of any good code to put inside the OpenSocket's while loop. What do you think about having a manual reset event in the controller and wait for it to be set inside the while loop within OpenSocket action?

Question 2: If it is not possible to separate HttpContext and WebSocket objects in MVC, what other alternative technologies or development patterns can be utilized to achieve socket connection reuse? If anyone thinks that SignalR or a similar library has some code allowing to have socket independent from HttpContext, please share some example code. If someone thinks there is a better alternative to MVC for this particular scenario, please provide an example, I do not mind switching to pure ASP.NET or Web API, if MVC does not have capabilities to handle independent socket communication.

Question 3: The requirement is to keep socket connection alive or be able to reconnect until explicit timeout or cancel request by the user. The idea is that some independent event happens on the server that triggers established socket to send data.
If you think that some technology other than web sockets would be more useful for this scenario (like HTML/2 or streaming), could you please describe the pattern and frameworks you would use?

P.S. Possible solution would be to send AJAX requests every second to ask if there was new data on the server. This is the last resort.

Body:
After lengthy research I ended up going with a custom middleware solution. Here is my middleware class:

        public class SocketMiddleware
    {
        private static ConcurrentDictionary<string, SocketMiddleware> _activeConnections = new ConcurrentDictionary<string, SocketMiddleware>();
        private string _packet;

        private ManualResetEvent _send = new ManualResetEvent(false);
        private ManualResetEvent _exit = new ManualResetEvent(false);
        private readonly RequestDelegate _next;

        public SocketMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public void Send(string data)
        {
            _packet = data;
            _send.Set();
        }

        public async Task Invoke(HttpContext context)
        {
            if (context.WebSockets.IsWebSocketRequest)
            {
                string connectionName = context.Request.Query["connectionName"]);
                if (!_activeConnections.Any(ac => ac.Key == connectionName))
                {
                    WebSocket socket = await context.WebSockets.AcceptWebSocketAsync();
                    if (socket == null || socket.State != WebSocketState.Open)
                    {
                        await _next.Invoke(context);
                        return;
                    }
                    Thread sender = new Thread(() => StartSending(socket));
                    sender.Start();

                    if (!_activeConnections.TryAdd(connectionName, this))
                    {
                        _exit.Set();
                        await _next.Invoke(context);
                        return;
                    }

                    while (true)
                    {
                        WebSocketReceiveResult result = socket.ReceiveAsync(new ArraySegment<byte>(new byte[1]), CancellationToken.None).Result;
                        if (result.CloseStatus.HasValue)
                        {
                            _exit.Set();
                            break;
                        }
                    }

                    SocketHandler dummy;
                    _activeConnections.TryRemove(key, out dummy);
                }
            }

            await _next.Invoke(context);

            string data = context.Items["Data"] as string;
            if (!string.IsNullOrEmpty(data))
            {
                string name = context.Items["ConnectionName"] as string;
                SocketMiddleware connection = _activeConnections.Where(ac => ac.Key == name)?.Single().Value;
                if (connection != null)
                {
                    connection.Send(data);
                }
            }
        }

        private void StartSending(WebSocket socket)
        {
            WaitHandle[] events = new WaitHandle[] { _send, _exit };
            while (true)
            {
                if (WaitHandle.WaitAny(events) == 1)
                {
                    break;
                }

                if (!string.IsNullOrEmpty(_packet))
                {
                    SendPacket(socket, _packet);
                }
                _send.Reset();
            }
        }

        private void SendPacket(WebSocket socket, string packet)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(packet);
            ArraySegment<byte> segment = new ArraySegment<byte>(buffer);
            Task.Run(() => socket.SendAsync(segment, WebSocketMessageType.Text, true, CancellationToken.None));
        }
    }

This middleware is going to run on every request. When Invoke is called it checks if it is a web socket request. If it is, the middleware checks if such connection was already opened and if it wasn't, the handshake is accepted and the middleware adds it to the dictionary of connections. It's important that the dictionary is static so that it is created only once during application lifetime.

Now if we stop here and move up the pipeline, HttpContext will eventually get destroyed and, since the socket is not properly encapsulated, it will be closed too. So we must keep the middleware thread running. It is done by asking socket to receive some data.

You may ask why we need to receive anything if the requirement is just to send? The answer is that it is the only way to reliably detect client disconnecting. HttpContext.RequestAborted.IsCancellationRequested works only if you constantly send within the while loop. If you need to wait for some server event on a WaitHandle, cancellation flag is never true. I tried to wait for HttpContext.RequestAborted.WaitHandle as my exit event, but it is never set either. So we ask socket to receive something and if that something sets CloseStatus.HasValue to true, we know that client disconnected. If we receive something else (client side code is unsafe) we will ignore it and start receiving again.

Sending is done in a separate thread. The reason is the same, it's not possible to detect disconnection if we wait on the main middleware thread. To notify the sender thread that client disconnected we use _exit synchronization variable. Remember, it is fine to have private members here since SocketMiddleware instances are saved in a static container.

Now, how do we actually send anything with this set up? Let's say an event occurs on the server and some data becomes available. For simplicity sake, lets assume this data arrives inside normal http request to some controller action. SocketMiddleware will run for every request, but since it is not web socket request, _next.Invoke(context) is called and the request reaches controller action which may look something like this:

[Route("ProvideData")]
[HttpGet]
public ActionResult ProvideData(string data, string connectionName)
{
    if (!string.IsNullOrEmpty(data) && !string.IsNullOrEmpty(connectionName))
    {
        HttpContext.Items.Add("ConnectionName", connectionName);
        HttpContext.Items.Add("Data", data);
    }
        return Ok();
}

Controller populates Items collection which is used to share data between components. Then the pipeline returns to the SocketMiddleware again where we check whether there is anything interesting inside the context.Items. If there is we select respective connection from the dictionary and call its Send() method that sets data string and sets _send event and allows single run of the while loop inside the sender thread.

And voila, we a have socket connection that sends on server side event. This example is very primitive and is there just to illustrate the concept. Of course, to use this middleware you will need to add the following lines in your Startup class before you add MVC:

app.UseWebSockets();
app.UseMiddleware<SocketMiddleware>();

Code is very strange and hopefully we'll be able to write something much nicer when SignalR for dotnetcore is finally out. Hopefully this example will be useful for someone. Comments and suggestions are welcome.


来源: stackexchange

问:
back to back or gates with object comparisons. Confusion
To put it simply, i do not understand why they second if statement did not return false for the example (null, null)</p>

```<code>function deepEqual(a, b) {
  if (a === b) return true;

  if (a == null || typeof a != "object" ||
      b == null || typeof b != "object")
    return false;

  var propsInA = 0, propsInB = 0;

  for (var prop in a)
    propsInA += 1;

  for (var prop in b) {
    propsInB += 1;
    if (!(prop in a) || !deepEqual(a[prop], b[prop]))
      return false;
  }

  return propsInA == propsInB;
}

var obj = {here: {is: "an"}, object: 2};
console.log(deepEqual(obj, obj));
// → true
console.log(deepEqual(obj, {here: 1, object: 2}));
// → false
console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
// → true
</code>```

答: If your code execute return, the next code will not being executed..</p>

ContentLicense: CC BY-SA 3.0

Body:
To put it simply, i do not understand why they second if statement did not return false for the example (null, null)

function deepEqual(a, b) {
  if (a === b) return true;

  if (a == null || typeof a != "object" ||
      b == null || typeof b != "object")
    return false;

  var propsInA = 0, propsInB = 0;

  for (var prop in a)
    propsInA += 1;

  for (var prop in b) {
    propsInB += 1;
    if (!(prop in a) || !deepEqual(a[prop], b[prop]))
      return false;
  }

  return propsInA == propsInB;
}

var obj = {here: {is: "an"}, object: 2};
console.log(deepEqual(obj, obj));
// → true
console.log(deepEqual(obj, {here: 1, object: 2}));
// → false
console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
// → true


问:
The best way to let asp.net fire events and methods automatically -according to a schedule-
Well, I'm sure this is not the first time to see this question. and TBH you can find this question answered on many other websites and blogs -not only here-

But I never saw a complete answer for this question, I mean no one talked about the advantages and the disadvantages. no one shared a real experience.

Although Quartz.NET seems like a good solution but yet, there's no enough reviews or a good comparison between the different ways to achieve such a thing.

As far as I read about it I found this are the possible ways of doing this :

Using a:  Web Service, Windows Appliction, Console Application, Quartz.NET.

Examples of stuff I want to achieve with the scheduled or automatic methods/events are like archiving after a certain period, auto deleting/moving records in the database, setting a property of an object after a certain time, automatically run some methods according to my holiday schedule.

I hope you'd share your experience either with one of those approaches or share a new way of doing this.

答:
The obvious problem will be that a web application is intended as a request-response service. So, although probably hackable (and surely people have), you would need to respond to a request in order to kick off some sort of processing task. I know you want a webforms solution, but I would suggest this type of problem domain is not best solved with a web platform.

As a suggestion, although maybe not one you wanted to hear, you could of course use a Windows Service solution and all the good things that go with that platform (background timers, MSMQ processing, threading, easier security integration, etc) and surface it's information via a web based UI application (connected via WCF).

ContentLicense: CC BY-SA 2.5


问:
How properly set up transition opacity effect
I cannot make transition effect, when  in @media 700 i set  display: none, but i want make my .content with full screen in @media 700px, how i can do that?

body {
  background-color: #eee;

}

.header {
  height: 50px;
  width: 100%;
  border-bottom: 1px solid #999;
}

.container {
  min-width: 500px;
  max-width: 800px;
  height: auto;
  margin: 0 auto;
  background-color: #fff;
  display: table;
}

.container::after {
  content: "";
  display: block;
  clear: both;
}

.content {
  padding: 0 15px 0 0;
  display: table-cell;
  width: 485px;
}

.sidebar {
  color: white;
  width: 300px;
  border-left: 1px solid #ccc;
  box-shadow: -15px 0 10px rgba(51, 51, 51, .5);
  opacity: 1;
  transition: opacity .25s;
  background: #000;
  display: table-cell;
  height: 80vh;
}

.footer {
  background-color: #eee;
  width: 100%;
  height: 50px;
  border-top: 1px solid #999;
  position: relative;
  bottom: 0;
}

@media screen and (max-width: 800px) {

  .container {
    width: 100%;
  }
}
@media screen and (max-width: 500px) {

  .container {
    width: 500px;
  }
}
@media screen and (max-width: 700px) {
  .content {
    height: 80vh;
    padding: 0;
    display: block;
    margin: 0 auto;
  }

  .sidebar {
    opacity: 0;
    display: none;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>
</head>
<body>

  <div class="header">
    </div>

    <div class="container">
      <div class="content">
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Porro maxime eligendi libero minus officiis inventore debitis, earum vero perferendis ut iste corrupti culpa. Consequuntur minus natus earum voluptas quos asperiores.
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Porro maxime eligendi libero minus officiis inventore debitis, earum vero perferendis ut iste corrupti culpa. Consequuntur minus natus earum voluptas quos asperiores.
      </div>
      <div class="sidebar">

      </div>
    </div>

    <div class="footer">
    </div>
</body>
</html></code>```

答:
For sidebar remove opacity and make width as transition property and make its width to zero in media 700 and also add width as transition property to content and make its width to 100% in media 700

body {
  background-color: #eee;

}

.header {
  height: 50px;
  width: 100%;
  border-bottom: 1px solid #999;
}

.container {
  min-width: 500px;
  max-width: 800px;
  height: auto;
  margin: 0 auto;
  background-color: #fff;
  display: table;
}

.container::after {
  content: "";
  display: block;
  clear: both;
}

.content {
  padding: 0 15px 0 0;
  display: table-cell;
  width: 485px;
  transition: width .25s;
}

.sidebar {
  color: white;
  width: 300px;
  border-left: 1px solid #ccc;
  box-shadow: -15px 0 10px rgba(51, 51, 51, .5);
  transition: width .25s;
  background: #000;
  display: table-cell;
  height: 80vh;
}

.footer {
  background-color: #eee;
  width: 100%;
  height: 50px;
  border-top: 1px solid #999;
  position: relative;
  bottom: 0;
}

@media screen and (max-width: 800px) {

  .container {
    width: 100%;
  }
}
@media screen and (max-width: 500px) {

  .container {
    width: 500px;
  }
}
@media screen and (max-width: 700px) {
  .content {
    height: 80vh;
    padding: 0;
    display: block;
    margin: 0 auto;
    width: 100%;

  }

  .sidebar {
    width: 0px;
    box-shadow: none;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>
</head>
<body>

  <div class="header">
    </div>

    <div class="container">
      <div class="content">
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Porro maxime eligendi libero minus officiis inventore debitis, earum vero perferendis ut iste corrupti culpa. Consequuntur minus natus earum voluptas quos asperiores.
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Porro maxime eligendi libero minus officiis inventore debitis, earum vero perferendis ut iste corrupti culpa. Consequuntur minus natus earum voluptas quos asperiores.
      </div>
      <div class="sidebar">

      </div>
    </div>

    <div class="footer">
    </div>
</body>
</html></code>```

Body:
I cannot make transition effect, when  in @media 700 i set  display: none, but i want make my .content with full screen in @media 700px, how i can do that?

body {
  background-color: #eee;

}

.header {
  height: 50px;
  width: 100%;
  border-bottom: 1px solid #999;
}

.container {
  min-width: 500px;
  max-width: 800px;
  height: auto;
  margin: 0 auto;
  background-color: #fff;
  display: table;
}

.container::after {
  content: "";
  display: block;
  clear: both;
}

.content {
  padding: 0 15px 0 0;
  display: table-cell;
  width: 485px;
}

.sidebar {
  color: white;
  width: 300px;
  border-left: 1px solid #ccc;
  box-shadow: -15px 0 10px rgba(51, 51, 51, .5);
  opacity: 1;
  transition: opacity .25s;
  background: #000;
  display: table-cell;
  height: 80vh;
}

.footer {
  background-color: #eee;
  width: 100%;
  height: 50px;
  border-top: 1px solid #999;
  position: relative;
  bottom: 0;
}

@media screen and (max-width: 800px) {

  .container {
    width: 100%;
  }
}
@media screen and (max-width: 500px) {

  .container {
    width: 500px;
  }
}
@media screen and (max-width: 700px) {
  .content {
    height: 80vh;
    padding: 0;
    display: block;
    margin: 0 auto;
  }

  .sidebar {
    opacity: 0;
    display: none;
  }
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>

        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Porro maxime eligendi libero minus officiis inventore debitis, earum vero perferendis ut iste corrupti culpa. Consequuntur minus natus earum voluptas quos asperiores.
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Porro maxime eligendi libero minus officiis inventore debitis, earum vero perferendis ut iste corrupti culpa. Consequuntur minus natus earum voluptas quos asperiores.

Body:
For sidebar remove opacity and make width as transition property and make its width to zero in media 700 and also add width as transition property to content and make its width to 100% in media 700

body {
  background-color: #eee;

}

.header {
  height: 50px;
  width: 100%;
  border-bottom: 1px solid #999;
}

.container {
  min-width: 500px;
  max-width: 800px;
  height: auto;
  margin: 0 auto;
  background-color: #fff;
  display: table;
}

.container::after {
  content: "";
  display: block;
  clear: both;
}

.content {
  padding: 0 15px 0 0;
  display: table-cell;
  width: 485px;
  transition: width .25s;
}

.sidebar {
  color: white;
  width: 300px;
  border-left: 1px solid #ccc;
  box-shadow: -15px 0 10px rgba(51, 51, 51, .5);
  transition: width .25s;
  background: #000;
  display: table-cell;
  height: 80vh;
}

.footer {
  background-color: #eee;
  width: 100%;
  height: 50px;
  border-top: 1px solid #999;
  position: relative;
  bottom: 0;
}

@media screen and (max-width: 800px) {

  .container {
    width: 100%;
  }
}
@media screen and (max-width: 500px) {

  .container {
    width: 500px;
  }
}
@media screen and (max-width: 700px) {
  .content {
    height: 80vh;
    padding: 0;
    display: block;
    margin: 0 auto;
    width: 100%;

  }

  .sidebar {
    width: 0px;
    box-shadow: none;
  }
}

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>
</head>
<body>

  <div class="header">
    </div>

    <div class="container">
      <div class="content">
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Porro maxime eligendi libero minus officiis inventore debitis, earum vero perferendis ut iste corrupti culpa. Consequuntur minus natus earum voluptas quos asperiores.
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Porro maxime eligendi libero minus officiis inventore debitis, earum vero perferendis ut iste corrupti culpa. Consequuntur minus natus earum voluptas quos asperiores.
      </div>
      <div class="sidebar">

      </div>
    </div>

    <div class="footer">
    </div>
</body>
</html>


问:
Split or extract a Value from a vector SCALA
I am working with the following list in a text file:

```<code>10,44,22
10,47,12
15,38,3
15,41,30
16,44,15
16,47,18
22,38,21
22,41,42
34,44,40
34,47,36
40,38,39
40,41,42
45,38,27
45,41,30
46,44,45
46,47,48
</code>```

I am creating some indexes to analysis the table, then if each column is (s,p,o) and I create a map that is P -> SO I create it of the form

```<code>val dicP_SO: scala.collection.mutable.Map[Int, Vector[Vector[Int]]] = collection.mutable.Map[Int, Vector[Vector[Int]]]()
</code>```

I read the file, and create the mapping with

```<code>if (dicP_SO.contains(p)) {
   P_SO = dicP_SO.apply(p) :+ Vector(s, o) //To add to the same key the diff
   dicP_SO += (p -> P_SO)                  //(s,o)
}else dicP_SO += (p -> Vector(Vector(s,o)))
</code>```

in this way if I put as key the 38, and I run the following code:

```<code>dicP_SO.getOrElse(38,Vector(0))
</code>```

I get the following:

```<code>Vector(Vector(15, 3), Vector(22, 21), Vector(40, 39), Vector(45, 27))
</code>```

My quetion is the following: I need each vector[Int] that are inside, I try to declare a variable

```<code>val a:Vector[Int] = dicP_SO.getOrElse(yi,Vector(0))
</code>```

I am getting the error that a Vector[Any] does not conform to Vector[Int] and I don't know why is this error and how fix it

答:
You should already have output as you want, you just need a correct way to access them

```<code>scala> val rdd = dicP_SO.getOrElse(38, Vector(0))
rdd: scala.collection.immutable.Vector[Any] = Vector(Vector(15, 3), Vector(22, 21), Vector(40, 39), Vector(45, 27))

scala> rdd.foreach(println)
Vector(15, 3)
Vector(22, 21)
Vector(40, 39)
Vector(45, 27)
</code>```

Edited

If you want to access each vector and assign to a variable you can do

```<code>scala> val v1 = rdd(0)
v1: Any = Vector(15, 3)

scala> println(v1)
Vector(15, 3)
</code>```

Body:
I am working with the following list in a text file:

10,44,22
10,47,12
15,38,3
15,41,30
16,44,15
16,47,18
22,38,21
22,41,42
34,44,40
34,47,36
40,38,39
40,41,42
45,38,27
45,41,30
46,44,45
46,47,48

I am creating some indexes to analysis the table, then if each column is (s,p,o) and I create a map that is P -> SO I create it of the form

val dicP_SO: scala.collection.mutable.Map[Int, Vector[Vector[Int]]] = collection.mutable.Map[Int, Vector[Vector[Int]]]()

I read the file, and create the mapping with

if (dicP_SO.contains(p)) {
   P_SO = dicP_SO.apply(p) :+ Vector(s, o) //To add to the same key the diff
   dicP_SO += (p -> P_SO)                  //(s,o)
}else dicP_SO += (p -> Vector(Vector(s,o)))

in this way if I put as key the 38, and I run the following code:

dicP_SO.getOrElse(38,Vector(0))

I get the following:

Vector(Vector(15, 3), Vector(22, 21), Vector(40, 39), Vector(45, 27))

My quetion is the following: I need each vector[Int] that are inside, I try to declare a variable

val a:Vector[Int] = dicP_SO.getOrElse(yi,Vector(0))

I am getting the error that a Vector[Any] does not conform to Vector[Int] and I don't know why is this error and how fix it

Body:
You should already have output as you want, you just need a correct way to access them

scala> val rdd = dicP_SO.getOrElse(38, Vector(0))
rdd: scala.collection.immutable.Vector[Any] = Vector(Vector(15, 3), Vector(22, 21), Vector(40, 39), Vector(45, 27))

scala> rdd.foreach(println)
Vector(15, 3)
Vector(22, 21)
Vector(40, 39)
Vector(45, 27)

Edited

If you want to access each vector and assign to a variable you can do

scala> val v1 = rdd(0)
v1: Any = Vector(15, 3)

scala> println(v1)
Vector(15, 3)


问:
pyspark - how to reducebykey to get the min of the one element of a tuple only
Suppose we have the following data in a csv file (station code, date, data_type, temperature):

'ITE00100554', '18000101', 'TMIN', -7.5

'ITE00100554', '18000101', 'TMIN', -14.8

'ITE00100554', '18000102', 'TMIN', -7.5

'ITE00100554', '18000102', 'TMIN', -14.9

And I try to find the min temperature with corresponding date. The answer should be: 'ITE00100554', '18000102', 'TMIN', -14.9

Here is my code:

```<code>from pyspark import SparkConf, SparkContext

conf = SparkConf().setMaster("local").setAppName("MinTempDate")
sc = SparkContext(conf = conf)

# parsing (mapping) the input data
def parseLine(line):
    fields = line.split(',')
    stationID = fields[0]
    date = fields[1]
    entryType = fields[2]
    temperature = float(fields[3])
    # creates key/value pairs
    return (stationID, date, entryType, temperature)

lines = sc.textFile("1800.csv")
parsedLines = lines.map(parseLine)

minTemps = parsedLines.filter(lambda x: "TMIN" in x[2])

stationTemps = minTemps.map(lambda x: (x[0], (x[1], x[3])))

minTemps = stationTemps.reduceByKey(lambda x, y: (if x[1] >= y[1] y[0] else x[0],min(x[1], y[1])))
</code>```

My problem is the reduceByKey in the last line as the syntax is incorrect and I do not know how to ensure that I got the min temperature and corresponding date.

If I do:

```<code>minTemps = stationTemps.reduceByKey(lambda x, y: min(x, y))
</code>```

It doesn't work as it will return the minimum of the tuple, which means:
'ITE00100554', '18000101', 'TMIN', -14.8

and it is not what I am looking for.

This post is really close to what I am looking for, however I do not know how to change my syntax to make it work:
Spark Python - how to use reduce by key to get minmum/maximum values

答:
change the syntax for if clause in lambda as,</p>

```<code> minTemps = stationTemps.reduceByKey(lambda x, y: (y[0] if x[1] >= y[1] else x[0],min(x[1],y[1])))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Suppose we have the following data in a csv file (station code, date, data_type, temperature):

'ITE00100554', '18000101', 'TMIN', -7.5

'ITE00100554', '18000101', 'TMIN', -14.8

'ITE00100554', '18000102', 'TMIN', -7.5

'ITE00100554', '18000102', 'TMIN', -14.9

And I try to find the min temperature with corresponding date. The answer should be: 'ITE00100554', '18000102', 'TMIN', -14.9

Here is my code:

from pyspark import SparkConf, SparkContext

conf = SparkConf().setMaster("local").setAppName("MinTempDate")
sc = SparkContext(conf = conf)

# parsing (mapping) the input data
def parseLine(line):
    fields = line.split(',')
    stationID = fields[0]
    date = fields[1]
    entryType = fields[2]
    temperature = float(fields[3])
    # creates key/value pairs
    return (stationID, date, entryType, temperature)

lines = sc.textFile("1800.csv")
parsedLines = lines.map(parseLine)

minTemps = parsedLines.filter(lambda x: "TMIN" in x[2])

stationTemps = minTemps.map(lambda x: (x[0], (x[1], x[3])))

minTemps = stationTemps.reduceByKey(lambda x, y: (if x[1] >= y[1] y[0] else x[0],min(x[1], y[1])))

My problem is the reduceByKey in the last line as the syntax is incorrect and I do not know how to ensure that I got the min temperature and corresponding date.

If I do:

minTemps = stationTemps.reduceByKey(lambda x, y: min(x, y))

It doesn't work as it will return the minimum of the tuple, which means:
'ITE00100554', '18000101', 'TMIN', -14.8

and it is not what I am looking for.

This post is really close to what I am looking for, however I do not know how to change my syntax to make it work:
Spark Python - how to use reduce by key to get minmum/maximum values

Body:
change the syntax for if clause in lambda as,

 minTemps = stationTemps.reduceByKey(lambda x, y: (y[0] if x[1] >= y[1] else x[0],min(x[1],y[1])))


问:
spring-cloud: Disable CSRF
Tried disabling CSRF in the edge/zuul with http.csrf().disable().
But still csrfFilter is available in filter chain @ position 4.
I even have set property spring.enableCsrf: false. Still the csrfFilter kicks in and my ajax requests get 403 error.

How to disable CSRF with Zuul and external OAuth server (UAA)?

答:
Configure CSRF Protection
Some frameworks handle invalid CSRF tokens by invaliding the user’s session, but this causes its own problems. Instead by default Spring Security’s CSRF protection will produce an HTTP 403 access denied. This can be customized by configuring the AccessDeniedHandler to process InvalidCsrfTokenException differently.

As of Spring Security 4.0, CSRF protection is enabled by default with XML configuration. If you would like to disable CSRF protection, the corresponding XML configuration can be seen below.

```<code><http>
    <!-- ... -->
    <csrf disabled="true"/>
</http>
</code>```

CSRF protection is enabled by default with Java Configuration. If you would like to disable CSRF, the corresponding Java configuration can be seen below. Refer to the Javadoc of csrf() for additional customizations in how CSRF protection is configured.

```<code>@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    .csrf().disable();
}
}
</code>```

Title: spring-cloud: Disable CSRF

Body:
Configure CSRF Protection
Some frameworks handle invalid CSRF tokens by invaliding the user’s session, but this causes its own problems. Instead by default Spring Security’s CSRF protection will produce an HTTP 403 access denied. This can be customized by configuring the AccessDeniedHandler to process InvalidCsrfTokenException differently.

As of Spring Security 4.0, CSRF protection is enabled by default with XML configuration. If you would like to disable CSRF protection, the corresponding XML configuration can be seen below.

<http>
    <!-- ... -->
    <csrf disabled="true"/>
</http>

CSRF protection is enabled by default with Java Configuration. If you would like to disable CSRF, the corresponding Java configuration can be seen below. Refer to the Javadoc of csrf() for additional customizations in how CSRF protection is configured.

@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    .csrf().disable();
}
}


问:
if multiple threads are updating the same variable, what should be done so each thread updates the variable correctly?
If multiple threads are updating the same variable, what should I do so each thread updates the variable correctly?

Any help would be greatly appreciated

答:
This is a major problem with multi-threaded applications, and spans more than I could really cover in an answer, so I'll point you to some resources.

http://download.oracle.com/javase/tutorial/essential/concurrency/sync.html

http://www.vogella.de/articles/JavaConcurrency/article.html#concurrencyjava_synchronized

Essentially, you use the synchronized keyword to place a lock around a variable.  This makes sure that the piece of code is only being run once at a time.  You can also place locks around the same object in multiple areas.

Additionally, you need to look out for several pitfalls, such as Deadlock.

http://tutorials.jenkov.com/java-concurrency/deadlock.html

Errors caused by misuse of locks are often very difficult to debug and track down, because they aren't very consistent.  So, you always need to be careful that you put all of your locks in the correct location.


问:
Chronicle Queue Does Not Release First File
I've been experimenting with Chronicle Queue 4.5.27. We are running some tests on a Windows 7x64 VM (Java x64) and sometimes it seems like Chronicle Queue will not ever release the first file that it creates.

We are configured with MINUTELY roll cycles. 1-3 threads can write and there is a single consumer processing on the other end.  I register a StoreFileListener to listen for the onReleased event and I groom the file from there (on Windows it tries a few times because of the known issue with mmap files).

The issue is that I never get a notification about the first file the queue creates and a heap dump shows that someone is holding on to the MappedByteBuffer; otherwise the Queue is working as expected. Is there any reason this might happen?

E.g. I'll see something like this on disk after a while:

20170705-2000.cq4

20170705-2008.cq4

20170705-2009.cq4

Thanks!

答: ( I think ) This is now fixed in the latest version. </p>


问:
how i change my keypad for type mail-id?
I have an EditText box in my android app, and when I click on it to input something, the default input languange is in normal keypad. Can I change it to edit for email-id?

i want @ and .com in my keyboard while entering mail-id .

when i try to use maildId.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
 it show error Fatal exception .

答:
You can use input type as:</p>

```<code>            <EditText

                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/email"
                android:inputType="textEmailAddress"
              />
</code>```

Body:
You can use input type as:

            <EditText

                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/email"
                android:inputType="textEmailAddress"
              />


问:
How to open CoreData database file to see saved values
Right now i am using coredata to save my data.
Its all working fine but now i changed the logic to save values to the database. So i need to compare that the after logic change same values are getting saved in tables. So I need to compare tables.

I went through many links like
link 1
link 2

all the links shows that the database file that coredata create is of .sqlite extension. But the files create at that location are "persistentStore, persistentStore-shm, persistentStore-wal" as show in screenshot.

How should i suppose to open these files to see the saved data in tables.
Thanks in advance

```<code> - (void)setupDatabase:(void (^)(BOOL))completionHandler
{

    NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    url = [url URLByAppendingPathComponent:@"MainDataModel"];

    self.db = [[CWUIManagedDocument alloc] initWithFileURL:url];

    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                                                  [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                                                  [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

    self.db.persistentStoreOptions = options;

    if(![[NSFileManager defaultManager] fileExistsAtPath:[self.db.fileURL path]])
    {
        [self.db saveToURL:self.db.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
            self.dataManager.db = self.db;
            completionHandler(success);
        }];
    } else if (self.db.documentState == UIDocumentStateClosed) {
        [self.db openWithCompletionHandler:^(BOOL success) {
            self.dataManager.db = self.db;
            completionHandler(success);
        }];
    }
}
</code>```

答:
In setupDatabase() method replace the following line

```<code> url = [url URLByAppendingPathComponent:@"MainDataModel"]
</code>```

with

```<code> url = [url URLByAppendingPathComponent:@"MainDataModel.sqlite"]
</code>```

You have to create the persistent store type as Sqlite

Body:
Right now i am using coredata to save my data.
Its all working fine but now i changed the logic to save values to the database. So i need to compare that the after logic change same values are getting saved in tables. So I need to compare tables.

I went through many links like
link 1
link 2

all the links shows that the database file that coredata create is of .sqlite extension. But the files create at that location are "persistentStore, persistentStore-shm, persistentStore-wal" as show in screenshot.

How should i suppose to open these files to see the saved data in tables.
Thanks in advance

 - (void)setupDatabase:(void (^)(BOOL))completionHandler
{

    NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    url = [url URLByAppendingPathComponent:@"MainDataModel"];

    self.db = [[CWUIManagedDocument alloc] initWithFileURL:url];

    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                                                  [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                                                  [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

    self.db.persistentStoreOptions = options;

    if(![[NSFileManager defaultManager] fileExistsAtPath:[self.db.fileURL path]])
    {
        [self.db saveToURL:self.db.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
            self.dataManager.db = self.db;
            completionHandler(success);
        }];
    } else if (self.db.documentState == UIDocumentStateClosed) {
        [self.db openWithCompletionHandler:^(BOOL success) {
            self.dataManager.db = self.db;
            completionHandler(success);
        }];
    }
}

Body:
In setupDatabase() method replace the following line

 url = [url URLByAppendingPathComponent:@"MainDataModel"]

with

 url = [url URLByAppendingPathComponent:@"MainDataModel.sqlite"]

You have to create the persistent store type as Sqlite


问:
angular2 display message if field value is invalid
I have the following field in an angular2 page (I am not using forms).

```<code><input id="firstname" name="firstname" class="field-input field-validation-input" [(ngModel)]="firstname"
                    placeholder="First name" spellcheck="false" required #firstNameField>
</code>```

Now I want to display a message at the bottom of the field if it is invalid, in this scenario if it is empty.  What is the best way to do this, I can use firstNameField.className but as you can see there are a number of classes here and trying to filter for ng-invalid might be a problem

答:
Use

```<code>#firstNameField="ngModel"
</code>```

so that this template variable references the NgModel directive, and thus have access to all its properties and methods:

```<code><div *ngIf="!firstNameField.valid">Houston, we have a problem</div>
</code>```

or

```<code><div *ngIf="firstNameField.hasError('required')">The first name is required</div>
</code>```

Body:
I have the following field in an angular2 page (I am not using forms).

<input id="firstname" name="firstname" class="field-input field-validation-input" [(ngModel)]="firstname"
                    placeholder="First name" spellcheck="false" required #firstNameField>

Now I want to display a message at the bottom of the field if it is invalid, in this scenario if it is empty.  What is the best way to do this, I can use firstNameField.className but as you can see there are a number of classes here and trying to filter for ng-invalid might be a problem

Body:
Use

#firstNameField="ngModel"

so that this template variable references the NgModel directive, and thus have access to all its properties and methods:

<div *ngIf="!firstNameField.valid">Houston, we have a problem</div>

or

<div *ngIf="firstNameField.hasError('required')">The first name is required</div>


问:
Updating Webpage from Within Thread
I have a webpage that runs a lengthy procedure, it's all working apart from displaying the progress on the page.

I have the following progress bar (Bootstrap):

```<code><div class="col-md-8">
  <label for="product-feed-progress">Progress</label>
    <div class="progress">
     <div class="progress-bar" role="progressbar" runat="server" id="prgProdFeed" style="min-width: 0em; width: 0%;">
                                    0%
     </div>
  </div>
</div>
</code>```

During the thread, I have the following snippet that adjusts the width property of prgProdFeed:

```<code>prgProdFeed.Attributes.Add("style", "width:" & ((p_objFeedInfo.Progress / p_objFeedInfo.Total) * 100).ToString() + "%")
</code>```

I have also tried:

```<code>prgProdFeed.Style.Item("width") = ((p_objFeedInfo.Progress / p_objFeedInfo.Total) * 100).ToString() + "%"
</code>```

They both change the width property of the bar which currently sits in an update panel (updated on the tick of a timer).

How come my progress bar is not updating on the page? I can see using the inspector that the update panel is refreshing, and in the debugger it's showing the width being correct - just nothing changes visually.

Any help would be appreciated.

答:
"width" is not the right property for a bargraph object. Usually, width denotes the width of the entire object.

You need to  look for a "value" property instead of "width"

Title: Updating Webpage from Within Thread

Body:
I have a webpage that runs a lengthy procedure, it's all working apart from displaying the progress on the page.

I have the following progress bar (Bootstrap):

  Progress

                                    0%

During the thread, I have the following snippet that adjusts the width property of prgProdFeed:

prgProdFeed.Attributes.Add("style", "width:" & ((p_objFeedInfo.Progress / p_objFeedInfo.Total) * 100).ToString() + "%")

I have also tried:

prgProdFeed.Style.Item("width") = ((p_objFeedInfo.Progress / p_objFeedInfo.Total) * 100).ToString() + "%"

They both change the width property of the bar which currently sits in an update panel (updated on the tick of a timer).

How come my progress bar is not updating on the page? I can see using the inspector that the update panel is refreshing, and in the debugger it's showing the width being correct - just nothing changes visually.

Any help would be appreciated.


问:
How can I make youtube video fit the screen?
I am loading a youtube video using an iFrame. With the current code the video's margins are slightly cropped (thumbnail image included). What do I have to change in order to make it fit the screen with black background beneath? To test just paste this code in an html file and run it in browser. Window resize shows the issue.</p>

```<code><html>
    <head>
        <title>Youtube Video</title>
        <meta name='viewport' content='width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no'/>
    </head>
    <body bgcolor='white' marginwidth='0' marginheight='0'>
        <!-- The <iframe> (and video player) will replace this <div> tag. -->
        <div id='player'></div>
        <script>
            var tag = document.createElement('script');
            tag.src = 'https://www.youtube.com/iframe_api';
            var firstScriptTag = document.getElementsByTagName('script')[0];
            firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

            var player;
            function onYouTubeIframeAPIReady() {
                player = new YT.Player('player', {
                    playerVars: { 'iv_load_policy': 3, 'controls': 1, 'rel': 0, 'showinfo': 0, 'fs': 0 },
                    frameborder: '0',
                    height: '100%',
                    width: '100%',
                    videoId: 'axZ1e0_2ysc',
                    events: {
                        'onReady': onPlayerReady,
                        'onStateChange': onPlayerStateChange
                    }
                });
            }

            function onPlayerReady(event) {
                document.title = '0';
            }

            function onPlayerStateChange(event) {
                if (event.data == YT.PlayerState.PLAYING) {
                    document.title = '1';
                } else if (event.data == YT.PlayerState.ENDED || event.data == YT.PlayerState.PAUSED) {
                    document.title = '2';
                }
            }
        </script>
    </body>
</html>
</code>```

答:
Add the following CSS to your site to make body of your page 100% of the viewport:

```<code>body {
    height: 100vh;
}
</code>```

Example: https://codepen.io/anon/pen/EXpmWR

Or you can use CSS to set the widht and height of the iframe element:

```<code>iframe {
  width: 100vw;
  height: 100vh;
}
</code>```

Example: https://codepen.io/anon/pen/gRjWWb

Body:
I am loading a youtube video using an iFrame. With the current code the video's margins are slightly cropped (thumbnail image included). What do I have to change in order to make it fit the screen with black background beneath? To test just paste this code in an html file and run it in browser. Window resize shows the issue.

        <title>Youtube Video</title>
        <meta name='viewport' content='width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no'/>

Body:
Add the following CSS to your site to make body of your page 100% of the viewport:

body {
    height: 100vh;
}

Example: https://codepen.io/anon/pen/EXpmWR

Or you can use CSS to set the widht and height of the iframe element:

iframe {
  width: 100vw;
  height: 100vh;
}

Example: https://codepen.io/anon/pen/gRjWWb


问:
eslint rules / fasle check: if compare condition
The rules i am looking for will
Showing error for

```<code>if(!package)
</code>```

because it is better to have

```<code>if(typeof(package) !== 'undefine')
</code>```

答:
had chat at eslint page, @ljharb sorted it out for me,

No, we don't.

Jordan Harband @ljharb

it might be a bug, but it's impossible to know that statically that's
  something unit tests, not linting, has to catch. if you mean == vs
  ===, it's because == is likely to be a bug a falsiness check is not, that's a completely valid pattern that appears all over the place, and
  is correct.

Kevin Partington @platinumazure

@seeliang If you really want more specific checks, you could certainly
  find or write a plugin with a rule that forbids general falsy checks.
  But I don't think that will ever be added to core because it's not
  obviously an error in most cases.

Body:
The rules i am looking for will
Showing error for

if(!package)

because it is better to have

if(typeof(package) !== 'undefine')


问:
JDOM.Element.getChild(String) is returning unexpected results
According to the API at jdom.org, the semantics of getChild(String name):

This returns the first child element within this element with the given local name and belonging to no namespace. If no elements exist for the specified name and namespace, null is returned.

Therefore, if I have an XML structure like:

```<code><?xml version="1.0" encoding="UTF-8"?>
<lvl1>
    <lvl2>
        <lvl3/>
    </lvl2>
</lvl1>
</code>```

I have a JDOM Element which is currently pointing to <lvl1>. I should be able to make the following call:

```<code>Element lvl3 = lvl1Element.getChild("lvl3");
</code>```

and lvl3 should have non-null.

However, I'm finding that lvl3 is actually null.  Am I missing something?

Here is a sample code snippet that should work:

```<code>import java.io.StringReader;
import org.jdom.*;
public static void main(String[] args){
    Document doc = new SAXBuilder().build(new StringReader("path to file"));
    Element lvl1Element = doc.getRootElement();
    Element lvl3Element = lvl1Element.getChild("lvl3"); //is null. Why?
}
</code>```

答:
In order to get the functionality I was looking for, I used an Iterator from the getDescendants(ElementFilter) function from jdom.org

I then got the Element I was looking for by using code similar to the following:

```<code>Element lvl3 = lvl1.getDescendants(new ElementFilter("lvl3"));
</code>```

Body:
According to the API at jdom.org, the semantics of getChild(String name):

This returns the first child element within this element with the given local name and belonging to no namespace. If no elements exist for the specified name and namespace, null is returned.

Therefore, if I have an XML structure like:

<?xml version="1.0" encoding="UTF-8"?>
<lvl1>
    <lvl2>
        <lvl3/>
    </lvl2>
</lvl1>

I have a JDOM Element which is currently pointing to <lvl1>. I should be able to make the following call:

Element lvl3 = lvl1Element.getChild("lvl3");

and lvl3 should have non-null.

However, I'm finding that lvl3 is actually null.  Am I missing something?

Here is a sample code snippet that should work:

import java.io.StringReader;
import org.jdom.*;
public static void main(String[] args){
    Document doc = new SAXBuilder().build(new StringReader("path to file"));
    Element lvl1Element = doc.getRootElement();
    Element lvl3Element = lvl1Element.getChild("lvl3"); //is null. Why?
}

Body:
In order to get the functionality I was looking for, I used an Iterator from the getDescendants(ElementFilter) function from jdom.org

I then got the Element I was looking for by using code similar to the following:

Element lvl3 = lvl1.getDescendants(new ElementFilter("lvl3"));


问:
.htaccess rewrite redirect based on domain name and request uri
I am unable to solve a problem for .htaccess.
The requirement is when user visits

abc.nl/nl_nl/some-content no redirection required.

abc.nl/fr_fr/some-content it should be redirected to abc.fr/fr_fr

Till now my code is this:

```<code>RewriteEngine On

# If the requested uri is  fr_fr
RewriteCond %{REQUEST_URI} !^\/fr_fr\/

# But domain is  abc.nl
RewriteCond %{HTTP_HOST} ^(www\.)?abc\.nl [NC]

# Then redirect to abc.fr/fr_fr/what-ever
RewriteRule ^(.*)$ abc\.fr\/fr_fr\/$1 [NC]
</code>```

Please help.

答:
Try with below only, in root directory,</p>

```<code>RewriteEngine On
RewriteCond %{REQUEST_URI} ^/fr_fr/(.*)
RewriteRule ^ http://abc.fr/fr_fr/%1 [R=301]
</code>```

Body:
I am unable to solve a problem for .htaccess.
The requirement is when user visits

abc.nl/nl_nl/some-content no redirection required.

abc.nl/fr_fr/some-content it should be redirected to abc.fr/fr_fr

Till now my code is this:

RewriteEngine On

# If the requested uri is  fr_fr
RewriteCond %{REQUEST_URI} !^\/fr_fr\/

# But domain is  abc.nl
RewriteCond %{HTTP_HOST} ^(www\.)?abc\.nl [NC]

# Then redirect to abc.fr/fr_fr/what-ever
RewriteRule ^(.*)$ abc\.fr\/fr_fr\/$1 [NC]

Please help.

Body:
Try with below only, in root directory,

RewriteEngine On
RewriteCond %{REQUEST_URI} ^/fr_fr/(.*)
RewriteRule ^ http://abc.fr/fr_fr/%1 [R=301]


问:
jQuery autocomplete is showing empty results
I have this PHP script to get all patient name from my database:

```<code><?php

error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once('connection.php');
header("Content-type:application/json");
$cid = $_SESSION['clinic_id'];

$res = array();
$getPatients = "SELECT * FROM patient WHERE clinic_id = :cid  ORDER BY patient_id DESC";

$execGetPatients = $conn->prepare($getPatients);
$execGetPatients->bindValue(':cid', $cid);
$execGetPatients->execute();
$getPatientsResult = $execGetPatients->fetchAll();

$i = 0;
foreach($getPatientsResult as $result)
{
    $res[$i] = $result;
    $i++;
}

echo json_encode($res);
?>
</code>```

And I have a text box where I want to display the patient_name as autocomplete using jquery-ui autocomplete library.

Here is my jQuery script:

```<code>  $(document).ready(function()
  {
    $( "#searchTxt" ).autocomplete({
      source: "../php/autoComplete.php"
    });
  })
</code>```

I can see that if a type a name at the network tab I can see a returned array:

But at the text box I see that the autocomplete are empty like in the following image:

And it is showing 2 white boxes instead of one that of the returned array

答:
Twitter typeahead.js is the best option to implement this feature.

Please take a look into this to achieve it with PHP, AJAX, and TypeAhead.js

```<code><script>
$(function() {
  $("#searchTxt").typeahead({
    source: function(query, process) {
      var textVal=$("#searchTxt").val();
      $.ajax({
        url: '/php/autoComplete.php', // Please add full URL here
        type: 'POST',
        data: 'term=' + textVal,
        dataType: 'JSON',
        async: true,
        success: function(data) {
          process(data);
          console.log(textVal);
        }
      });
    }
  });
});
</script>
</code>```

link to TypeAhead.js

Let me know if you need any help.

Body:
I have this PHP script to get all patient name from my database:

<?php

error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once('connection.php');
header("Content-type:application/json");
$cid = $_SESSION['clinic_id'];

$res = array();
$getPatients = "SELECT * FROM patient WHERE clinic_id = :cid  ORDER BY patient_id DESC";

$execGetPatients = $conn->prepare($getPatients);
$execGetPatients->bindValue(':cid', $cid);
$execGetPatients->execute();
$getPatientsResult = $execGetPatients->fetchAll();

$i = 0;
foreach($getPatientsResult as $result)
{
    $res[$i] = $result;
    $i++;
}

echo json_encode($res);
?>

And I have a text box where I want to display the patient_name as autocomplete using jquery-ui autocomplete library.

Here is my jQuery script:

  $(document).ready(function()
  {
    $( "#searchTxt" ).autocomplete({
      source: "../php/autoComplete.php"
    });
  })

I can see that if a type a name at the network tab I can see a returned array:

But at the text box I see that the autocomplete are empty like in the following image:

And it is showing 2 white boxes instead of one that of the returned array

Body:
Twitter typeahead.js is the best option to implement this feature.

Please take a look into this to achieve it with PHP, AJAX, and TypeAhead.js

<script>
$(function() {
  $("#searchTxt").typeahead({
    source: function(query, process) {
      var textVal=$("#searchTxt").val();
      $.ajax({
        url: '/php/autoComplete.php', // Please add full URL here
        type: 'POST',
        data: 'term=' + textVal,
        dataType: 'JSON',
        async: true,
        success: function(data) {
          process(data);
          console.log(textVal);
        }
      });
    }
  });
});
</script>

link to TypeAhead.js

Let me know if you need any help.


问:
answer repeating in the foor-loop
I have a data frame which has everyday for a month, and for each day the times every 10 minutes:

```<code>        Date     Time   Temp
0   31/05/2006  09:00   9.3
1   31/05/2006  09:10   10.1
2   31/05/2006  09:20   10.7
</code>```

I am trying to get the time (hh:mm) for the Max(Temp), so I used the function argmax for calculating the index of the Max(Temp)

maxTime = data.iloc[data[data['Date'] == '31/05/2006']['Outside Temperature'].argmax()]['Time']

That's fine, but now I need to calculate this for each day of the month, so I put this inside a loop. First I created the list MaxTempTime for saving the results of my loop:

```<code>MaxTempTime = []
for i in data['Date']:
    maxTime = data.iloc[data[data['Date'] == i ]['Outside Temperature'].argmax()]['Time']
    MaxTempTime.extend(maxTime)
    print maxTime
</code>```

But I get the answer as many times as there are per day, I just need it only once and then go on to the next date

(having periods of 10 min, there are 144 periods of 10 minutes within the 1440 minutes per day, so I get 144 of the same answer per each day)

Can anybody help me sort out this please? Thanks!

答:
I think you need groupby with idxmax for indices of max Temp per group and then select original df by loc:

```<code>df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)
df = df.loc[df.groupby('Date')['Temp'].idxmax()]
print (df)
        Date  Temp   Time
4 2006-05-31  10.9  09:40
8 2006-06-01   9.7  09:30
</code>```

Alternative solution with sort_values, groupby with aggregate last:

```<code>df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)
df = df.sort_values('Temp').groupby('Date', as_index=False).last()
print (df)
        Date  Temp   Time
0 2006-05-31  10.9  09:40
1 2006-06-01   9.7  09:30
</code>```

Title: answer repeating in the foor-loop

Body:
I have a data frame which has everyday for a month, and for each day the times every 10 minutes:

        Date     Time   Temp
0   31/05/2006  09:00   9.3
1   31/05/2006  09:10   10.1
2   31/05/2006  09:20   10.7

I am trying to get the time (hh:mm) for the Max(Temp), so I used the function argmax for calculating the index of the Max(Temp)

maxTime = data.iloc[data[data['Date'] == '31/05/2006']['Outside Temperature'].argmax()]['Time']

That's fine, but now I need to calculate this for each day of the month, so I put this inside a loop. First I created the list MaxTempTime for saving the results of my loop:

MaxTempTime = []
for i in data['Date']:
    maxTime = data.iloc[data[data['Date'] == i ]['Outside Temperature'].argmax()]['Time']
    MaxTempTime.extend(maxTime)
    print maxTime

But I get the answer as many times as there are per day, I just need it only once and then go on to the next date

(having periods of 10 min, there are 144 periods of 10 minutes within the 1440 minutes per day, so I get 144 of the same answer per each day)

Can anybody help me sort out this please? Thanks!

Body:
I think you need groupby with idxmax for indices of max Temp per group and then select original df by loc:

df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)
df = df.loc[df.groupby('Date')['Temp'].idxmax()]
print (df)
        Date  Temp   Time
4 2006-05-31  10.9  09:40
8 2006-06-01   9.7  09:30

Alternative solution with sort_values, groupby with aggregate last:

df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)
df = df.sort_values('Temp').groupby('Date', as_index=False).last()
print (df)
        Date  Temp   Time
0 2006-05-31  10.9  09:40
1 2006-06-01   9.7  09:30


答:
Run these commands on terminal and open yourpersistentStore in sqlite manager. These commands will merge the WAL file into the main sqlite file

```<code>$ sqlite3 persistentStore
sqlite> PRAGMA wal_checkpoint;

Press control + d
</code>```

These steps are already covered in the answer of the above link : https://stackoverflow.com/a/43406516/468724

Title: How to open CoreData database file to see saved values

Body:
Run these commands on terminal and open yourpersistentStore in sqlite manager. These commands will merge the WAL file into the main sqlite file

$ sqlite3 persistentStore
sqlite> PRAGMA wal_checkpoint;

Press control + d

These steps are already covered in the answer of the above link : https://stackoverflow.com/a/43406516/468724


问:
Parse a .ttl file and map it to a Java class
I am new to OWL 2, and I want to parse a ".ttl" file with OWL API, but I found that OWL API is not same as the API I used before. It seems that I should write a "visitor" if I want to get the content within a OWLAxiom or OWLEntity, and so on. I have read some tutorials, but I didn't get the proper way to do it. Also, I found the tutorials searched were use older version of owl api. So I want a detailed example to parse a instance, and store the content to a Java class.

I have made some attempts, my codes are as follows, but I don't know to go on.

```<code>OWLOntologyManager manager = OWLManager.createOWLOntologyManager();

File file = new File("./source.ttl");

OWLOntology localAcademic = manager.loadOntologyFromOntologyDocument(file);

Stream<OWLNamedIndividual> namedIndividualStream = localAcademic.individualsInSignature();

Iterator<OWLNamedIndividual> iterator = namedIndividualStream.iterator();

while (iterator.hasNext()) {

     OWLNamedIndividual namedIndividual = iterator.next();

}
</code>```

Instance for example are as follows. Specially, I want store the "@en" in the object of "ecrm:P3_has_note".

```<code><http://data.doremus.org/performance/4db95574-8497-3f30-ad1e-f6f65ed6c896>
    a                      mus:M42_Performed_Expression_Creation ;
    ecrm:P3_has_note       "Créée par Teodoro Anzellotti, son commanditaire, en novembre 1995 à Rotterdam"@en ;
    ecrm:P4_has_time-span  <http://data.doremus.org/performance/4db95574-8497-3f30-ad1e-f6f65ed6c896/time> ;
    ecrm:P9_consists_of    [ a                        mus:M28_Individual_Performance ;
                             ecrm:P14_carried_out_by  "Teodoro Anzellotti"
                           ] ;
    ecrm:P9_consists_of    [ a                        mus:M28_Individual_Performance ;
                             ecrm:P14_carried_out_by  "à Rotterdam"
                           ] ;
    efrbroo:R17_created    <http://data.doremus.org/expression/2fdd40f3-f67c-30a0-bb03-f27e69b9f07f> ;
    efrbroo:R19_created_a_realisation_of
            <http://data.doremus.org/work/907de583-5247-346a-9c19-e184823c9fd6> ;
    efrbroo:R25_performed  <http://data.doremus.org/expression/b4bb1588-dd83-3915-ab55-b8b70b0131b5> .
</code>```

The contents I want are as follows:

```<code>class Instance{
    String subject;
    Map<String, Set<Object>> predicateToObject = new HashMap<String,Set<Object>>();
}

class Object{
    String value;
    String type;
    String language = null;
}
</code>```

The version of owlapi I am using is 5.1.0. I download the jar and the doc from there. I just want to know how to get the content I need in the java class.

If there are some tutorials that describe the way to do it, please tell me.

Thanks a lot.

Update: I have known how to do it, when I finish it, I will write an answer, I hope it can help latecomers of OWLAPI.

Thanks again.

答:
What you need, once you have the individual, is to retrieve the data property assertion axioms and collect the literals asserted for each property.

So, in the for loop in your code:

```<code>// Let's rename your Object class to Literal so we don't get confused with java.lang.Object
Instance instance = new Instance();
localAcademic.dataPropertyAssertionAxioms()
    .forEach(ax -> instance.predicateToObject.put(
        ax.getProperty().getIRI().toString(),
        Collections.singleton(new Literal(ax.getObject))));
</code>```

This code assumes properties only appear once - if your properties appear multiple times, you'll have to check whether a set already exists for the property and just add to it instead of replacing the value in the map. I left that out to simplify the example.

A visitor is not necessary for this scenario, because you already know what axiom type you're interested in and what methods to call on it. It could have been written as an OWLAxiomVisitor implementing only visit(OWLDataPropertyAssertionAxiom) but in this case there would be little advantage in doing so.

Body:
I am new to OWL 2, and I want to parse a ".ttl" file with OWL API, but I found that OWL API is not same as the API I used before. It seems that I should write a "visitor" if I want to get the content within a OWLAxiom or OWLEntity, and so on. I have read some tutorials, but I didn't get the proper way to do it. Also, I found the tutorials searched were use older version of owl api. So I want a detailed example to parse a instance, and store the content to a Java class.

I have made some attempts, my codes are as follows, but I don't know to go on.

OWLOntologyManager manager = OWLManager.createOWLOntologyManager();

File file = new File("./source.ttl");

OWLOntology localAcademic = manager.loadOntologyFromOntologyDocument(file);

Stream<OWLNamedIndividual> namedIndividualStream = localAcademic.individualsInSignature();

Iterator<OWLNamedIndividual> iterator = namedIndividualStream.iterator();

while (iterator.hasNext()) {

     OWLNamedIndividual namedIndividual = iterator.next();

}

Instance for example are as follows. Specially, I want store the "@en" in the object of "ecrm:P3_has_note".

<http://data.doremus.org/performance/4db95574-8497-3f30-ad1e-f6f65ed6c896>
    a                      mus:M42_Performed_Expression_Creation ;
    ecrm:P3_has_note       "Créée par Teodoro Anzellotti, son commanditaire, en novembre 1995 à Rotterdam"@en ;
    ecrm:P4_has_time-span  <http://data.doremus.org/performance/4db95574-8497-3f30-ad1e-f6f65ed6c896/time> ;
    ecrm:P9_consists_of    [ a                        mus:M28_Individual_Performance ;
                             ecrm:P14_carried_out_by  "Teodoro Anzellotti"
                           ] ;
    ecrm:P9_consists_of    [ a                        mus:M28_Individual_Performance ;
                             ecrm:P14_carried_out_by  "à Rotterdam"
                           ] ;
    efrbroo:R17_created    <http://data.doremus.org/expression/2fdd40f3-f67c-30a0-bb03-f27e69b9f07f> ;
    efrbroo:R19_created_a_realisation_of
            <http://data.doremus.org/work/907de583-5247-346a-9c19-e184823c9fd6> ;
    efrbroo:R25_performed  <http://data.doremus.org/expression/b4bb1588-dd83-3915-ab55-b8b70b0131b5> .

The contents I want are as follows:

class Instance{
    String subject;
    Map<String, Set<Object>> predicateToObject = new HashMap<String,Set<Object>>();
}

class Object{
    String value;
    String type;
    String language = null;
}

The version of owlapi I am using is 5.1.0. I download the jar and the doc from there. I just want to know how to get the content I need in the java class.

If there are some tutorials that describe the way to do it, please tell me.

Thanks a lot.

Update: I have known how to do it, when I finish it, I will write an answer, I hope it can help latecomers of OWLAPI.

Thanks again.

Body:
What you need, once you have the individual, is to retrieve the data property assertion axioms and collect the literals asserted for each property.

So, in the for loop in your code:

// Let's rename your Object class to Literal so we don't get confused with java.lang.Object
Instance instance = new Instance();
localAcademic.dataPropertyAssertionAxioms()
    .forEach(ax -> instance.predicateToObject.put(
        ax.getProperty().getIRI().toString(),
        Collections.singleton(new Literal(ax.getObject))));

This code assumes properties only appear once - if your properties appear multiple times, you'll have to check whether a set already exists for the property and just add to it instead of replacing the value in the map. I left that out to simplify the example.

A visitor is not necessary for this scenario, because you already know what axiom type you're interested in and what methods to call on it. It could have been written as an OWLAxiomVisitor implementing only visit(OWLDataPropertyAssertionAxiom) but in this case there would be little advantage in doing so.


问:
SimpleSchema: How to validate an specific array
As you can see below there is an array parameter passed to the validated method.
For validation I'm using SimpleSchema.

client

```<code>const url = "/articles/bmphCpyHZLhTc74Zp"
example.call({ item: url.split('/') })
</code>```

server

```<code>example = new ValidatedMethod({
    name    : 'example',
    validate: new SimpleSchema({
        item: {
            type: [String]
        }
    }).validator(),

    run({ item }) {
        console.log(item)
    }
})
</code>```

But I would like to validate a bit more specific. So the item array must have three elements.
The first is empty, the second should use a value set by allowedValues and the third is an ID SimpleSchema.RegEx.Id

答:
you can implemented is using custom schema like this.
pass regex as well.

```<code>AddressSchema = new SimpleSchema({
  street: {
    type: String,
    max: 100
  },
  city: {
    type: String,
    max: 50
  },
  state: {
    type: String,
    regEx: /^A[LKSZRAEP]|C[AOT]|D[EC]|F[LM]|G[AU]|HI|I[ADLN]|K[SY]|LA|M[ADEHINOPST]|N[CDEHJMVY]|O[HKR]|P[ARW]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY]$/
  },
  zip: {
    type: String,
    regEx: /^[0-9]{5}$/
  }
});

CustomerSchema = new SimpleSchema({
  billingAddress: {
    type: AddressSchema
  },
  shippingAddresses: {
    type: [AddressSchema],
    minCount: 1
  }
});
</code>```

you can put it like this.

```<code>example = new ValidatedMethod({
    name    : 'example',
    validate: new SimpleSchema({
        item: {
            type: [CustomType],
            regEx: // your regex
        }
    }).validator(),

    run({ item }) {
        console.log(item)
    }
})
</code>```

Body:
As you can see below there is an array parameter passed to the validated method.
For validation I'm using SimpleSchema.

client

const url = "/articles/bmphCpyHZLhTc74Zp"
example.call({ item: url.split('/') })

server

example = new ValidatedMethod({
    name    : 'example',
    validate: new SimpleSchema({
        item: {
            type: [String]
        }
    }).validator(),

    run({ item }) {
        console.log(item)
    }
})

But I would like to validate a bit more specific. So the item array must have three elements.
The first is empty, the second should use a value set by allowedValues and the third is an ID SimpleSchema.RegEx.Id

Body:
you can implemented is using custom schema like this.
pass regex as well.

AddressSchema = new SimpleSchema({
  street: {
    type: String,
    max: 100
  },
  city: {
    type: String,
    max: 50
  },
  state: {
    type: String,
    regEx: /^A[LKSZRAEP]|C[AOT]|D[EC]|F[LM]|G[AU]|HI|I[ADLN]|K[SY]|LA|M[ADEHINOPST]|N[CDEHJMVY]|O[HKR]|P[ARW]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY]$/
  },
  zip: {
    type: String,
    regEx: /^[0-9]{5}$/
  }
});

CustomerSchema = new SimpleSchema({
  billingAddress: {
    type: AddressSchema
  },
  shippingAddresses: {
    type: [AddressSchema],
    minCount: 1
  }
});

you can put it like this.

example = new ValidatedMethod({
    name    : 'example',
    validate: new SimpleSchema({
        item: {
            type: [CustomType],
            regEx: // your regex
        }
    }).validator(),

    run({ item }) {
        console.log(item)
    }
})


问:
Sentence compression using NLP
Using Machine translation, can I obtain a very compressed version of a sentence,
eg. I would really like to have a delicious tasty cup of coffee would be translated to I want coffee
Does any of the NLP engines provide such a functionality?

I got a few research papers that does paraphase generation and sentence compression. But is there any library which has already implemented this?

答:
To start with try using watson NaturalLanguageUnderstanding/Alchemy libraries. Using which I was able to extract important keywords from my statements, example :

Input : Hey! I am having issues with my laptop screen

Output : laptop screen issues hardware.

not just rephrasing but using NLU you can get the following details of your input statement, like for above statement you can get details for the following categories:

Language like “en”, Entities, Concepts, Keywords like "laptop screen“ , “issues” with details like relevance, text, keyword emotion, sentiment.
  Categories with details like labels, relevance score.
  SemanticRoles with details like sentence, it's subject, action and object

Along with this you can use the tone analyzer to get the prominent tone of the statement like, fear, anger, happy, disgust etc.

following is the code sample for watson libraries
note : waston libs are not free but gives one month trial, so you can start with this and then once you get hold of the concepts then switch to other open source libraries and figure out similar libraries and functions

```<code>NaturalLanguageUnderstanding service = new NaturalLanguageUnderstanding(
    NaturalLanguageUnderstanding.VERSION_DATE_2017_02_27,
    WatsonConfiguration.getAlchemyUserName(),
    WatsonConfiguration.getAlchemyPassword());

//ConceptsOptions
ConceptsOptions conceptOptions = new ConceptsOptions.Builder()
    .limit(10)
    .build();

//CategoriesOptions
    CategoriesOptions categoriesOptions = new CategoriesOptions();

//SemanticOptions
SemanticRolesOptions semanticRoleOptions = new SemanticRolesOptions.Builder()
    .entities(true)
    .keywords(true)
    .limit(10)
    .build();

EntitiesOptions entitiesOptions = new EntitiesOptions.Builder()
    .emotion(true)
    .sentiment(true)
    .limit(10)
    .build();

KeywordsOptions keywordsOptions = new KeywordsOptions.Builder()
    .emotion(true)
    .sentiment(true)
    .limit(10)
    .build();

Features features = new Features.Builder()
    .entities(entitiesOptions)
    .keywords(keywordsOptions)
    .concepts(conceptOptions)
    .categories(categoriesOptions)
    .semanticRoles(semanticRoleOptions)
    .build();

AnalyzeOptions parameters = new AnalyzeOptions.Builder()
    .text(inputText)
    .features(features)
    .build();

AnalysisResults response = service
    .analyze(parameters)
    .execute();
System.out.println(response);
</code>```

Title: Sentence compression using NLP

Body:
To start with try using watson NaturalLanguageUnderstanding/Alchemy libraries. Using which I was able to extract important keywords from my statements, example :

Input : Hey! I am having issues with my laptop screen

Output : laptop screen issues hardware.

not just rephrasing but using NLU you can get the following details of your input statement, like for above statement you can get details for the following categories:

Language like “en”, Entities, Concepts, Keywords like "laptop screen“ , “issues” with details like relevance, text, keyword emotion, sentiment.
  Categories with details like labels, relevance score.
  SemanticRoles with details like sentence, it's subject, action and object

Along with this you can use the tone analyzer to get the prominent tone of the statement like, fear, anger, happy, disgust etc.

following is the code sample for watson libraries
note : waston libs are not free but gives one month trial, so you can start with this and then once you get hold of the concepts then switch to other open source libraries and figure out similar libraries and functions

NaturalLanguageUnderstanding service = new NaturalLanguageUnderstanding(
    NaturalLanguageUnderstanding.VERSION_DATE_2017_02_27,
    WatsonConfiguration.getAlchemyUserName(),
    WatsonConfiguration.getAlchemyPassword());

//ConceptsOptions
ConceptsOptions conceptOptions = new ConceptsOptions.Builder()
    .limit(10)
    .build();

//CategoriesOptions
    CategoriesOptions categoriesOptions = new CategoriesOptions();

//SemanticOptions
SemanticRolesOptions semanticRoleOptions = new SemanticRolesOptions.Builder()
    .entities(true)
    .keywords(true)
    .limit(10)
    .build();

EntitiesOptions entitiesOptions = new EntitiesOptions.Builder()
    .emotion(true)
    .sentiment(true)
    .limit(10)
    .build();

KeywordsOptions keywordsOptions = new KeywordsOptions.Builder()
    .emotion(true)
    .sentiment(true)
    .limit(10)
    .build();

Features features = new Features.Builder()
    .entities(entitiesOptions)
    .keywords(keywordsOptions)
    .concepts(conceptOptions)
    .categories(categoriesOptions)
    .semanticRoles(semanticRoleOptions)
    .build();

AnalyzeOptions parameters = new AnalyzeOptions.Builder()
    .text(inputText)
    .features(features)
    .build();

AnalysisResults response = service
    .analyze(parameters)
    .execute();
System.out.println(response);


问:
If isset ID inside array, get values from defined ID in same array?
If user access my page using an ID: mysite.com/page.php?id=3, I want the PHP to check if ID is defined in an array, if true, it returns in page multiple user information from same array according to their defined IDs.

My code:

```<code>$userinfo = [
        ['id' => 3, 'name' => 'username3', 'phone' => '3333'],
        ['id' => 2, 'name' => 'username2', 'phone' => '2222'],
        ['id' => 1, 'name' => 'username1', 'phone' => '1111']
    ];

if (isset($_GET['id']) && isset($userinfo[$_GET['id']])) {
     $name = $userinfo[$_GET['name']]; // If I access PHP with '?id=3' wanna 'username3'.
     $phone = $userinfo[$_GET['phone']]; // It stores id 3 user phone: '3333'
    }

echo $name; // It returns 'name' from array.
echo $phone; // It returns 'phone' from array.
</code>```

It's only a base, I know it don't works, any help with the code? thanks in advance.

答:
```<code>$userinfo = [
        ['id' => 3, 'name' => 'username3', 'phone' => '3333'],
        ['id' => 2, 'name' => 'username2', 'phone' => '2222'],
        ['id' => 1, 'name' => 'username1', 'phone' => '1111']
    ];
if (isset($_GET['id'])){
    foreach($userinfo as $user){
        if($user['id']==$_GET['id']){
            $name = $user['name'];
            $phone = $user['phone'];
        }
    }
}
echo $name;
echo $phone;
</code>```

Body:
If user access my page using an ID: mysite.com/page.php?id=3, I want the PHP to check if ID is defined in an array, if true, it returns in page multiple user information from same array according to their defined IDs.

My code:

$userinfo = [
        ['id' => 3, 'name' => 'username3', 'phone' => '3333'],
        ['id' => 2, 'name' => 'username2', 'phone' => '2222'],
        ['id' => 1, 'name' => 'username1', 'phone' => '1111']
    ];

if (isset($_GET['id']) && isset($userinfo[$_GET['id']])) {
     $name = $userinfo[$_GET['name']]; // If I access PHP with '?id=3' wanna 'username3'.
     $phone = $userinfo[$_GET['phone']]; // It stores id 3 user phone: '3333'
    }

echo $name; // It returns 'name' from array.
echo $phone; // It returns 'phone' from array.

It's only a base, I know it don't works, any help with the code? thanks in advance.


问:
Handle ClickEvent by PreviewMouseLeftButtonDown in Behavior<FrameworkElement>
I have a Behavior<FrameworkElement> where I register PreviewKeyDown and PreviewMouseLeftButtonDown. I have attached this Behavior on a MenuItem. Now when I click on the MenuItem, sometimes the ClickEvent is still invoked and sometimes not. It is like a timing problem. Do you have any suggestions how to solve this problem and stop invoke the event?

```<code>protected override void OnAttached()
{
    base.OnAttached();
    AssociatedObject.PreviewKeyDown += _OnPreviewKeyDown;
    AssociatedObject.PreviewMouseLeftButtonDown += _OnPreviewMouseLeftButtonDown;
}

private void _OnPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs mouseButtonEventArgs)
{
    if (!_HasAccess())
        mouseButtonEventArgs.Handled = true;
}

private void _OnPreviewKeyDown(object sender, KeyEventArgs keyEventArgs)
{
    if (!_HasAccess())
        keyEventArgs.Handled = true;
}
</code>```

答: I also had to subscribe to AssociatedObject.PreviewMouseLeftButtonUp and set handled = true. Now I got the desired behavior!

Body:
I have a Behavior<FrameworkElement> where I register PreviewKeyDown and PreviewMouseLeftButtonDown. I have attached this Behavior on a MenuItem. Now when I click on the MenuItem, sometimes the ClickEvent is still invoked and sometimes not. It is like a timing problem. Do you have any suggestions how to solve this problem and stop invoke the event?

protected override void OnAttached()
{
    base.OnAttached();
    AssociatedObject.PreviewKeyDown += _OnPreviewKeyDown;
    AssociatedObject.PreviewMouseLeftButtonDown += _OnPreviewMouseLeftButtonDown;
}

private void _OnPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs mouseButtonEventArgs)
{
    if (!_HasAccess())
        mouseButtonEventArgs.Handled = true;
}

private void _OnPreviewKeyDown(object sender, KeyEventArgs keyEventArgs)
{
    if (!_HasAccess())
        keyEventArgs.Handled = true;
}


问:
Regex for numbers between 0-9 and 15 digits as limit
RegEx for only Numbers between 0-9 and 15 digits as limit</p>

答:
Try this:

```<code>  ^[0-9]{0,15}$
</code>```

And for match this pattern with your input, use JavaScript match function.

Body:
Try this:

  ^[0-9]{0,15}$

And for match this pattern with your input, use JavaScript match function.


问:
Routing not working in reactjs application
I have created a reactjs app having three pages (components), App, Login and Register, where I need to navigate from page to page by entering the url in the browser but the navigation is not working for me. Entering any url just shows me the 'App' page.

following is the code that I have written in main.js file of the app and the url that I am using to navigate looks something like this http://localhost:8080/#/login or http://localhost:8080/#/reg

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route, NavLink, Redirect, Switch, hashHistory} from 'react-router-dom'
import App from './../jsx/App.jsx';
import Login from './../jsx/Login.jsx';
import Register from './../jsx/Register.jsx';

ReactDOM.render((
     <Router history={hashHistory}>
        <div>
            <Route path="/" component={App}/>
            <Route path="/login" component={Login}/>
            <Route path="/reg" component={Register}/>
        </div>
    </Router>

), document.getElementById('app'))
</code>```

答:
Remove / from your path in Route path in

```<code><Route path="/login" component={Login}/>
            <Route path="/reg" component={Register}/>
</code>```

try this it's working for me

entry class

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import Layout from './Component/Layout.jsx';
import { Router, Route, IndexRoute, hashHistory } from "react-router";

import Archives from './Component/Archives.jsx';
import Settings from './Component/Settings.jsx';

import Featured from './Component/Featured.jsx';

ReactDOM.render(
<Router history={hashHistory}>
<Route path="/" component={Layout}>
//<IndexRoute component={Featured}></IndexRoute>
<Route path="archives" name="archives" component={Archives}></Route>
<Route path="settings" component={Settings}></Route>
<Route path="featured" component={Featured}></Route>
</Route>
</Router>,
document.getElementById('app'));

Layout class
{
render{

return(
<div>
      {this.props.children}
      <ul>
       <li><Link to="archives">archives</Link></li>
         <li><Link to="settings">settings</Link></li>
         <li><Link to="featured">featured</Link></li>
         </ul>

</div>

);
}

}
</code>```

Body:
I have created a reactjs app having three pages (components), App, Login and Register, where I need to navigate from page to page by entering the url in the browser but the navigation is not working for me. Entering any url just shows me the 'App' page.

following is the code that I have written in main.js file of the app and the url that I am using to navigate looks something like this http://localhost:8080/#/login or http://localhost:8080/#/reg

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route, NavLink, Redirect, Switch, hashHistory} from 'react-router-dom'
import App from './../jsx/App.jsx';
import Login from './../jsx/Login.jsx';
import Register from './../jsx/Register.jsx';

ReactDOM.render((
     <Router history={hashHistory}>

            <Route path="/" component={App}/>
            <Route path="/login" component={Login}/>
            <Route path="/reg" component={Register}/>

    </Router>

), document.getElementById('app'))

Body:
Remove / from your path in Route path in

<Route path="/login" component={Login}/>
            <Route path="/reg" component={Register}/>

try this it's working for me

entry class

import React from 'react';
import ReactDOM from 'react-dom';
import Layout from './Component/Layout.jsx';
import { Router, Route, IndexRoute, hashHistory } from "react-router";

import Archives from './Component/Archives.jsx';
import Settings from './Component/Settings.jsx';

import Featured from './Component/Featured.jsx';

ReactDOM.render(
<Router history={hashHistory}>
<Route path="/" component={Layout}>
//<IndexRoute component={Featured}></IndexRoute>
<Route path="archives" name="archives" component={Archives}></Route>
<Route path="settings" component={Settings}></Route>
<Route path="featured" component={Featured}></Route>
</Route>
</Router>,
document.getElementById('app'));

Layout class
{
render{

return(
<div>
      {this.props.children}
      <ul>
       <li><Link to="archives">archives</Link></li>
         <li><Link to="settings">settings</Link></li>
         <li><Link to="featured">featured</Link></li>
         </ul>

</div>

);
}

}