问:
How to process django url tags in context variables
I'm creating a django-based website where page content is stored in a model textfield with a detail view of the model displaying it. How can I put {% url %} tags in the content to link to other pages without hard coding links?

Putting the tag into the textfield will just print the tag as plain text. (or if inside an href create a broken link)

Other options are

parsing the content manually inside the view and replacing the tags with the correct url

using some django supplied string parser to create the links before sending to the template

maybe there is a way to do it in the template with a filter or tag around the variable.

I could probably do the manual way but I am hoping there is a django way that I am missing.

class Page(models.Model):
    content = models.TextField(blank=True)

class PageView(DetailView):
    model=Page
    context_object_name='page'
```

<pre class="lang-html prettyprint-override"><code>{% extends "base.html" %}

{% block content %}
    {{ page.content|safe }}
{% endblock %}
</code>```

Edit for clarity:

Content in admin

What it renders

What it should render

Edit 2:
I was able to find a solution to the second option thanks to this answer on another question. Using that template_from_string function I rendered the page content as a template then replaced the content in the context with the rendered result.

class PageView(DetailView):
  model=Page
  context_object_name='page'
  def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    # Add to context here
    context['page'].content = template_from_string(context['page'].content).render(context)
    return context
```

答:
your url's will have a name as shown below-
path('page//',PageView.as_view, name="page-detail")

and in your Page Detail

hope this is what your asking for

Body:
I'm creating a django-based website where page content is stored in a model textfield with a detail view of the model displaying it. How can I put {% url %} tags in the content to link to other pages without hard coding links?

Putting the tag into the textfield will just print the tag as plain text. (or if inside an href create a broken link)

Other options are

parsing the content manually inside the view and replacing the tags with the correct url

using some django supplied string parser to create the links before sending to the template

maybe there is a way to do it in the template with a filter or tag around the variable.

I could probably do the manual way but I am hoping there is a django way that I am missing.

class Page(models.Model):
    content = models.TextField(blank=True)

class PageView(DetailView):
    model=Page
    context_object_name='page'

{% extends "base.html" %}

{% block content %}
    {{ page.content|safe }}
{% endblock %}

Edit for clarity:

Content in admin

What it renders

What it should render

Edit 2:
I was able to find a solution to the second option thanks to this answer on another question. Using that template_from_string function I rendered the page content as a template then replaced the content in the context with the rendered result.

class PageView(DetailView):
  model=Page
  context_object_name='page'
  def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    # Add to context here
    context['page'].content = template_from_string(context['page'].content).render(context)
    return context


来源: stackexchange

问:
Pyspark tool in PyCharm tool
I have installed pyspark package in pycharma and now I am run pyspark code in pycharm. But I am not able to import all the the vaialbale classes/functions in the pyspark .sql module.

getting error for Sparksession module and hence not able to create dataframes.
Can you please suggest me what is wrong here.

Below is snippet for importing modules.

from pyspark.sql.functions import explode, col
from pyspark.sql.Sparksessions

```<code>import pyspark.sql.SparkSession
</code>```

ModuleNotFoundError: No module named 'pyspark.sql.SparkSession'

答: try from pyspark.sql import SparkSession

ContentLicense: CC BY-SA 4.0

Title: Pyspark tool in PyCharm tool

Body:
I have installed pyspark package in pycharma and now I am run pyspark code in pycharm. But I am not able to import all the the vaialbale classes/functions in the pyspark .sql module.

getting error for Sparksession module and hence not able to create dataframes.
Can you please suggest me what is wrong here.

Below is snippet for importing modules.

from pyspark.sql.functions import explode, col
from pyspark.sql.Sparksessions

import pyspark.sql.SparkSession

ModuleNotFoundError: No module named 'pyspark.sql.SparkSession'


问:
How to Test and Run a Client Server Program in C++ using Eclipse
I am trying to get started with UDP and would like to test and debug some client server programs.

I am using an Eclipse IDE with cygwin64 as a compiler.

I have found some example client server programs from here: https://www.geeksforgeeks.org/udp-server-client-implementation-c/

I would like to be able to run the example to get me started on learning about UDP client servers.

The example code is as follows:

Server

```<code>    // Server side implementation of UDP client-server model
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#define PORT     8080
#define MAXLINE 1024

// Driver code
int main() {
    int sockfd;
    char buffer[MAXLINE];
    char *hello = "Hello from server";
    struct sockaddr_in servaddr, cliaddr;

    // Creating socket file descriptor
    if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }

    memset(&servaddr, 0, sizeof(servaddr));
    memset(&cliaddr, 0, sizeof(cliaddr));

    // Filling server information
    servaddr.sin_family    = AF_INET; // IPv4
    servaddr.sin_addr.s_addr = INADDR_ANY;
    servaddr.sin_port = htons(PORT);

    // Bind the socket with the server address
    if ( bind(sockfd, (const struct sockaddr *)&servaddr,
            sizeof(servaddr)) < 0 )
    {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    int len, n;
    n = recvfrom(sockfd, (char *)buffer, MAXLINE,
                MSG_WAITALL, ( struct sockaddr *) &cliaddr,
                &len);
    buffer[n] = '\0';
    printf("Client : %s\n", buffer);
    sendto(sockfd, (const char *)hello, strlen(hello),
        0, (const struct sockaddr *) &cliaddr,
            len);
    printf("Hello message sent.\n");

    return 0;
}
</code>```

Client

```<code>// Client side implementation of UDP client-server model
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#define PORT     8080
#define MAXLINE 1024

// Driver code
int main() {
    int sockfd;
    char buffer[MAXLINE];
    char *hello = "Hello from client";
    struct sockaddr_in     servaddr;

    // Creating socket file descriptor
    if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }

    memset(&servaddr, 0, sizeof(servaddr));

    // Filling server information
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(PORT);
    servaddr.sin_addr.s_addr = INADDR_ANY;

    int n, len;

    sendto(sockfd, (const char *)hello, strlen(hello),
        MSG_CONFIRM, (const struct sockaddr *) &servaddr,
            sizeof(servaddr));
    printf("Hello message sent.\n");

    n = recvfrom(sockfd, (char *)buffer, MAXLINE,
                MSG_WAITALL, (struct sockaddr *) &servaddr,
                &len);
    buffer[n] = '\0';
    printf("Server : %s\n", buffer);

    close(sockfd);
    return 0;
}
</code>```

I have tried opening up two different eclipse workbenches and running both the codes, but it is not running as expected and it is saying that the messages have been sent but I have not been able to receive them on the client or server.

I definitely would like to stick with c/c++ and try to get this working in eclipse if it's possible.

If anyone has any advice on how I can be able to see some results or anything that could get me started with this, it would be much appreciated. Thank you!

答:
Problem

You have not set the address of the server correctly in the client code.

```<code>servaddr.sin_addr.s_addr = INADDR_ANY;
</code>```

is meaningless when sending (Why would you want to send to any available address? You want to send to the server.) and is rejected by sendto. You would have seen this if you'd checked the return value. Always check the return value, even for UDP communications. Sure there are a million reasons why a packet won't arrive with UDP that you can't detect at the time of sendto, but it's good to know that the network stack actually accepted the message even if a grue subsequently devours the packet in one of the dark corners of the Internet. A sending error you can do something about, like perror and then fix the code accordingly. A grue, not so much. You'll have to make a protocol robust enough to retransmit or otherwise survive the loss of the packet.

Solution

Get the server's address structure with getaddrinfo.

Replace

```<code>// Filling server information
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
servaddr.sin_addr.s_addr = INADDR_ANY;
</code>```

with something more like

```<code>struct addrinfo hints;
struct addrinfo *hostlist;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = 0;
hints.ai_protocol = IPPROTO_UDP;

if (getaddrinfo("Server Name or Address Goes Here",
                PORT, // this needs to be a char *, not an integer
                &hints,
                &hostlist))
{
    // handle error
    exit(EXIT_FAILURE);
}
</code>```

PORT in this case needs to be a char *, so instead of

```<code>#define PORT     8080
</code>```

use

```<code>constexpr char const * PORT = "8080";
</code>```

You can leave out the constexpr if your compiler is old and doesn't support it.

Then when you go to send, iterate through the hostlist until you find a host that responds. Since you've probably narrowed the servers down to exactly one candidate, this is probably overkill, but you might as well get into practice doing things right. The alternative sucks when systems start getting complicated.

```<code>struct addrinfo *curhost;
for (curhost = hostlist; curhost != NULL; curhost = curhost->ai_next)
{
    int rval = sendto(sockfd,
                      (const char *) hello,
                      strlen(hello),
                      0,
                      curhost->ai_addr,
                      curhost->ai_addrlen);
    if (rval> 0) // always check return codes. Programmers are lazy.
                 // They wouldn't have gone to the effort of putting
                 // it there if it wasn't important.
    {
        if server responds
            do protocol stuff to complete transaction
            break;
    }
}
freeaddrinfo(hostlist); // thou shalt not leak resources.
if (curhost == nullptr)
{
    notify user that no server was willing to talk
}
</code>```

Documentation for getaddrinfo.

Body:
I am trying to get started with UDP and would like to test and debug some client server programs.

I am using an Eclipse IDE with cygwin64 as a compiler.

I have found some example client server programs from here: https://www.geeksforgeeks.org/udp-server-client-implementation-c/

I would like to be able to run the example to get me started on learning about UDP client servers.

The example code is as follows:

Server

    // Server side implementation of UDP client-server model
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#define PORT     8080
#define MAXLINE 1024

// Driver code
int main() {
    int sockfd;
    char buffer[MAXLINE];
    char *hello = "Hello from server";
    struct sockaddr_in servaddr, cliaddr;

    // Creating socket file descriptor
    if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }

    memset(&servaddr, 0, sizeof(servaddr));
    memset(&cliaddr, 0, sizeof(cliaddr));

    // Filling server information
    servaddr.sin_family    = AF_INET; // IPv4
    servaddr.sin_addr.s_addr = INADDR_ANY;
    servaddr.sin_port = htons(PORT);

    // Bind the socket with the server address
    if ( bind(sockfd, (const struct sockaddr *)&servaddr,
            sizeof(servaddr)) < 0 )
    {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    int len, n;
    n = recvfrom(sockfd, (char *)buffer, MAXLINE,
                MSG_WAITALL, ( struct sockaddr *) &cliaddr,
                &len);
    buffer[n] = '\0';
    printf("Client : %s\n", buffer);
    sendto(sockfd, (const char *)hello, strlen(hello),
        0, (const struct sockaddr *) &cliaddr,
            len);
    printf("Hello message sent.\n");

    return 0;
}

Client

// Client side implementation of UDP client-server model
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#define PORT     8080
#define MAXLINE 1024

// Driver code
int main() {
    int sockfd;
    char buffer[MAXLINE];
    char *hello = "Hello from client";
    struct sockaddr_in     servaddr;

    // Creating socket file descriptor
    if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }

    memset(&servaddr, 0, sizeof(servaddr));

    // Filling server information
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(PORT);
    servaddr.sin_addr.s_addr = INADDR_ANY;

    int n, len;

    sendto(sockfd, (const char *)hello, strlen(hello),
        MSG_CONFIRM, (const struct sockaddr *) &servaddr,
            sizeof(servaddr));
    printf("Hello message sent.\n");

    n = recvfrom(sockfd, (char *)buffer, MAXLINE,
                MSG_WAITALL, (struct sockaddr *) &servaddr,
                &len);
    buffer[n] = '\0';
    printf("Server : %s\n", buffer);

    close(sockfd);
    return 0;
}

I have tried opening up two different eclipse workbenches and running both the codes, but it is not running as expected and it is saying that the messages have been sent but I have not been able to receive them on the client or server.

I definitely would like to stick with c/c++ and try to get this working in eclipse if it's possible.

If anyone has any advice on how I can be able to see some results or anything that could get me started with this, it would be much appreciated. Thank you!

Body:
Problem

You have not set the address of the server correctly in the client code.

servaddr.sin_addr.s_addr = INADDR_ANY;

is meaningless when sending (Why would you want to send to any available address? You want to send to the server.) and is rejected by sendto. You would have seen this if you'd checked the return value. Always check the return value, even for UDP communications. Sure there are a million reasons why a packet won't arrive with UDP that you can't detect at the time of sendto, but it's good to know that the network stack actually accepted the message even if a grue subsequently devours the packet in one of the dark corners of the Internet. A sending error you can do something about, like perror and then fix the code accordingly. A grue, not so much. You'll have to make a protocol robust enough to retransmit or otherwise survive the loss of the packet.

Solution

Get the server's address structure with getaddrinfo.

Replace

// Filling server information
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
servaddr.sin_addr.s_addr = INADDR_ANY;

with something more like

struct addrinfo hints;
struct addrinfo *hostlist;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = 0;
hints.ai_protocol = IPPROTO_UDP;

if (getaddrinfo("Server Name or Address Goes Here",
                PORT, // this needs to be a char *, not an integer
                &hints,
                &hostlist))
{
    // handle error
    exit(EXIT_FAILURE);
}

PORT in this case needs to be a char *, so instead of

#define PORT     8080

use

constexpr char const * PORT = "8080";

You can leave out the constexpr if your compiler is old and doesn't support it.

Then when you go to send, iterate through the hostlist until you find a host that responds. Since you've probably narrowed the servers down to exactly one candidate, this is probably overkill, but you might as well get into practice doing things right. The alternative sucks when systems start getting complicated.

struct addrinfo *curhost;
for (curhost = hostlist; curhost != NULL; curhost = curhost->ai_next)
{
    int rval = sendto(sockfd,
                      (const char *) hello,
                      strlen(hello),
                      0,
                      curhost->ai_addr,
                      curhost->ai_addrlen);
    if (rval> 0) // always check return codes. Programmers are lazy.
                 // They wouldn't have gone to the effort of putting
                 // it there if it wasn't important.
    {
        if server responds
            do protocol stuff to complete transaction
            break;
    }
}
freeaddrinfo(hostlist); // thou shalt not leak resources.
if (curhost == nullptr)
{
    notify user that no server was willing to talk
}

Documentation for getaddrinfo.


问:
Installation issue in Nativescript
Hi I am using Mintos(Linux) platform. For create Andriod app Angular based  using Nativescript so i installed Nativescript successfully installed node.js version 8.10.0. When i tried to install nativescript cmd npm install -g nativescript It was showing error like

```<code>mint2@mint2-ASAG3730-ASAG1730:~$ npm install -g nativescript
    npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules/nativescript
    npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules/nativescript/node_modules/fsevents/node_modules
    npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules
    /usr/local/lib
    +-- nativescript@5.1.0
    `-- rc@1.2.7
      `-- minimist@1.2.0

    npm WARN tsutils@2.29.0 requires a peer of typescript@>=2.1.0 || >=2.1.0-dev || >=2.2.0-dev || >=2.3.0-dev || >=2.4.0-dev || >=2.5.0-dev || >=2.6.0-dev || >=2.7.0-dev || >=2.8.0-dev || >=2.9.0-dev || >= 3.0.0-dev || >= 3.1.0-dev but none was installed.
    npm WARN tslint@5.4.3 requires a peer of typescript@>=2.1.0 || >=2.1.0-dev || >=2.2.0-dev || >=2.3.0-dev || >=2.4.0-dev but none was installed.
    npm ERR! Linux 4.15.0-20-generic
    npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "install" "-g" "nativescript"
    npm ERR! node v8.10.0
    npm ERR! npm  v3.5.2
    npm ERR! path /usr/local/lib/node_modules/nativescript
    npm ERR! code EACCES
    npm ERR! errno -13
    npm ERR! syscall access

    npm ERR! Error: EACCES: permission denied, access '/usr/local/lib/node_modules/nativescript'
    npm ERR!  { Error: EACCES: permission denied, access '/usr/local/lib/node_modules/nativescript'
    npm ERR!   errno: -13,
    npm ERR!   code: 'EACCES',
    npm ERR!   syscall: 'access',
    npm ERR!   path: '/usr/local/lib/node_modules/nativescript' }
    npm ERR!
    npm ERR! Please try running this command again as root/Administrator.

    npm ERR! Please include the following file with any support request:
    npm ERR!     /home/mint2/npm-debug.log
</code>```

答:
To avoid all these kinds of problems on Linux, the best solution that I've found is to use Node Version Manager.

You can install it using:

wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash

Logout and log back in again for the path updates to take effect.

After this, see what Node versions are available:

nvm list-remote

Pick a version and install it, for example:

nvm install v12.3.1

nvm will automatically use this version (or whatever other version you selected).

You can install other versions as required and switch between versions using (for example):

nvm use v12.3.0

The advantages of doing things this way are at least the following:

No more access control issues

You can swap between Node versions as you please

Here's a repo link for further information: https://github.com/nvm-sh/nvm

Title: Installation issue in Nativescript

Body:
Hi I am using Mintos(Linux) platform. For create Andriod app Angular based  using Nativescript so i installed Nativescript successfully installed node.js version 8.10.0. When i tried to install nativescript cmd npm install -g nativescript It was showing error like

mint2@mint2-ASAG3730-ASAG1730:~$ npm install -g nativescript
    npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules/nativescript
    npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules/nativescript/node_modules/fsevents/node_modules
    npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules
    /usr/local/lib
    +-- nativescript@5.1.0
    `-- rc@1.2.7
      `-- minimist@1.2.0

    npm WARN tsutils@2.29.0 requires a peer of typescript@>=2.1.0 || >=2.1.0-dev || >=2.2.0-dev || >=2.3.0-dev || >=2.4.0-dev || >=2.5.0-dev || >=2.6.0-dev || >=2.7.0-dev || >=2.8.0-dev || >=2.9.0-dev || >= 3.0.0-dev || >= 3.1.0-dev but none was installed.
    npm WARN tslint@5.4.3 requires a peer of typescript@>=2.1.0 || >=2.1.0-dev || >=2.2.0-dev || >=2.3.0-dev || >=2.4.0-dev but none was installed.
    npm ERR! Linux 4.15.0-20-generic
    npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "install" "-g" "nativescript"
    npm ERR! node v8.10.0
    npm ERR! npm  v3.5.2
    npm ERR! path /usr/local/lib/node_modules/nativescript
    npm ERR! code EACCES
    npm ERR! errno -13
    npm ERR! syscall access

    npm ERR! Error: EACCES: permission denied, access '/usr/local/lib/node_modules/nativescript'
    npm ERR!  { Error: EACCES: permission denied, access '/usr/local/lib/node_modules/nativescript'
    npm ERR!   errno: -13,
    npm ERR!   code: 'EACCES',
    npm ERR!   syscall: 'access',
    npm ERR!   path: '/usr/local/lib/node_modules/nativescript' }
    npm ERR!
    npm ERR! Please try running this command again as root/Administrator.

    npm ERR! Please include the following file with any support request:
    npm ERR!     /home/mint2/npm-debug.log


问:
TIdHTTPProxyServer raising "Unknown Protocol" RSHTTPUnknownProtocol exception
I'm recoding an old Delphi XE program using Delphi 10.3 Rio.  It uses the TIdHTTPProxyServer Indy component listening on 127.0.0.1:80.

```<code>  with IdHTTPProxyServer.Bindings.Add do begin

    IP := '127.0.0.1';
    Port := 80;

  end;

  IdHTTPProxyServer.Active := True;
</code>```

For testing, I added 127.0.0.1 localtest123.com and 127.0.0.1 www.localtest123.com to the hosts file and disabled the DNS cache service.  Then in multiple browers I requested http://localtest123.com/ and http://www.localtest123.com/.  With OutputDebugString() I can see the connections accepted but then raises an "Unknown Protocol" error.

I debugged the exception in the TIdHTTPProxyServer.CommandPassThrough procedure in IdHTTPProxyServer.pas.  It seems LURI.Protocol is an empty string which is why the RSHTTPUnknownProtocol is raised.

```<code>  LContext := TIdHTTPProxyServerContext(ASender.Context);
  LContext.FCommand := ASender.CommandHandler.Command; //<-'GET'
  LContext.FTarget := ASender.Params.Strings[0]; //<-'/'

  LContext.FOutboundClient := TIdTCPClient.Create(nil);
  try
    LURI := TIdURI.Create(LContext.Target); //<-'/'
    try
      TIdTCPClient(LContext.FOutboundClient).Host := LURI.Host; //<-''

      if LURI.Port <> '' then begin //<-''
        TIdTCPClient(LContext.FOutboundClient).Port := IndyStrToInt(LURI.Port, 80);
      end
      else if TextIsSame(LURI.Protocol, 'http') then begin //<-''    {do not localize}
        TIdTCPClient(LContext.FOutboundClient).Port := IdPORT_HTTP;
      end
      else if TextIsSame(LURI.Protocol, 'https') then begin //<-'' {do not localize}
        TIdTCPClient(LContext.FOutboundClient).Port := IdPORT_https;
      end else begin
        raise EIdException.Create(RSHTTPUnknownProtocol);
      end;
</code>```

I'm probably missing something but TIdHTTPProxyServer just works without much code so I have to ask for help on this exception.  Thanks in advance!

答:
You can't just redirect the domains in your HOSTS file and expect things to magically work. That is not how proxying works.

You must explicitly configure web browsers to make HTTP requests through an HTTP proxy so that they format the proper requests that a proxy would understand. Sending an HTTP request directly to a target web server is handled differently than sending the same HTTP request through a proxy.

You are getting the exception because the browser requests are not targeting your proxy properly.

For example, when a browser sends an HTTP GET request directly to a target web server, it connects directly to that server and then sends a request that looks something like this:

```<code>GET /path HTTP/1.1
Host: server.com
</code>```

But, when it sends the same request through an HTTP proxy, it connects to the proxy and sends a request that looks more like this instead:

```<code>GET http://server.com/path HTTP/1.1
</code>```

That extra path information in the GET line is missing in your browser requests, because you do not have your browsers configured for proxying, thus the exception when TIdHTTPProxyServer is trying to determine the info it needs to make a connection to the target web server and forward the current request to it.

This is fundamentally to how HTTP works, and how TIdHTTPProxyServer is designed to work.

Things are a bit more complicated when HTTPS is involved, but I'm leaving that detail out for now, as it is not relevant to your question about the exception.

UPDATE: in comments, you say:

In the XE version it never raised an exception when checking for the protocol which would still work today because I manually set the host and port in DoHTTPBeforeCommand.

In that old version, there was no exception raised, because TIdHTTPProxyServer did not check the protocol yet to differentiate between HTTP and HTTPS. You were able to manually fill in missing info when a request was received that was not specifically targeting your proxy. That is why things worked for you before.

In a later version, TIdHTTPProxyServer was updated to differentiate between HTTP and HTTPS when no port is explicitly specified in the request, so a default port is set based on protocol requested. That check happens before DoHTTPBeforeCommand() is called.

To get the old behavior back, you would have to alter TIdHTTPProxyServer's source code to delay the raising of the exception until after DoHTTPBeforeCommand() returns, so you have a chance to fill in missing values again.

If you file a feature request for that, I might consider adding it to Indy's official code.

Body:
I'm recoding an old Delphi XE program using Delphi 10.3 Rio.  It uses the TIdHTTPProxyServer Indy component listening on 127.0.0.1:80.

  with IdHTTPProxyServer.Bindings.Add do begin

    IP := '127.0.0.1';
    Port := 80;

  end;

  IdHTTPProxyServer.Active := True;

For testing, I added 127.0.0.1 localtest123.com and 127.0.0.1 www.localtest123.com to the hosts file and disabled the DNS cache service.  Then in multiple browers I requested http://localtest123.com/ and http://www.localtest123.com/.  With OutputDebugString() I can see the connections accepted but then raises an "Unknown Protocol" error.

I debugged the exception in the TIdHTTPProxyServer.CommandPassThrough procedure in IdHTTPProxyServer.pas.  It seems LURI.Protocol is an empty string which is why the RSHTTPUnknownProtocol is raised.

  LContext := TIdHTTPProxyServerContext(ASender.Context);
  LContext.FCommand := ASender.CommandHandler.Command; //<-'GET'
  LContext.FTarget := ASender.Params.Strings[0]; //<-'/'

  LContext.FOutboundClient := TIdTCPClient.Create(nil);
  try
    LURI := TIdURI.Create(LContext.Target); //<-'/'
    try
      TIdTCPClient(LContext.FOutboundClient).Host := LURI.Host; //<-''

      if LURI.Port <> '' then begin //<-''
        TIdTCPClient(LContext.FOutboundClient).Port := IndyStrToInt(LURI.Port, 80);
      end
      else if TextIsSame(LURI.Protocol, 'http') then begin //<-''    {do not localize}
        TIdTCPClient(LContext.FOutboundClient).Port := IdPORT_HTTP;
      end
      else if TextIsSame(LURI.Protocol, 'https') then begin //<-'' {do not localize}
        TIdTCPClient(LContext.FOutboundClient).Port := IdPORT_https;
      end else begin
        raise EIdException.Create(RSHTTPUnknownProtocol);
      end;

I'm probably missing something but TIdHTTPProxyServer just works without much code so I have to ask for help on this exception.  Thanks in advance!

Body:
You can't just redirect the domains in your HOSTS file and expect things to magically work. That is not how proxying works.

You must explicitly configure web browsers to make HTTP requests through an HTTP proxy so that they format the proper requests that a proxy would understand. Sending an HTTP request directly to a target web server is handled differently than sending the same HTTP request through a proxy.

You are getting the exception because the browser requests are not targeting your proxy properly.

For example, when a browser sends an HTTP GET request directly to a target web server, it connects directly to that server and then sends a request that looks something like this:

GET /path HTTP/1.1
Host: server.com

But, when it sends the same request through an HTTP proxy, it connects to the proxy and sends a request that looks more like this instead:

GET http://server.com/path HTTP/1.1

That extra path information in the GET line is missing in your browser requests, because you do not have your browsers configured for proxying, thus the exception when TIdHTTPProxyServer is trying to determine the info it needs to make a connection to the target web server and forward the current request to it.

This is fundamentally to how HTTP works, and how TIdHTTPProxyServer is designed to work.

Things are a bit more complicated when HTTPS is involved, but I'm leaving that detail out for now, as it is not relevant to your question about the exception.

UPDATE: in comments, you say:

In the XE version it never raised an exception when checking for the protocol which would still work today because I manually set the host and port in DoHTTPBeforeCommand.

In that old version, there was no exception raised, because TIdHTTPProxyServer did not check the protocol yet to differentiate between HTTP and HTTPS. You were able to manually fill in missing info when a request was received that was not specifically targeting your proxy. That is why things worked for you before.

In a later version, TIdHTTPProxyServer was updated to differentiate between HTTP and HTTPS when no port is explicitly specified in the request, so a default port is set based on protocol requested. That check happens before DoHTTPBeforeCommand() is called.

To get the old behavior back, you would have to alter TIdHTTPProxyServer's source code to delay the raising of the exception until after DoHTTPBeforeCommand() returns, so you have a chance to fill in missing values again.

If you file a feature request for that, I might consider adding it to Indy's official code.


问:
Check if Calendar (List) is free in SharePoint CSOM
I am writing javascript (CSOM) code in SharePoint to add items to SharePoint Calendar app (list).

I want to add these records only if calendar is free during the specified time.

i.e in below ex, I want to check if calendar is free from 08:00 to 08:15 before adding

```<code>    var itemCreateInfo = new SP.ListItemCreationInformation();
    var listItem = list.addItem(itemCreateInfo);
    var startdate = new Date('2017-10-21 08:00 GMT+0000').toISOString();
    var enddate = new Date('2017-10-21 08:15 GMT+0000').toISOString();
    listItem.set_item("Title", "My Event");
    listItem.set_item("EventDate", startdate);
    listItem.set_item("EndDate", enddate);
    listItem.set_item("Location", "MyCalander");
    listItem.update();
</code>```

答:
Here is a query you can use: (The caml value looks terrible so I'll post the xml below)

```<code>function queryCalendar(startDate, endDate) {
    var context = SP.ClientContext.get_current();
    var list = context.get_web().get_lists().getByTitle("Calendar");
    var caml = "\n<View>\n    <Query>\n        <Where>\n            <And>\n                <Lt>\n                    <FieldRef Name='EventDate' />\n                    <Value Type='DateTime' IncludeTimeValue='True' StorageTZ='TRUE'>" + endDate.toISOString() + "</Value>\n                </Lt>\n                <Gt>\n                    <FieldRef Name='EndDate' />\n                    <Value Type='DateTime' IncludeTimeValue='True' StorageTZ='TRUE'>" + startDate.toISOString() + "</Value>\n                </Gt>\n            </And>\n        </Where>\n    </Query>\n    <ViewFields>\n        <FieldRef Name='EventDate' />\n        <FieldRef Name='EndDate' />\n        <FieldRef Name='Title' />\n    </ViewFields>\n</View>\n\n";
    var query = new SP.CamlQuery();
    query.set_viewXml(caml);
    var listItems = list.getItems(query);
    context.load(listItems);
    context.executeQueryAsync(function (sender, args) {
        if (listItems.get_count() > 0) {
            console.warn("That time is already booked");
        }
        else {
            console.log("that time is good");
        }
    }, function (sender, args) {
        console.error(args.get_message());
    });
}
</code>```

Here is how I am calling it:

```<code>SP.SOD.executeOrDelayUntilScriptLoaded(function () {
    queryCalendar(new Date(2019, 4, 27, 8), new Date(2019, 4, 27, 9));
}, "SP.js");
</code>```

I use the following XML for the CAML:

```<code><View>
    <Query>
        <Where>
            <And>
                <Lt>
                    <FieldRef Name='EventDate' />
                    <Value Type='DateTime' IncludeTimeValue="True" StorageTZ='TRUE'>enddate</Value>
                </Lt>
                <Gt>
                    <FieldRef Name='EndDate' />
                    <Value Type='DateTime' IncludeTimeValue="True" StorageTZ='TRUE'>starttime</Value>
                </Gt>
            </And>
        </Where>
    </Query>
    <ViewFields>
        <FieldRef Name='EventDate' />
        <FieldRef Name='EndDate' />
        <FieldRef Name='Title' />
    </ViewFields>
</View>
</code>```

Make sure to replace "enddate" and "startdate" with a proper date value and use date.toISOString() method (which might not work in IE).

ContentLicense: CC BY-SA 3.0

Body:
I am writing javascript (CSOM) code in SharePoint to add items to SharePoint Calendar app (list).

I want to add these records only if calendar is free during the specified time.

i.e in below ex, I want to check if calendar is free from 08:00 to 08:15 before adding

    var itemCreateInfo = new SP.ListItemCreationInformation();
    var listItem = list.addItem(itemCreateInfo);
    var startdate = new Date('2017-10-21 08:00 GMT+0000').toISOString();
    var enddate = new Date('2017-10-21 08:15 GMT+0000').toISOString();
    listItem.set_item("Title", "My Event");
    listItem.set_item("EventDate", startdate);
    listItem.set_item("EndDate", enddate);
    listItem.set_item("Location", "MyCalander");
    listItem.update();

Body:
Here is a query you can use: (The caml value looks terrible so I'll post the xml below)

function queryCalendar(startDate, endDate) {
    var context = SP.ClientContext.get_current();
    var list = context.get_web().get_lists().getByTitle("Calendar");
    var caml = "\n<View>\n    <Query>\n        <Where>\n            <And>\n                <Lt>\n                    <FieldRef Name='EventDate' />\n                    <Value Type='DateTime' IncludeTimeValue='True' StorageTZ='TRUE'>" + endDate.toISOString() + "</Value>\n                </Lt>\n                <Gt>\n                    <FieldRef Name='EndDate' />\n                    <Value Type='DateTime' IncludeTimeValue='True' StorageTZ='TRUE'>" + startDate.toISOString() + "</Value>\n                </Gt>\n            </And>\n        </Where>\n    </Query>\n    <ViewFields>\n        <FieldRef Name='EventDate' />\n        <FieldRef Name='EndDate' />\n        <FieldRef Name='Title' />\n    </ViewFields>\n</View>\n\n";
    var query = new SP.CamlQuery();
    query.set_viewXml(caml);
    var listItems = list.getItems(query);
    context.load(listItems);
    context.executeQueryAsync(function (sender, args) {
        if (listItems.get_count() > 0) {
            console.warn("That time is already booked");
        }
        else {
            console.log("that time is good");
        }
    }, function (sender, args) {
        console.error(args.get_message());
    });
}

Here is how I am calling it:

SP.SOD.executeOrDelayUntilScriptLoaded(function () {
    queryCalendar(new Date(2019, 4, 27, 8), new Date(2019, 4, 27, 9));
}, "SP.js");

I use the following XML for the CAML:

<View>
    <Query>
        <Where>
            <And>
                <Lt>
                    <FieldRef Name='EventDate' />
                    <Value Type='DateTime' IncludeTimeValue="True" StorageTZ='TRUE'>enddate</Value>
                </Lt>
                <Gt>
                    <FieldRef Name='EndDate' />
                    <Value Type='DateTime' IncludeTimeValue="True" StorageTZ='TRUE'>starttime</Value>
                </Gt>
            </And>
        </Where>
    </Query>
    <ViewFields>
        <FieldRef Name='EventDate' />
        <FieldRef Name='EndDate' />
        <FieldRef Name='Title' />
    </ViewFields>
</View>

Make sure to replace "enddate" and "startdate" with a proper date value and use date.toISOString() method (which might not work in IE).


问:
Transfer calculated value from stat_smooth to other geom like linerange
I have a question about ggplot2.

I want to connect data point with ols result via vertical line, like the code listed below.

Can I transfer ..y.., the value calculated by stat_smooth, to geom_linerange directly?

I tried stat_smooth(..., geom = "linerange", mapping(aes(ymin=pmin(myy, ..y..), ymax=pmax(myy,..y..)) but it is not the result I want.

```<code>library(ggplot2)
df <- data.frame(myx = 1:10,
                 myy = c(1:10) * 5 + 2 * rnorm(10, 0, 1))
lm.fit <- lm("myy~myx", data = df)
pred <- predict(lm.fit)
ggplot(df, aes(myx, myy)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) +
  geom_linerange(mapping = aes(ymin = pmin(myy, pred),
                               ymax = pmax(myy, pred)))
</code>```

答:
stat_smooth evaluates the values at n evenly spaced points, with n = 80 by default. These points may not coincide with the original x values in your data frame.

Since you are calculating predicted values anyway, it would probably be more straightforward to add that back to your data frame and plot all geom layers based on that as your data source, for example:

```<code>df$pred <- pred

ggplot(df, aes(myx, myy)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) +
  geom_linerange(aes(ymin = myy, ymax = pred))
</code>```

Body:
I have a question about ggplot2.

I want to connect data point with ols result via vertical line, like the code listed below.

Can I transfer ..y.., the value calculated by stat_smooth, to geom_linerange directly?

I tried stat_smooth(..., geom = "linerange", mapping(aes(ymin=pmin(myy, ..y..), ymax=pmax(myy,..y..)) but it is not the result I want.

library(ggplot2)
df <- data.frame(myx = 1:10,
                 myy = c(1:10) * 5 + 2 * rnorm(10, 0, 1))
lm.fit <- lm("myy~myx", data = df)
pred <- predict(lm.fit)
ggplot(df, aes(myx, myy)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) +
  geom_linerange(mapping = aes(ymin = pmin(myy, pred),
                               ymax = pmax(myy, pred)))

Body:
stat_smooth evaluates the values at n evenly spaced points, with n = 80 by default. These points may not coincide with the original x values in your data frame.

Since you are calculating predicted values anyway, it would probably be more straightforward to add that back to your data frame and plot all geom layers based on that as your data source, for example:

df$pred <- pred

ggplot(df, aes(myx, myy)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) +
  geom_linerange(aes(ymin = myy, ymax = pred))


问:
Assist me in finding the error: invalid method declaration; return type required
This is my last homework for my java class and I have been trying to run this through a compiler but I don't understand whats wrong with the code.

I tried using void after reading about how that would fix the return type issue but that just made it worse, maybe I was putting void in the wrong place.

```<code>public class Exercise09_01 {
    private double width = 1;
    private double height = 1;

    public Rectangle() {
    }

    public Rectangle(double newWidth, double newHeight) {
        width = newWidth;
        height = newHeight;
    }

    public double getArea() {
        return width * height;
    }

    public double getPerimeter() {
        return 2 * (width + height);
    }

    public static void main(String[] args) {
        Rectangle rectangle1 = new Rectangle(4, 40);
        System.out.println("The area of a 4.0 x 40.0 Rectangle is " +
        rectangle1.getArea());
        System.out.println("The perimeter of a 4.0 x 40.0 Rectangle is " +
        rectangle1.getPerimeter());
        Rectangle rectangle2 = new Rectangle(3.5, 35.9);
        System.out.println("The area of a 3.5 x 35.9 Rectangle is " +
        rectangle2.getArea());
        System.out.println("The perimeter of a 3.5 x 35.9 Rectangle is " +
        rectangle2.getPerimeter());
    }
}
</code>```

This is my last homework for this class I just want this over with any help is appreciated.

答:
```<code>public class Exercise09_01 {
private double width = 1;
private double height = 1;

public Exercise09_01() {
}

public Exercise09_01(double newWidth, double newHeight) {
width = newWidth;
height = newHeight;
}

public double getArea() {
return width * height;
}

public double getPerimeter() {
return 2 * (width + height);
}

public static void main(String[] args) {
Exercise09_01 rectangle1 = new Exercise09_01(4, 40);
System.out.println("The area of a 4.0 x 40.0 Rectangle is " + rectangle1.getArea());
System.out.println("The perimeter of a 4.0 x 40.0 Rectangle is " +
rectangle1.getPerimeter());
Exercise09_01 rectangle2 = new Exercise09_01(3.5, 35.9);
System.out.println("The area of a 3.5 x 35.9 Rectangle is " + rectangle2.getArea());
System.out.println("The perimeter of a 3.5 x 35.9 Rectangle is " +
rectangle2.getPerimeter());
}
}
</code>```

Thanks for all the help and this is the code that passes through the compiler. Just leaving it here for future visitors.

Body:
This is my last homework for my java class and I have been trying to run this through a compiler but I don't understand whats wrong with the code.

I tried using void after reading about how that would fix the return type issue but that just made it worse, maybe I was putting void in the wrong place.

public class Exercise09_01 {
    private double width = 1;
    private double height = 1;

    public Rectangle() {
    }

    public Rectangle(double newWidth, double newHeight) {
        width = newWidth;
        height = newHeight;
    }

    public double getArea() {
        return width * height;
    }

    public double getPerimeter() {
        return 2 * (width + height);
    }

    public static void main(String[] args) {
        Rectangle rectangle1 = new Rectangle(4, 40);
        System.out.println("The area of a 4.0 x 40.0 Rectangle is " +
        rectangle1.getArea());
        System.out.println("The perimeter of a 4.0 x 40.0 Rectangle is " +
        rectangle1.getPerimeter());
        Rectangle rectangle2 = new Rectangle(3.5, 35.9);
        System.out.println("The area of a 3.5 x 35.9 Rectangle is " +
        rectangle2.getArea());
        System.out.println("The perimeter of a 3.5 x 35.9 Rectangle is " +
        rectangle2.getPerimeter());
    }
}

This is my last homework for this class I just want this over with any help is appreciated.

Body:
public class Exercise09_01 {
private double width = 1;
private double height = 1;

public Exercise09_01() {
}

public Exercise09_01(double newWidth, double newHeight) {
width = newWidth;
height = newHeight;
}

public double getArea() {
return width * height;
}

public double getPerimeter() {
return 2 * (width + height);
}

public static void main(String[] args) {
Exercise09_01 rectangle1 = new Exercise09_01(4, 40);
System.out.println("The area of a 4.0 x 40.0 Rectangle is " + rectangle1.getArea());
System.out.println("The perimeter of a 4.0 x 40.0 Rectangle is " +
rectangle1.getPerimeter());
Exercise09_01 rectangle2 = new Exercise09_01(3.5, 35.9);
System.out.println("The area of a 3.5 x 35.9 Rectangle is " + rectangle2.getArea());
System.out.println("The perimeter of a 3.5 x 35.9 Rectangle is " +
rectangle2.getPerimeter());
}
}

Thanks for all the help and this is the code that passes through the compiler. Just leaving it here for future visitors.


问:
How to resolve the "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index" error message?
I made a list of employees connected to MySQL database. Every employee's name can do CRUD. However, when updating employee data, this error message appears "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name : index"

How to overcome it? Here is my code

```<code>try {
  if (e.CommandName.Equals("Tambah")) {
    using(SqlConnection sqlcon = new SqlConnection(connectionString)) {
      sqlcon.Open();
      string query = "INSERT INTO EmployeeDB (NamaLengkap,Alamat,Telp,Email,Gender,Jabatan) VALUES (@NamaLengkap,@Alamat,@Telp,@Email,@Gender,@Jabatan)";
      SqlCommand sqlcmd = new SqlCommand(query, sqlcon);
      sqlcmd.Parameters.AddWithValue("@NamaLengkap", (gvEmployeeDB.FooterRow.FindControl("txtNamaLengkapFooter") as TextBox).Text.Trim());
      sqlcmd.Parameters.AddWithValue("@Alamat", (gvEmployeeDB.FooterRow.FindControl("txtAlamatFooter") as TextBox).Text.Trim());
      sqlcmd.Parameters.AddWithValue("@Telp", (gvEmployeeDB.FooterRow.FindControl("txtTelpFooter") as TextBox).Text.Trim());
      sqlcmd.Parameters.AddWithValue("@Email", (gvEmployeeDB.FooterRow.FindControl("txtEmailFooter") as TextBox).Text.Trim());
      sqlcmd.Parameters.AddWithValue("@Gender", (gvEmployeeDB.FooterRow.FindControl("txtGenderFooter") as TextBox).Text.Trim());
      sqlcmd.Parameters.AddWithValue("@Jabatan", (gvEmployeeDB.FooterRow.FindControl("txtJabatanFooter") as TextBox).Text.Trim());
      sqlcmd.ExecuteNonQuery();
      PopulateGridView();
      lblSuccessMessage.Text = "New Record Add!";
      lblErrorMessage.Text = "";
    }
  }
} catch (Exception ex) {

  lblSuccessMessage.Text = "";
  lblErrorMessage.Text = ex.Message;
}
</code>```

答:
In this case (and others), index is an internal parameter which signifies the position in the string on which the function is working at that moment. As an example, if index=3 then the function operates on the 4th letter of the string.

You get the specified error message if the procedure tries to work with a string either before the beginning of it (index<0) or beyond its end (index>length).

To solve it, you need to use the debugger, create a breakpoint at the line where the exception is thrown and see more closely what's happening there. Personally, I think it's somewhere in this code:

```<code>sqlcmd.Parameters.AddWithValue("@NamaLengkap", (gvEmployeeDB.FooterRow.FindControl("txtNamaLengkapFooter") as TextBox).Text.Trim());
sqlcmd.Parameters.AddWithValue("@Alamat", (gvEmployeeDB.FooterRow.FindControl("txtAlamatFooter") as TextBox).Text.Trim());
sqlcmd.Parameters.AddWithValue("@Telp", (gvEmployeeDB.FooterRow.FindControl("txtTelpFooter") as TextBox).Text.Trim());
sqlcmd.Parameters.AddWithValue("@Email", (gvEmployeeDB.FooterRow.FindControl("txtEmailFooter") as TextBox).Text.Trim());
sqlcmd.Parameters.AddWithValue("@Gender", (gvEmployeeDB.FooterRow.FindControl("txtGenderFooter") as TextBox).Text.Trim());
sqlcmd.Parameters.AddWithValue("@Jabatan", (gvEmployeeDB.FooterRow.FindControl("txtJabatanFooter") as TextBox).Text.Trim());
</code>```

I think this because, in the code you provided, this is the only place where strings modify their lengths. Check once again if you actually have texts to trim, or if one or more of your texts are null.

Body:
I made a list of employees connected to MySQL database. Every employee's name can do CRUD. However, when updating employee data, this error message appears "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name : index"

How to overcome it? Here is my code

try {
  if (e.CommandName.Equals("Tambah")) {
    using(SqlConnection sqlcon = new SqlConnection(connectionString)) {
      sqlcon.Open();
      string query = "INSERT INTO EmployeeDB (NamaLengkap,Alamat,Telp,Email,Gender,Jabatan) VALUES (@NamaLengkap,@Alamat,@Telp,@Email,@Gender,@Jabatan)";
      SqlCommand sqlcmd = new SqlCommand(query, sqlcon);
      sqlcmd.Parameters.AddWithValue("@NamaLengkap", (gvEmployeeDB.FooterRow.FindControl("txtNamaLengkapFooter") as TextBox).Text.Trim());
      sqlcmd.Parameters.AddWithValue("@Alamat", (gvEmployeeDB.FooterRow.FindControl("txtAlamatFooter") as TextBox).Text.Trim());
      sqlcmd.Parameters.AddWithValue("@Telp", (gvEmployeeDB.FooterRow.FindControl("txtTelpFooter") as TextBox).Text.Trim());
      sqlcmd.Parameters.AddWithValue("@Email", (gvEmployeeDB.FooterRow.FindControl("txtEmailFooter") as TextBox).Text.Trim());
      sqlcmd.Parameters.AddWithValue("@Gender", (gvEmployeeDB.FooterRow.FindControl("txtGenderFooter") as TextBox).Text.Trim());
      sqlcmd.Parameters.AddWithValue("@Jabatan", (gvEmployeeDB.FooterRow.FindControl("txtJabatanFooter") as TextBox).Text.Trim());
      sqlcmd.ExecuteNonQuery();
      PopulateGridView();
      lblSuccessMessage.Text = "New Record Add!";
      lblErrorMessage.Text = "";
    }
  }
} catch (Exception ex) {

  lblSuccessMessage.Text = "";
  lblErrorMessage.Text = ex.Message;
}

Body:
In this case (and others), index is an internal parameter which signifies the position in the string on which the function is working at that moment. As an example, if index=3 then the function operates on the 4th letter of the string.

You get the specified error message if the procedure tries to work with a string either before the beginning of it (index<0) or beyond its end (index>length).

To solve it, you need to use the debugger, create a breakpoint at the line where the exception is thrown and see more closely what's happening there. Personally, I think it's somewhere in this code:

sqlcmd.Parameters.AddWithValue("@NamaLengkap", (gvEmployeeDB.FooterRow.FindControl("txtNamaLengkapFooter") as TextBox).Text.Trim());
sqlcmd.Parameters.AddWithValue("@Alamat", (gvEmployeeDB.FooterRow.FindControl("txtAlamatFooter") as TextBox).Text.Trim());
sqlcmd.Parameters.AddWithValue("@Telp", (gvEmployeeDB.FooterRow.FindControl("txtTelpFooter") as TextBox).Text.Trim());
sqlcmd.Parameters.AddWithValue("@Email", (gvEmployeeDB.FooterRow.FindControl("txtEmailFooter") as TextBox).Text.Trim());
sqlcmd.Parameters.AddWithValue("@Gender", (gvEmployeeDB.FooterRow.FindControl("txtGenderFooter") as TextBox).Text.Trim());
sqlcmd.Parameters.AddWithValue("@Jabatan", (gvEmployeeDB.FooterRow.FindControl("txtJabatanFooter") as TextBox).Text.Trim());

I think this because, in the code you provided, this is the only place where strings modify their lengths. Check once again if you actually have texts to trim, or if one or more of your texts are null.


问:
Firestore onSnapshot updates and adds array to the DOM instead of only updating
I have data from Firestore that I'm mapping to the DOM and then updating client-side. While the data is updating how I want, every time the event fires, another updated array is added to the DOM.

I'm thinking the issue is with the how the click events are set up, but I'm not sure how else I can apply my client-side actions otherwise on the array.

here's my setup and click event

function App() {
  const [heroesArr, setHeroesArr] = useState([]);
  const db = firebase.firestore();
  const onFetch = () => {
    const newHeroes = [];
    db.collection("characterOptions").onSnapshot(coll => {
      coll.forEach(doc => {
        const { Name, uidDownvoted, uidUpvoted, votes } = doc.data();
        newHeroes.push({
          key: doc.id,
          doc,
          Name,
          uidDownvoted,
          uidUpvoted,
          votes
        });
      });
      setHeroesArr(newHeroes);
    });
  };

  const onUpVote = i => {
    const collRef = db.collection("characterOptions");
    setHeroesArr(heroesArr =>
      heroesArr.map((item, o) => {
        if (i === o && !item.uidDownvoted && !item.uidUpvoted) {
          collRef.doc(item.key).update({
            votes: firebase.firestore.FieldValue.increment(1),
            uidUpvoted: true
          });
        } else if (i === o && !item.uidDownvoted && item.uidUpvoted) {
          collRef.doc(item.key).update({
            votes: firebase.firestore.FieldValue.increment(-1),
            uidUpvoted: false
          });
        } else if (i === o && item.uidDownvoted && !item.uidUpvoted) {
          collRef.doc(item.key).update({
            votes: firebase.firestore.FieldValue.increment(2),
            uidUpvoted: true,
            uidDownvoted: false
          });
        }
        return item;
      })
    );
  };
```

<p>and here's the markup</p>

<pre class="lang-js prettyprint-override"><code> return (
    <div className="App">
      <button onClick={onFetch}>click</button>
      {heroesArr.map((item, i) => (
        <div key={item.key}>
          <p>{item.Name}</p>
          <p>{item.votes}</p>
          {item.uidDownvoted && <p>this has been downvoted</p>}
          {item.uidUpvoted && <p>this has been upvoted</p>}
          <button onClick={() => onUpVote(i)}>Upvote</button>
        </div>
      ))}
    </div>
  );
</code>```

I'm obviously just expecting the array to update, not to create an additional updated copy every time the click event is triggered.

答:
You have two options:

Always clear the array

Perform incremental updates

Since the first option is the simplest, I'll show you the code for that.

Right now, you declare your newHeroes outside of the onSnapshot, even though you only use it inside of it. This means that every time you loop over coll.forEach() you're adding all elements to newHeroes, including elements that you had read before.

The simplest option is to declare newHeroes inside the callback, so that it starts empty each time the callback runs.

```<code>db.collection("characterOptions").onSnapshot(coll => {
  const newHeroes = [];
  coll.forEach(doc => {
    const { Name, uidDownvoted, uidUpvoted, votes } = doc.data();
    newHeroes.push({
      key: doc.id,
      doc,
      Name,
      uidDownvoted,
      uidUpvoted,
      votes
    });
  });
  setHeroesArr(newHeroes);
});
</code>```

An alternative is to use the information that Firestore gives you about what documents are new, which ones are updated, etc. To get this information, you need to loop over coll.documentChanges. For an example of this, see the documentation on view changes between snapshots.

Body:
I have data from Firestore that I'm mapping to the DOM and then updating client-side. While the data is updating how I want, every time the event fires, another updated array is added to the DOM.

I'm thinking the issue is with the how the click events are set up, but I'm not sure how else I can apply my client-side actions otherwise on the array.

here's my setup and click event

function App() {
  const [heroesArr, setHeroesArr] = useState([]);
  const db = firebase.firestore();
  const onFetch = () => {
    const newHeroes = [];
    db.collection("characterOptions").onSnapshot(coll => {
      coll.forEach(doc => {
        const { Name, uidDownvoted, uidUpvoted, votes } = doc.data();
        newHeroes.push({
          key: doc.id,
          doc,
          Name,
          uidDownvoted,
          uidUpvoted,
          votes
        });
      });
      setHeroesArr(newHeroes);
    });
  };

  const onUpVote = i => {
    const collRef = db.collection("characterOptions");
    setHeroesArr(heroesArr =>
      heroesArr.map((item, o) => {
        if (i === o && !item.uidDownvoted && !item.uidUpvoted) {
          collRef.doc(item.key).update({
            votes: firebase.firestore.FieldValue.increment(1),
            uidUpvoted: true
          });
        } else if (i === o && !item.uidDownvoted && item.uidUpvoted) {
          collRef.doc(item.key).update({
            votes: firebase.firestore.FieldValue.increment(-1),
            uidUpvoted: false
          });
        } else if (i === o && item.uidDownvoted && !item.uidUpvoted) {
          collRef.doc(item.key).update({
            votes: firebase.firestore.FieldValue.increment(2),
            uidUpvoted: true,
            uidDownvoted: false
          });
        }
        return item;
      })
    );
  };

and here's the markup

 return (

      <button onClick={onFetch}>click</button>
      {heroesArr.map((item, i) => (

{item.Name}

{item.votes}

          {item.uidDownvoted &&
this has been downvoted
}
          {item.uidUpvoted &&
this has been upvoted
}
          <button onClick={() => onUpVote(i)}>Upvote</button>

      ))}

  );

I'm obviously just expecting the array to update, not to create an additional updated copy every time the click event is triggered.

Body:
You have two options:

Always clear the array

Perform incremental updates

Since the first option is the simplest, I'll show you the code for that.

Right now, you declare your newHeroes outside of the onSnapshot, even though you only use it inside of it. This means that every time you loop over coll.forEach() you're adding all elements to newHeroes, including elements that you had read before.

The simplest option is to declare newHeroes inside the callback, so that it starts empty each time the callback runs.

db.collection("characterOptions").onSnapshot(coll => {
  const newHeroes = [];
  coll.forEach(doc => {
    const { Name, uidDownvoted, uidUpvoted, votes } = doc.data();
    newHeroes.push({
      key: doc.id,
      doc,
      Name,
      uidDownvoted,
      uidUpvoted,
      votes
    });
  });
  setHeroesArr(newHeroes);
});

An alternative is to use the information that Firestore gives you about what documents are new, which ones are updated, etc. To get this information, you need to loop over coll.documentChanges. For an example of this, see the documentation on view changes between snapshots.


答:
Let see if I understood you well, do you want django to show you a url as such and not as plain text?

If you want to avoid django to show you the data as plain text, you can use the escape filter as follows: {{string | escape}}

Check this page for more details about django filters and tags

Title: How to process django url tags in context variables

Body:
I'm creating a django-based website where page content is stored in a model textfield with a detail view of the model displaying it. How can I put {% url %} tags in the content to link to other pages without hard coding links?

Putting the tag into the textfield will just print the tag as plain text. (or if inside an href create a broken link)

Other options are

parsing the content manually inside the view and replacing the tags with the correct url

using some django supplied string parser to create the links before sending to the template

maybe there is a way to do it in the template with a filter or tag around the variable.

I could probably do the manual way but I am hoping there is a django way that I am missing.

class Page(models.Model):
    content = models.TextField(blank=True)

class PageView(DetailView):
    model=Page
    context_object_name='page'

{% extends "base.html" %}

{% block content %}
    {{ page.content|safe }}
{% endblock %}

Edit for clarity:

Content in admin

What it renders

What it should render

Edit 2:
I was able to find a solution to the second option thanks to this answer on another question. Using that template_from_string function I rendered the page content as a template then replaced the content in the context with the rendered result.

class PageView(DetailView):
  model=Page
  context_object_name='page'
  def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    # Add to context here
    context['page'].content = template_from_string(context['page'].content).render(context)
    return context


问:
Want to use cos^-1 in Swift
I need help with my Swift code. I don't know how to use cos^-1. Would be great if anyone could show me a way.</p>

```<code> let cosinus = cos((.pi * cosinusValue / 180))
</code>```

答:
acos() and other mathematical functions from the BSD library can be used directly from Swift. Example:

```<code>import Darwin // or Foundation

let x = 0.0
let angle = acos(x)

print(angle) // 1.5707963267948966 (radians)
print(angle * 180.0 / .pi) // 90.0 (degrees)
</code>```

In a future version of Swift these functions are also available as static functions on the floating point types, compare SE-0246 Generic Math(s) Functions

```<code>let x = 0.0
let angle = Double.acos(x)

print(angle) // 1.5707963267948966 (radians)
print(angle * 180.0 / .pi) // 90.0 (degrees)
</code>```

Title: Want to use cos^-1 in Swift

Body:
I need help with my Swift code. I don't know how to use cos^-1. Would be great if anyone could show me a way.

 let cosinus = cos((.pi * cosinusValue / 180))

Body:
acos() and other mathematical functions from the BSD library can be used directly from Swift. Example:

import Darwin // or Foundation

let x = 0.0
let angle = acos(x)

print(angle) // 1.5707963267948966 (radians)
print(angle * 180.0 / .pi) // 90.0 (degrees)

In a future version of Swift these functions are also available as static functions on the floating point types, compare SE-0246 Generic Math(s) Functions

let x = 0.0
let angle = Double.acos(x)

print(angle) // 1.5707963267948966 (radians)
print(angle * 180.0 / .pi) // 90.0 (degrees)


问:
Receiving error; AttributeError: 'NoneType' object has no attribute 'app' while using render_template in return statement
I am trying to display the plotted figure using the web browser. But the render template in return statement is throwing error. Below is the code used and the error received.

The python code:

```<code>from flask import Flask, render_template, Response
import io
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import numpy as np

app = Flask(__name__,template_folder = 'D:/DATA_SETS')

@app.route('/html_example')
def myplot():
    with app.app_context():
        plt.figure()
        t = range(0,6,1)
        x= np.sin(t)
        plt.plot(t,x)
        plt.savefig('D:/DATA_SETS/new_plot.png')
        return Response(render_template('template_1.html', name = 'new_plot', url ='D:/DATA_SETS/new_plot.png'))

f = myplot()

if 1 == 1:
    app.run(debug=True)
</code>```

The template template_1.html

```<code><!doctype html>
<html>
   <body>

      <h1>Performance</h1>

        <p>{{ name }}</p>

        <img src={{ url}} alt="Chart" height="42" width="42">

   </body>
</html>
</code>```

Expected : The image return from function should be displayed in the HTML format written.

Current : The webpage is displaying 'Not Found Error'.
Webpage looking at is 'http://localhost:5000/html_example'

答:
The problem is in the return statement. It should be

```<code>return render_template('template_1.html', name = 'new_plot', url ='D:/DATA_SETS/new_plot.png'))
</code>```

and you should not be doing

```<code>f= myplot()
</code>```

for producing the image.
when you will hit the URL localhost:5000/ it will automatically do the process of producing image and serve it to frontend.

Update:
Directory Structure:

main.py

```<code>from flask import Flask, render_template, Response
import io
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import numpy as np

app = Flask(__name__,static_url_path="/folder/",static_folder="folder")

@app.route('/')
def myplot():
        plt.figure()
        t = range(0,6,1)
        x= np.sin(t)
        plt.plot(t,x)
        plt.savefig(app.static_folder+'/'+'new_plot.png')
        return render_template('template_1.html', name = 'new_plot', filename ='new_plot.png')

if __name__ == "__main__":
    app.run(debug=True)
</code>```

template_1.html

```<code><!doctype html>
<html>
   <body>

      <h1>Performance</h1>

        <p>{{ name }}</p>

        <img src="{{ url_for('static', filename=filename) }}" alt="Chart" height="100" width="100">

   </body>
</html>
</code>```

Output:

Body:
I am trying to display the plotted figure using the web browser. But the render template in return statement is throwing error. Below is the code used and the error received.

The python code:

from flask import Flask, render_template, Response
import io
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import numpy as np

app = Flask(__name__,template_folder = 'D:/DATA_SETS')

@app.route('/html_example')
def myplot():
    with app.app_context():
        plt.figure()
        t = range(0,6,1)
        x= np.sin(t)
        plt.plot(t,x)
        plt.savefig('D:/DATA_SETS/new_plot.png')
        return Response(render_template('template_1.html', name = 'new_plot', url ='D:/DATA_SETS/new_plot.png'))

f = myplot()

if 1 == 1:
    app.run(debug=True)

The template template_1.html

<!doctype html>

Performance

{{ name }}

Expected : The image return from function should be displayed in the HTML format written.

Current : The webpage is displaying 'Not Found Error'.
Webpage looking at is 'http://localhost:5000/html_example'

Body:
The problem is in the return statement. It should be

return render_template('template_1.html', name = 'new_plot', url ='D:/DATA_SETS/new_plot.png'))

and you should not be doing

f= myplot()

for producing the image.
when you will hit the URL localhost:5000/ it will automatically do the process of producing image and serve it to frontend.

Update:
Directory Structure:

main.py

from flask import Flask, render_template, Response
import io
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import numpy as np

app = Flask(__name__,static_url_path="/folder/",static_folder="folder")

@app.route('/')
def myplot():
        plt.figure()
        t = range(0,6,1)
        x= np.sin(t)
        plt.plot(t,x)
        plt.savefig(app.static_folder+'/'+'new_plot.png')
        return render_template('template_1.html', name = 'new_plot', filename ='new_plot.png')

if __name__ == "__main__":
    app.run(debug=True)

template_1.html

<!doctype html>
<html>
   <body>

      <h1>Performance</h1>

        <p>{{ name }}</p>

        <img src="{{ url_for('static', filename=filename) }}" alt="Chart" height="100" width="100">

   </body>
</html>

Output:


问:
Google App Engine communicate with Compute Engine over internal network
We're building an application in the google cloud. We're using App Engine as frontend and Compute Engine as backend. On these Compute Engine instances I'm running a TCP server that accepts certain "command" messages. The Compute Engine instances are also connected to the internet behind a firewall and load balancer for incoming https traffic. I would like to bind the TCP server to a local IP addres and allow only App Engine instances (thes are within the same project) to connect to the TCP "commands" port via the socket api.

For now we're limiting the incoming connections to Google Ip's only

The Compute Engine documentation sais the following:

Every instance is a member of a single network. A network performs the same function that a router does in a home network: it describes the network range and gateway IP address, handles communication between instances, and serves as a gateway between instances and callers outside the network. A network is constrained to a single project; it cannot span projects. Any communication between instances in different networks, even within the same project, must be through external IP addresses. In the API, a network is represented by the Network object.

Would it be possible to build a secure communication setup? Perhaps with App Engine backend instances?

答: As of April 9, 2019, you can use the serverless VPC connector to allow your App Engine application to connect to other services on the Google Cloud Platform. I linked to the Python standard environment docs, but this applies to any language on App Engine in either runtime environment.</p>


问:
Extending a tidy tibble to its original form
I have a tidy tibble.

```<code>Tibble <- data.frame(Doc_ID = c(1, 9, 9, 67),
                     Compartment = c("Car", "Truck", "Bus", "Plane"),
                     Count = c(3, 2, 1, 5))
</code>```

I need to extend it back to its original form.

```<code>Result <- data.frame(Doc_ID = c(1,1,1,9,9,9,67,67,67,67,67),
                     Compartment = c("Car","Car","Car","Truck","Truck","Bus",
                                     "Plane","Plane","Plane","Plane","Plane"))
</code>```

Does the tidy() function have an opposite function?

答:
We can use uncount from tidyr to expand the data to long format by specifying the weights as 'Count'

```<code>library(tidyr)
uncount(Tibble, Count)
</code>```

Body:
I have a tidy tibble.

Tibble <- data.frame(Doc_ID = c(1, 9, 9, 67),
                     Compartment = c("Car", "Truck", "Bus", "Plane"),
                     Count = c(3, 2, 1, 5))

I need to extend it back to its original form.

Result <- data.frame(Doc_ID = c(1,1,1,9,9,9,67,67,67,67,67),
                     Compartment = c("Car","Car","Car","Truck","Truck","Bus",
                                     "Plane","Plane","Plane","Plane","Plane"))

Does the tidy() function have an opposite function?

Body:
We can use uncount from tidyr to expand the data to long format by specifying the weights as 'Count'

library(tidyr)
uncount(Tibble, Count)


问:
Issue with TreeView in an ASP.NET master page
If I click the treeview in master page's leftside menu, the file should open in contect place holder (main). Below is my code.</p>

```<code><form id="form1" runat="server">
    <table>
        <tr>
            <td>
                <asp:TreeView ID="TreeView1" runat="server">
                    <Nodes>
                        <asp:TreeNode Expanded="True" Text="Sample Links" Value="Sample Links">
                            <asp:TreeNode NavigateUrl="~/one.htm" Target="fmain" Text="First Node"
                                Value="First Node"></asp:TreeNode>
                            <asp:TreeNode NavigateUrl="~/two.htm" Target="fmain" Text="Second Node"
                                Value="Second Node"></asp:TreeNode>
                            <asp:TreeNode NavigateUrl="~/three.htm" Target="fmain" Text="Third Node"
                                Value="Third Node"></asp:TreeNode>
                        </asp:TreeNode>
                    </Nodes>
                </asp:TreeView>
            </td>
            <td>
                <asp:ContentPlaceHolder id="tmain" runat="server">
                </asp:ContentPlaceHolder>
            </td>
        </tr>
    </table>
</form>
</code>```

答:
Master pages were designed for page inheritance, not as a page to load other pages. What you should be doing is using aspx pages which inherit from the master page.

Here are some guides on them:
http://www.asp.net/master-pages/tutorials

If you really must load in html files I suggest using an iframe or opening them in a new window.

Body:
If I click the treeview in master page's leftside menu, the file should open in contect place holder (main). Below is my code.

<form id="form1" runat="server">

                <asp:TreeView ID="TreeView1" runat="server">
                    <Nodes>
                        <asp:TreeNode Expanded="True" Text="Sample Links" Value="Sample Links">
                            <asp:TreeNode NavigateUrl="~/one.htm" Target="fmain" Text="First Node"
                                Value="First Node"></asp:TreeNode>
                            <asp:TreeNode NavigateUrl="~/two.htm" Target="fmain" Text="Second Node"
                                Value="Second Node"></asp:TreeNode>
                            <asp:TreeNode NavigateUrl="~/three.htm" Target="fmain" Text="Third Node"
                                Value="Third Node"></asp:TreeNode>
                        </asp:TreeNode>
                    </Nodes>
                </asp:TreeView>

                <asp:ContentPlaceHolder id="tmain" runat="server">
                </asp:ContentPlaceHolder>

</form>


问:
SweetAlert isn't waiting confirm
My SweetAlert confirm is not waiting any action. Confirm box just flashes and then action will be executed. What's wrong?

```<code><script type="text/javascript">
    function confirmDelete() {
        swal({
            title: "Are you sure?",
            text: "You will not be able to recover this imaginary file!",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "Delete",
            cancelButtonText: "Cancel",
            closeOnConfirm: false,
            closeOnCancel: false
        });
    }
</script>

<form onsubmit="confirmDelete()" action="index.php" method="post">
    <button type="submit" name="delete">Delete</button>
</form>
</code>```

Also tried this. Same problem... the window just flashes and action executes.

```<code><script type="text/javascript">
    function confirmDelete() {
        swal({
            title: "Are you sure?",
            text: "You will not be able to recover this imaginary file!",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "Delete",
            cancelButtonText: "Cancel",
            closeOnConfirm: false,
            closeOnCancel: false
        },
        function(isConfirm) {
            if (isConfirm) {
                document.deleteForm.submit();
            }
        });
    }
</script>

<form id="deleteForm" action="index.php" method="post">
    <button onclick="confirmDelete()" type="input" name="delete">Delete</button>
</form>
</code>```

答:
Change your code as per below:

In view:

```<code><form id="my_form" action="index.php" method="post">
     <a href="javascript:void(0);" class="btn btn-primary _delete_data">DELETE</a>
</form>
</code>```

In js code:

```<code><script>
    $(document).ready(function(){
        $('._delete_data').click(function(e){

            Swal.fire({
                title: 'Are you sure?',
                text: "You won't be able to revert this!",
                type: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, delete it!'
            }).then((result) => {

                if (result.value) {
                    $(document).find('#my_form').submit();
                }
            })
        });
    });
</script>
</code>```

Title: SweetAlert isn't waiting confirm

Body:
My SweetAlert confirm is not waiting any action. Confirm box just flashes and then action will be executed. What's wrong?

<form onsubmit="confirmDelete()" action="index.php" method="post">
    <button type="submit" name="delete">Delete</button>
</form>

Also tried this. Same problem... the window just flashes and action executes.

<form id="deleteForm" action="index.php" method="post">
    <button onclick="confirmDelete()" type="input" name="delete">Delete</button>
</form>

Body:
Change your code as per below:

In view:

<form id="my_form" action="index.php" method="post">
     <a href="javascript:void(0);" class="btn btn-primary _delete_data">DELETE</a>
</form>

In js code:

<script>
    $(document).ready(function(){
        $('._delete_data').click(function(e){

            Swal.fire({
                title: 'Are you sure?',
                text: "You won't be able to revert this!",
                type: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, delete it!'
            }).then((result) => {

                if (result.value) {
                    $(document).find('#my_form').submit();
                }
            })
        });
    });
</script>


问:
Rails Form not saving the Association Attributes
For some reason, the form seems to work as intended but it does not process correctly:

Here are the parameters that are sent to my Paragraph#create method

Parameters: {"utf8"=>"✓", "authenticity_token"=>"s6V7WS6NZwcu4ZAeSenkEgVEd6MrrDD1asMjPEOuZHyglMKoGQ/5cP/USzF/5MJV3wyFn+siC2t47dSFkVtuVQ==", "paragraph"=>{"sentiments_attributes"=>{"0"=>{"body"=>"test"}}}}

I get this error when trying to submit the form: Sentiments body can't be blank

```<code> #paragraphs_controller.rb
  def create
    @paragraph = Paragraph.new(paragraph_params)
    @paragraph.sentiments.build
    if @paragraph.save
      redirect_to root_url
    else
      puts @paragraph.errors.full_messages
      redirect_to root_url
    end
  end

  private
  def paragraph_params
    params.require(:paragraph).permit(:sentiments_attributes => [:body])
  end
</code>```

I have 2 models, Sentiment & Paragraph. The Paragraph is a collection of sentiments. So if I have a form to create a new paragraph, it creates a sentiment at the same time.

```<code>class Sentiment < ApplicationRecord
  belongs_to :paragraph, optional: true
  validates :body, presence: true

end
class Paragraph < ApplicationRecord
  has_many :sentiments
  accepts_nested_attributes_for :sentiments

end

<%= form_for(@paragraph) do |f| %>
  <%= f.fields_for :sentiments do |u| %>
        <%= u.text_area :body %>
  <% end  %>
  <%= f.submit %>
<% end %>
</code>```

UPDATED

Need to remove @paragraph.sentiments.build from paragraphs_controller#create

答: Need to remove @paragraph.sentiments.build from paragraphs_controller#create</p>

Body:
For some reason, the form seems to work as intended but it does not process correctly:

Here are the parameters that are sent to my Paragraph#create method

Parameters: {"utf8"=>"✓", "authenticity_token"=>"s6V7WS6NZwcu4ZAeSenkEgVEd6MrrDD1asMjPEOuZHyglMKoGQ/5cP/USzF/5MJV3wyFn+siC2t47dSFkVtuVQ==", "paragraph"=>{"sentiments_attributes"=>{"0"=>{"body"=>"test"}}}}

I get this error when trying to submit the form: Sentiments body can't be blank

 #paragraphs_controller.rb
  def create
    @paragraph = Paragraph.new(paragraph_params)
    @paragraph.sentiments.build
    if @paragraph.save
      redirect_to root_url
    else
      puts @paragraph.errors.full_messages
      redirect_to root_url
    end
  end

  private
  def paragraph_params
    params.require(:paragraph).permit(:sentiments_attributes => [:body])
  end

I have 2 models, Sentiment & Paragraph. The Paragraph is a collection of sentiments. So if I have a form to create a new paragraph, it creates a sentiment at the same time.

class Sentiment < ApplicationRecord
  belongs_to :paragraph, optional: true
  validates :body, presence: true

end
class Paragraph < ApplicationRecord
  has_many :sentiments
  accepts_nested_attributes_for :sentiments

end

<%= form_for(@paragraph) do |f| %>
  <%= f.fields_for :sentiments do |u| %>
        <%= u.text_area :body %>
  <% end  %>
  <%= f.submit %>
<% end %>

UPDATED

Need to remove @paragraph.sentiments.build from paragraphs_controller#create


问:
Why is the ::before pseudo element going on top on mobile menu?
I have a menu that has a png img as ::before pseudo-element, and instead of sticking next to menu items, it's going on top.

const menu_button = $('img');
const menu_nav = $('#myNav');

menu_button.click(function(){
  menu_nav.toggleClass('menu_open')
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.overlay {
  height: 0%;
  width: 100%;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #d6cece;
  overflow-y: auto;
  transition: 0.5s;
}

.overlay-content {
  position: relative;
  top: 10%;
  width: 100%;
  margin-top: 50px;
}

.overlay a {
  padding-left: 30px;
  padding-bottom: 5px;
  padding-top: 5px;
  text-decoration: none;
  font-size: 27px;
  display: block;
  transition: 0.3s;
  font-style: italic;
  color: black;
}

.overlay-content a:before {
  width: 6px;
  content: " ";
  background-image: url(https://picsum.photos/5);
  background-repeat: no-repeat;
  position: absolute;
  left: 18px;
  top: 18px;
  height: 20px;
}

.menu_open {
  height: 100%;
}</code>```

    Test
    Test
    Test
    Test

```

Why this behavior? It's working without the menu, but not when the elements are vertically aligned. Please check out the snippet I quickly made.

答:
the elements are going "on top" because you set top to 18px for all elements.

that wouldn't be a problem if the positioning context for absolute positioning, was set correctly (the a element instead of the overlay-content div).

you should set the positioning context to the a element itself:

```<code>.overlay a {
  position: relative;
}
</code>```

Body:
I have a menu that has a png img as ::before pseudo-element, and instead of sticking next to menu items, it's going on top.

const menu_button = $('img');
const menu_nav = $('#myNav');

menu_button.click(function(){
  menu_nav.toggleClass('menu_open')
});

.overlay {
  height: 0%;
  width: 100%;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #d6cece;
  overflow-y: auto;
  transition: 0.5s;
}

.overlay-content {
  position: relative;
  top: 10%;
  width: 100%;
  margin-top: 50px;
}

.overlay a {
  padding-left: 30px;
  padding-bottom: 5px;
  padding-top: 5px;
  text-decoration: none;
  font-size: 27px;
  display: block;
  transition: 0.3s;
  font-style: italic;
  color: black;
}

.overlay-content a:before {
  width: 6px;
  content: " ";
  background-image: url(https://picsum.photos/5);
  background-repeat: no-repeat;
  position: absolute;
  left: 18px;
  top: 18px;
  height: 20px;
}

.menu_open {
  height: 100%;
}

    Test
    Test
    Test
    Test

Why this behavior? It's working without the menu, but not when the elements are vertically aligned. Please check out the snippet I quickly made.

Body:
the elements are going "on top" because you set top to 18px for all elements.

that wouldn't be a problem if the positioning context for absolute positioning, was set correctly (the a element instead of the overlay-content div).

you should set the positioning context to the a element itself:

.overlay a {
  position: relative;
}


问:
How to unit test gRPC service in go
I'm having difficulties in unit testing the gRPC service in go.

I looked at Testing a gRPC service but it isn't working for me, not sure what I'm doing wrong.

gRPC service implementation for the Add method:

```<code>type server struct{}

func main() {
    listener, err := net.Listen("tcp", ":4040")
    if err != nil {
      panic(err)
    }

    srv := grpc.NewServer()
    service.RegisterMathOpServiceServer(srv, &server{})
    reflection.Register(srv)

    if e := srv.Serve(listener); e != nil {
          panic(e)
    }

    fmt.Println("Service is running on localhost:4040")
}

func (s *server) Add(ctx context.Context, request *service.AddRequest)
(*service.AddResponse, error) {
    a, b := request.GetX(), request.GetY()
    result := a + b

    return &service.AddResponse{Answer: result}, nil
}
</code>```

Unit Test for the Add method:

package test

import (
    "context"
    pb "mathOp_service/src/service"
    "testing"
)
func TestAddition(t *testing.T) {
    s := server{}   <-- error occurs here
    req := pb.AddRequest{X: int64(1), Y: int64(2)}
    res, err := s.Add(context.Background(), req)

    if res.Answer != 3 {
        t.Error("Expected 1 + 2 to equal 3")
    }
}
```

Project Directory structure

s := server{} throws an error saying undefined: server.

I'm very new to Go and can't find a solution to fix this.

答:
Looking at your code organization, It seems that you are coming from Java background putting the src and test in there respective folders. I also struggled with the same when I started writing go. What I learned is it is better to have the src and test in the same package and folder therefore, to make the code idiomatic go and it also resolves any variable/methods references within the same package. So in your tests, you only need to import the pb package.

I will also encourage you to look at https://github.com/golang-standards/project-layout for various code organization techniques in Golang.

Title: How to unit test gRPC service in go

Body:
I'm having difficulties in unit testing the gRPC service in go.

I looked at Testing a gRPC service but it isn't working for me, not sure what I'm doing wrong.

gRPC service implementation for the Add method:

type server struct{}

func main() {
    listener, err := net.Listen("tcp", ":4040")
    if err != nil {
      panic(err)
    }

    srv := grpc.NewServer()
    service.RegisterMathOpServiceServer(srv, &server{})
    reflection.Register(srv)

    if e := srv.Serve(listener); e != nil {
          panic(e)
    }

    fmt.Println("Service is running on localhost:4040")
}

func (s *server) Add(ctx context.Context, request *service.AddRequest)
(*service.AddResponse, error) {
    a, b := request.GetX(), request.GetY()
    result := a + b

    return &service.AddResponse{Answer: result}, nil
}

Unit Test for the Add method:

package test

import (
    "context"
    pb "mathOp_service/src/service"
    "testing"
)
func TestAddition(t *testing.T) {
    s := server{}   <-- error occurs here
    req := pb.AddRequest{X: int64(1), Y: int64(2)}
    res, err := s.Add(context.Background(), req)

    if res.Answer != 3 {
        t.Error("Expected 1 + 2 to equal 3")
    }
}

Project Directory structure

s := server{} throws an error saying undefined: server.

I'm very new to Go and can't find a solution to fix this.


问:
How to execute custom C++ binary on HDFS file
I have custom c++ binaries which reads raw data file and writes derived data file. The size of files are in 100Gbs. Moreover, I would like to process multiple 100Gb files in parallel and generated a materialized view of derived metadata. Hence, map-reduce paradigm seems more scalable.

I am a newbie in Hadoop ecosystem. I have used Ambari to setup a Hadoop cluster on AWS. I have built my custom C++ binaries on every data node and loaded the raw data files on HDFS. What are my options to execute this binary on HDFS files?

答:
Hadoop streaming is the simplest way to run non-Java applications as MapReduce.

Refer to Hadoop Streaming for more details.


问:
How to style ng-zorro component with angular css component?
I have a certain problem, for example:

I don't like the margin on the ng-zorro table.
In my browser I can see that it gets the margin from .ant-table-small>.ant-table-content>.ant-table-body selector.

Is there some way to override it?

It doesn't exist in ng-zorro theme.less.
I am terribly sorry for this noob question.

答:
You can override the Angular css by ::ng-deep keyword, for example:

::ng-deep .ant-table-small>.ant-table-content>.ant-table-body {
    margin: 0;
}
```


问:
Bootstrap modal hide not working with jquery ajax
I have a modal dialog made with bootstrap, like this:

```<code><div class="modal fade" id="myid">
  <div class="modal-dialog">
    <div class="modal-content">
       Loading...
    </div>
  </div>
</div>
</code>```

And I make a javascript function like this:

```<code>$(document)
            .ajaxStart(function () {
                $('#myid').modal('show');
            })
            .ajaxStop(function () {
                $('#myid').modal('hide');
            });
</code>```

But when I call some ajax function the modal appears but no hide. I put console.log in both functions (ajaxStart and ajaxStop) and it was called. when I replace ajaxStop as below, everything works, but not appears right.

```<code>$(document)
                .ajaxStart(function () {
                    $('#myid').modal('show');
                })
                .ajaxStop(function () {
                    $('#myid').hide();
                    $('.fade').hide();
                });
</code>```

The main problema is when I call another modal within ajax, then I click in link, loading ajax appears, request is send to server, response returns, modal with data from request appears, but loading modal not hide.

How can I fix it?

答: Instead of using $('#myid').hide(); in ajaxStop, use $('#myid').modal('hide');

Body:
I have a modal dialog made with bootstrap, like this:

       Loading...

And I make a javascript function like this:

$(document)
            .ajaxStart(function () {
                $('#myid').modal('show');
            })
            .ajaxStop(function () {
                $('#myid').modal('hide');
            });

But when I call some ajax function the modal appears but no hide. I put console.log in both functions (ajaxStart and ajaxStop) and it was called. when I replace ajaxStop as below, everything works, but not appears right.

$(document)
                .ajaxStart(function () {
                    $('#myid').modal('show');
                })
                .ajaxStop(function () {
                    $('#myid').hide();
                    $('.fade').hide();
                });

The main problema is when I call another modal within ajax, then I click in link, loading ajax appears, request is send to server, response returns, modal with data from request appears, but loading modal not hide.

How can I fix it?


问:
Can -Exclude and -Filter be used together?
I have the following script in which I am trying to get any LATEST csv file with Members in its name but not members AND server[-1] in its name

suppose server is an array holding servers in it. as an example, the file that should be left out would be Members_server1.domain.com.csv

```<code>Get-ChildItem "$csvLocation" -Filter '*Members*.csv' -Exclude "*Members_$($Server[-1])*.csv" | Where-Object {
                    $_.LastWriteTime.GetDateTimeFormats()[44] -eq $today
                } | Move-Item -Destination "$csvLocation\$($DBName)_Members_$($Server[-1]).csv" -Force
</code>```

However, it doesn't look like exclude is working.

what am I doing wrong?

答:
Yes, -Filter and -Exclude can be used together: -Filter filters at the source (asks the filesystem to perform the filtering, which is much faster than using -Include)) and -Exclude then makes PowerShell exclude matches.

However, with Get-ChildItem, the -Include and -Exclude parameters - surprisingly - apply only directly to the leaf component of the (implied) -Path or -LiteralPath argument, not its children.

While including -Recurse extends the inclusions / exclusions to the leaf components of all items inside the target folder, that obviously changes the behavior, given that not only the immediate children are processed.

To process only the immediate children while applying inclusions / exclusions, use wildcard expression *:

```<code>Get-ChildItem $csvLocation/* -Filter *Members*.csv -Exclude "*Members_$($Server[-1])*.csv"
</code>```

Note that Get-Item would equally work in this case, given that the aspect of child-item processing is achieved by the wildcard expression.

Body:
I have the following script in which I am trying to get any LATEST csv file with Members in its name but not members AND server[-1] in its name

suppose server is an array holding servers in it. as an example, the file that should be left out would be Members_server1.domain.com.csv

Get-ChildItem "$csvLocation" -Filter '*Members*.csv' -Exclude "*Members_$($Server[-1])*.csv" | Where-Object {
                    $_.LastWriteTime.GetDateTimeFormats()[44] -eq $today
                } | Move-Item -Destination "$csvLocation\$($DBName)_Members_$($Server[-1]).csv" -Force

However, it doesn't look like exclude is working.

what am I doing wrong?

Body:
Yes, -Filter and -Exclude can be used together: -Filter filters at the source (asks the filesystem to perform the filtering, which is much faster than using -Include)) and -Exclude then makes PowerShell exclude matches.

However, with Get-ChildItem, the -Include and -Exclude parameters - surprisingly - apply only directly to the leaf component of the (implied) -Path or -LiteralPath argument, not its children.

While including -Recurse extends the inclusions / exclusions to the leaf components of all items inside the target folder, that obviously changes the behavior, given that not only the immediate children are processed.

To process only the immediate children while applying inclusions / exclusions, use wildcard expression *:

Get-ChildItem $csvLocation/* -Filter *Members*.csv -Exclude "*Members_$($Server[-1])*.csv"

Note that Get-Item would equally work in this case, given that the aspect of child-item processing is achieved by the wildcard expression.


问:
How to insert pair into map
I have the following map structure: map < pair < int,int >, object* > and I wish to insert into it.

How would I do it since I am trying to insert a pair and an object and I must make a pair out of this?

Should I create a new pair using make_pair() out of the pair and object that I have? If so, could you please let me know how to do this?

答:
```<code>int a=10,b=20;

map < pair < int,int >, int > m;

pair < int,int >numbers = make_pair(a,b);

int sum=a+b;

m[numbers]=sum;
</code>```

Our map will have its key as pairs of numbers.We can access the integer values of pair variable using dot(.) operator.

Title: How to insert pair into map

Body:
int a=10,b=20;

map < pair < int,int >, int > m;

pair < int,int >numbers = make_pair(a,b);

int sum=a+b;

m[numbers]=sum;

Our map will have its key as pairs of numbers.We can access the integer values of pair variable using dot(.) operator.


问:
How to generate some feasible solutions in CPLEX-PYTHON (Not docplex)?
I am working on my thesis about a variant form of Vehicle routing problem (VRP) using a linear mathematical programming approach. I have a well-tested model that I formulated but this model is solved in an acceptable computational time for at most 30 nodes, so I need to implement some metaheuristics to find good feasible solutions for bigger instances, so here is the question. I know that I can generate some solutions using a python-cplex command solution_pool (something like that) so I would like help to know how to generate and access to these solutions (objective function value, decision variables values, etc) my model is a cplex object Model. I know that this is possible if you could help me it would be great. Thanks in advance and greetings from Chile.</p>

答:
Once you have your cpx object you may write</p>

```<code>cpx.populate_solution_pool()
numsol = cpx.solution.pool.get_num()
print("The solution pool contains %d solutions." % numsol)
meanobjval = cpx.solution.pool.get_mean_objective_value()

sol_pool = []
for i in range(numsol):
    objval_i = cpx.solution.pool.get_objective_value(i)
    x_i = cpx.solution.pool.get_values(i)
    nb_vars=len(x_i)
    sol = []
    for k in range(nb_vars):
        sol.append(x_i[k])
    sol_pool.append(sol)
print("pools =",sol_pool)
</code>```

Body:
Once you have your cpx object you may write

cpx.populate_solution_pool()
numsol = cpx.solution.pool.get_num()
print("The solution pool contains %d solutions." % numsol)
meanobjval = cpx.solution.pool.get_mean_objective_value()

sol_pool = []
for i in range(numsol):
    objval_i = cpx.solution.pool.get_objective_value(i)
    x_i = cpx.solution.pool.get_values(i)
    nb_vars=len(x_i)
    sol = []
    for k in range(nb_vars):
        sol.append(x_i[k])
    sol_pool.append(sol)
print("pools =",sol_pool)


问:
How to check whether Java plugins are installed or not in a browser using Code .?
How to check whether Java plugins are installed or not in a browser using java or javascript or JSP Code .?</p>

答:
Java/Sun/Oracle provides a deployment toolkit script in the form of a JavaScript file that lets you achieve what you need.

You could invoke the getJREs() function which returns an array of currently-installed JRE version strings.

You can even install a particular JRE version if you need to, via the installJRE(requestVersion) function.