问:
Inserting nodes at the end of a linked list
I'm having trouble inserting a node at the end of a linked list. The logic to me and others i have asked seems fine, however the problem remains and i'm clueless to where it might be happening.I insert the first node fine, it prints correctly. When, however, i try to insert the following node, it's as if the other has been deleted and substituted by the new one.Here are the functions i'm using :

```<code>struct client_info{
  pthread_t client_ID;
  int sockfd;
  struct chat chats;
  char user[NAMELEN];
  struct client_info *next;
  char current[NAMELEN];
};

struct header{
  struct client_info *fnode, *lnode;
}client_head;
void client_insert(struct client_info *node){
  if(client_head.fnode == NULL){
    client_head.fnode = node;
    client_head.lnode = node;
  }
  else{
    client_head.lnode->next = node;
    client_head.lnode = node;
  }
}
void display_clients(){
  struct client_info *tmp = client_head.fnode;
  while(tmp!=NULL){
    printf("Username: %s\nSocket: %d\n--------------------\n",tmp->user,tmp->sockfd);
    tmp = tmp->next;
  }
}

//inside main.
while(1){
    size = sizeof(struct sockaddr_in);
    if((clientfd = accept(sockfd, (struct sockaddr *)&client_addr,(socklen_t*)&size))>0){
      printf("Client accepted\n");
      struct client_info clinfo;
      clinfo.sockfd = clientfd;
      clinfo.next = NULL;
      pthread_mutex_lock(&mutex);
      client_insert(&clinfo);
      pthread_mutex_unlock(&mutex);
      pthread_create(&clinfo.client_ID, NULL, client_commands_handler, (void *)&clinfo);
    }
    else{
      perror("accept");
    }
  }
  return 0;
}
</code>```

the accept funtion in main, is because i'm using this for a chat program. fnode and lnode in this code are, respectively, the pointers to the first and last node of the list (head and tail).
So for instance i have a connected client named jack with socket number 5, him being the first and only connected client, it would rightfully print out jack and 5. however if a sencond client, amy joins in with socket 3 it would only print out amy and 3, without the first client, and so on and so forth.

答:
Inside your while loop, you declare clinfo as a instance of struct client_info.  You then pass the address of that variable to client_insert to put that variable's address in the list.

When you then reach the end of the loop, that variable goes out of scope.  So now you have the address of an out-of-scope variable.  Subsequently using that address invokes undefined behaivor.

As to why things seem to be overwritten, that's exactly what's happening.  On each loop iteration, you have an instance of struct client_info which just so happens (due to undefined behavior) to have the same address as the last time through the loop.  So you're passing in the same address to client_insert each time.

You instead need to dynamically allocate an instance of struct client_info and add that to the list.

```<code>  struct client_info *clinfo = malloc(sizeof(*clinfo);
  if (!clinfo) {
      perror("malloc failed");
      exit(1);
  }
  clinfo->sockfd = clientfd;
  clinfo->next = NULL;
  pthread_mutex_lock(&mutex);
  client_insert(clinfo);
  pthread_mutex_unlock(&mutex);
  pthread_create(&clinfo->client_ID, NULL, client_commands_handler, clinfo);
</code>```

Body:
I'm having trouble inserting a node at the end of a linked list. The logic to me and others i have asked seems fine, however the problem remains and i'm clueless to where it might be happening.I insert the first node fine, it prints correctly. When, however, i try to insert the following node, it's as if the other has been deleted and substituted by the new one.Here are the functions i'm using :

struct client_info{
  pthread_t client_ID;
  int sockfd;
  struct chat chats;
  char user[NAMELEN];
  struct client_info *next;
  char current[NAMELEN];
};

struct header{
  struct client_info *fnode, *lnode;
}client_head;
void client_insert(struct client_info *node){
  if(client_head.fnode == NULL){
    client_head.fnode = node;
    client_head.lnode = node;
  }
  else{
    client_head.lnode->next = node;
    client_head.lnode = node;
  }
}
void display_clients(){
  struct client_info *tmp = client_head.fnode;
  while(tmp!=NULL){
    printf("Username: %s\nSocket: %d\n--------------------\n",tmp->user,tmp->sockfd);
    tmp = tmp->next;
  }
}

//inside main.
while(1){
    size = sizeof(struct sockaddr_in);
    if((clientfd = accept(sockfd, (struct sockaddr *)&client_addr,(socklen_t*)&size))>0){
      printf("Client accepted\n");
      struct client_info clinfo;
      clinfo.sockfd = clientfd;
      clinfo.next = NULL;
      pthread_mutex_lock(&mutex);
      client_insert(&clinfo);
      pthread_mutex_unlock(&mutex);
      pthread_create(&clinfo.client_ID, NULL, client_commands_handler, (void *)&clinfo);
    }
    else{
      perror("accept");
    }
  }
  return 0;
}

the accept funtion in main, is because i'm using this for a chat program. fnode and lnode in this code are, respectively, the pointers to the first and last node of the list (head and tail).
So for instance i have a connected client named jack with socket number 5, him being the first and only connected client, it would rightfully print out jack and 5. however if a sencond client, amy joins in with socket 3 it would only print out amy and 3, without the first client, and so on and so forth.

Body:
Inside your while loop, you declare clinfo as a instance of struct client_info.  You then pass the address of that variable to client_insert to put that variable's address in the list.

When you then reach the end of the loop, that variable goes out of scope.  So now you have the address of an out-of-scope variable.  Subsequently using that address invokes undefined behaivor.

As to why things seem to be overwritten, that's exactly what's happening.  On each loop iteration, you have an instance of struct client_info which just so happens (due to undefined behavior) to have the same address as the last time through the loop.  So you're passing in the same address to client_insert each time.

You instead need to dynamically allocate an instance of struct client_info and add that to the list.

  struct client_info *clinfo = malloc(sizeof(*clinfo);
  if (!clinfo) {
      perror("malloc failed");
      exit(1);
  }
  clinfo->sockfd = clientfd;
  clinfo->next = NULL;
  pthread_mutex_lock(&mutex);
  client_insert(clinfo);
  pthread_mutex_unlock(&mutex);
  pthread_create(&clinfo->client_ID, NULL, client_commands_handler, clinfo);


来源: stackexchange

问:
VBA spitting out error at seemingly arbitrary time?

I have an array of formulas that I am filling across all relevant columns on Row 2. After that, I have code that fills the range with dynamic references. This particular data set has 74 rows of data, but for some reason the receive the

438 Error: 'Object doesn't support this property or method'

at row 65 every time.

```<code>     'Find last row/col variables
        Dim lastRow As Long
        Dim lastCol As Long
        'Array variable
        Dim TestFormulas() As Variant
       'WS variable
         Dim WS as Worksheet

    lastRow = Cells.Find(What:="*", _
                    After:=Range("A1"), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row

lastCol = Cells.Find(What:="*", _
                    After:=Range("A1"), LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByColumns, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row

'Create Array [this is cut down significantly. There are roughly 50 formulas here. Code runs quickly, if it matters.]
TestFormulas() = Array( _
                  "=Sheet1!H2", "=Sheet1!B2", "=IF(Sheet1!P2=""Resiliency""")

'Fill Row 2 with formulas
 With WS
    For i = LBound(TestFormulas()) To UBound(TestFormulas())
      .Cells(2, 1 + i).Formula = TestFormulas(i)
    Next i
 End With

'Copy formulas and fill down the entire range
 Range("A2:" & lastCol & ":" & "2").Formula = TestFormulas
 Range("A2:" & WS(1).lastCol & ":" & WS(1).lastRow).FillDown
</code>```

I am expecting the range to fill with the dynamic formula. It fills, dynmically at that, though only up to and including row 65.

438 Error: 'Object doesn't support this property or method'

答:
```<code>Dim lastRow As Long

'Array variable
Dim TestFormulas() As Variant
'WS variable
Dim WS As Worksheet

Set WS = Worksheets("Sheet4") ' change to your sheet name

With WS
    If Application.WorksheetFunction.CountA(Worksheets("Sheet1").Cells) > 0 Then
        lastRow = Worksheets("Sheet1").Cells.Find(What:="*", _
            After:=Range("A1"), _
            LookAt:=xlPart, _
            LookIn:=xlFormulas, _
            SearchOrder:=xlByRows, _
            SearchDirection:=xlPrevious, _
            MatchCase:=False).Row

        'Create Array [this is cut down significantly. There are roughly 50 formulas here. Code runs quickly, if it matters.]
        TestFormulas() = Array( _
        "=Sheet1!H2", "=Sheet1!B2", "=IF(Sheet1!P2=""Resiliency"",TRUE,FALSE)")

        'Fill Row 2 with formulas

        For i = LBound(TestFormulas()) To UBound(TestFormulas())
            .Range(.Cells(2, 1 + i), .Cells(lastRow, 1 + i)).Formula = TestFormulas(i)
        Next i
    End If
End With
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an array of formulas that I am filling across all relevant columns on Row 2. After that, I have code that fills the range with dynamic references. This particular data set has 74 rows of data, but for some reason the receive the

438 Error: 'Object doesn't support this property or method'

at row 65 every time.

     'Find last row/col variables
        Dim lastRow As Long
        Dim lastCol As Long
        'Array variable
        Dim TestFormulas() As Variant
       'WS variable
         Dim WS as Worksheet

    lastRow = Cells.Find(What:="*", _
                    After:=Range("A1"), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row

lastCol = Cells.Find(What:="*", _
                    After:=Range("A1"), LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByColumns, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row

'Create Array [this is cut down significantly. There are roughly 50 formulas here. Code runs quickly, if it matters.]
TestFormulas() = Array( _
                  "=Sheet1!H2", "=Sheet1!B2", "=IF(Sheet1!P2=""Resiliency""")

'Fill Row 2 with formulas
 With WS
    For i = LBound(TestFormulas()) To UBound(TestFormulas())
      .Cells(2, 1 + i).Formula = TestFormulas(i)
    Next i
 End With

'Copy formulas and fill down the entire range
 Range("A2:" & lastCol & ":" & "2").Formula = TestFormulas
 Range("A2:" & WS(1).lastCol & ":" & WS(1).lastRow).FillDown

I am expecting the range to fill with the dynamic formula. It fills, dynmically at that, though only up to and including row 65.

438 Error: 'Object doesn't support this property or method'


问:
Edit Comment Template in Netbeans PHP 6.8
I would like to ask is there any way change the comment code template in Netbeans PHP 6.8

In eclipse, when I type /** ENTER , it would come out the comment template that I set in the setting, like this:

```<code>/**
* Apr 19, 2010 - Shiro
* Description
*
* @return unknown_type
*/
function test()
{

}
</code>```

by Default Netbeans only will show the parameter in the function.

```<code>/**
  *
  * @param <type> $order_No
  * @param <type> $array
  */
</code>```

in Netbeans is there any possible I could found any customization about this, anyone know where is the setting for this?

答: In some way I feel NetBeans is just doing it right - Eclipse seems to mimic a "poor man's version control". But there are tons of free VCS, so why bother?

ContentLicense: CC BY-SA 2.5

Body:
I would like to ask is there any way change the comment code template in Netbeans PHP 6.8

In eclipse, when I type /** ENTER , it would come out the comment template that I set in the setting, like this:

/**
* Apr 19, 2010 - Shiro
* Description
*
* @return unknown_type
*/
function test()
{

}

by Default Netbeans only will show the parameter in the function.

/**
  *
  * @param <type> $order_No
  * @param <type> $array
  */

in Netbeans is there any possible I could found any customization about this, anyone know where is the setting for this?


问:
Java netty client cannot send message to server, but telnet to sever ok
I'm just learning Java Netty to make very simple client-server via socket 7000. Server is running and it will echo the message received from client. It works if I use telnet localhost 7000 and send message to server and receive the echo message.

However, with a Java Netty client, it doesn't work. Server receives nothing, client sends nothing? as I tried to add some writing to console.

Here is the classes of this example:

Client

```<code>public final class EchoClient {

    public static void main(String[] args) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    new LoggingHandler(LogLevel.TRACE),
                                    new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Delimiters.lineDelimiter()),
                                    new StringEncoder(),
                                    new StringDecoder(),
                                    new EchoClientHandler());
                        }
                    });

            // Start the connection attempt.
            bootstrap.connect("localhost", 7000).sync().channel().closeFuture().sync();
            System.out.println("Message sent successfully.");
        } finally {
            group.shutdownGracefully();
        }
    }
}

public class EchoClientHandler extends SimpleChannelInboundHandler<String> {

    /**
     * Constructor for the class
     *
     * @param message the message you want to transmit
     */
    public EchoClientHandler() {

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String message = "message from client.";
        System.out.println("Sending message: " + message);
        ctx.write(message);
        ctx.flush();
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        System.out.println("Error caught in the communication service: " + cause);
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println("Received message: " + msg);
    }
}
</code>```

Server

```<code>    public final class EchoServer {

    static final boolean SSL = System.getProperty("ssl") != null;
    static final int PORT = Integer.parseInt(System.getProperty("port", "7000"));

    public static void main(String[] args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.TRACE))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    new LoggingHandler(LogLevel.TRACE),
                                    new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Delimiters.lineDelimiter()),
                                    new StringEncoder(),
                                    new StringDecoder(),
                                    new EchoServerHandler());
                        }
                    });

            System.out.println("Server is listening on port 7000.");

            // Start the server.
            ChannelFuture channelFuture = serverBootstrap.bind("localhost", 7000).sync();

            // Wait until the server socket is closed.
            channelFuture.channel().closeFuture().sync();

        } finally {
            // Shut down all event loops to terminate all threads.
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

public class EchoServerHandler extends SimpleChannelInboundHandler<String> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String message = "message from server.";
        System.out.println("Sending message: " + message);
        ctx.write(message);
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        System.out.println("Error in receiving message.");
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String message) throws Exception {
        System.out.println("Received message: " + message);
        ctx.write(message);
        ctx.flush();
        //ctx.close();
    }
}
</code>```

So when I run EchoServer, then I run EchoClient, the output from EchoClient is

```<code>Sending message: message from client.
Message sent successfully.
Then application stopped.
</code>```

And the output from EchoServer is

```<code>Sending message: message from server.
</code>```

答:
In your code, the DelimiterBasedFrameDecoder handler is coming before decoder/encoder. Hence, if the transferred message is without expected delimiter (e.g. new line in this case), both client/server will continue waiting and think that message is still transferring. Hence, there are two possible ways to fix your issue.

Remove new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Delimiters.lineDelimiter()) in both Client and Server

Every time you send message over the channel, please add new line separator. Otherwise, the message can't be decoded from other end. Please find below the sample code

EchoClientHandler class

```<code>public class EchoClientHandler extends SimpleChannelInboundHandler<String> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String message = "message from client.";
        System.out.println("Sending message: " + message);
        ctx.writeAndFlush(message + System.lineSeparator());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        System.out.println("Error caught in the communication service: " + cause);
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println("Received message: " + msg);
    }
}
</code>```

EchoServerHandler class

```<code>  public class EchoServerHandler extends SimpleChannelInboundHandler<String> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String message = "message from server.";
        System.out.println("Sending message: " + message);
        ctx.writeAndFlush(message + System.lineSeparator());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        System.out.println("Error in receiving message.");
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String message) throws Exception {
        System.out.println("Received message: " + message);
        ctx.writeAndFlush(message + System.lineSeparator());
    }
}
</code>```

Output from Server

```<code>Server is listening on port 7000.
Sending message: message from server.
Received message: message from client.
</code>```

Output from Client

```<code>Sending message: message from client.
Received message: message from server.
Received message: message from client.
</code>```

Body:
I'm just learning Java Netty to make very simple client-server via socket 7000. Server is running and it will echo the message received from client. It works if I use telnet localhost 7000 and send message to server and receive the echo message.

However, with a Java Netty client, it doesn't work. Server receives nothing, client sends nothing? as I tried to add some writing to console.

Here is the classes of this example:

Client

public final class EchoClient {

    public static void main(String[] args) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    new LoggingHandler(LogLevel.TRACE),
                                    new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Delimiters.lineDelimiter()),
                                    new StringEncoder(),
                                    new StringDecoder(),
                                    new EchoClientHandler());
                        }
                    });

            // Start the connection attempt.
            bootstrap.connect("localhost", 7000).sync().channel().closeFuture().sync();
            System.out.println("Message sent successfully.");
        } finally {
            group.shutdownGracefully();
        }
    }
}

public class EchoClientHandler extends SimpleChannelInboundHandler<String> {

    /**
     * Constructor for the class
     *
     * @param message the message you want to transmit
     */
    public EchoClientHandler() {

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String message = "message from client.";
        System.out.println("Sending message: " + message);
        ctx.write(message);
        ctx.flush();
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        System.out.println("Error caught in the communication service: " + cause);
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println("Received message: " + msg);
    }
}

Server

    public final class EchoServer {

    static final boolean SSL = System.getProperty("ssl") != null;
    static final int PORT = Integer.parseInt(System.getProperty("port", "7000"));

    public static void main(String[] args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.TRACE))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    new LoggingHandler(LogLevel.TRACE),
                                    new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Delimiters.lineDelimiter()),
                                    new StringEncoder(),
                                    new StringDecoder(),
                                    new EchoServerHandler());
                        }
                    });

            System.out.println("Server is listening on port 7000.");

            // Start the server.
            ChannelFuture channelFuture = serverBootstrap.bind("localhost", 7000).sync();

            // Wait until the server socket is closed.
            channelFuture.channel().closeFuture().sync();

        } finally {
            // Shut down all event loops to terminate all threads.
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

public class EchoServerHandler extends SimpleChannelInboundHandler<String> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String message = "message from server.";
        System.out.println("Sending message: " + message);
        ctx.write(message);
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        System.out.println("Error in receiving message.");
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String message) throws Exception {
        System.out.println("Received message: " + message);
        ctx.write(message);
        ctx.flush();
        //ctx.close();
    }
}

So when I run EchoServer, then I run EchoClient, the output from EchoClient is

Sending message: message from client.
Message sent successfully.
Then application stopped.

And the output from EchoServer is

Sending message: message from server.

Body:
In your code, the DelimiterBasedFrameDecoder handler is coming before decoder/encoder. Hence, if the transferred message is without expected delimiter (e.g. new line in this case), both client/server will continue waiting and think that message is still transferring. Hence, there are two possible ways to fix your issue.

Remove new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Delimiters.lineDelimiter()) in both Client and Server

Every time you send message over the channel, please add new line separator. Otherwise, the message can't be decoded from other end. Please find below the sample code

EchoClientHandler class

public class EchoClientHandler extends SimpleChannelInboundHandler<String> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String message = "message from client.";
        System.out.println("Sending message: " + message);
        ctx.writeAndFlush(message + System.lineSeparator());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        System.out.println("Error caught in the communication service: " + cause);
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println("Received message: " + msg);
    }
}

EchoServerHandler class

  public class EchoServerHandler extends SimpleChannelInboundHandler<String> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String message = "message from server.";
        System.out.println("Sending message: " + message);
        ctx.writeAndFlush(message + System.lineSeparator());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        System.out.println("Error in receiving message.");
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String message) throws Exception {
        System.out.println("Received message: " + message);
        ctx.writeAndFlush(message + System.lineSeparator());
    }
}

Output from Server

Server is listening on port 7000.
Sending message: message from server.
Received message: message from client.

Output from Client

Sending message: message from client.
Received message: message from server.
Received message: message from client.


问:
Need help in serialization
Been spending my last two hours trying to learn how to serialize my data i need a code that serializes my data in "StatContainer" i tried this :

https://gamedevelopment.tutsplus.com/tutorials/how-to-save-and-load-your-players-progress-in-unity--cms-20934

and alot more but i wasnt able to understand how to serialize my data

```<code>using UnityEngine;
using System.Collections;

public class Stats : MonoBehaviour
{
    StatContainer stats = new StatContainer();

    // Use this for initialization
    void Start () {
        InvokeRepeating ("AddCoins", 4.0f, 2.0f);
        InvokeRepeating ("AddScore", 1.5f, 1.5f);
    }

    // Update is called once per frame
    void Update () {
        this.stats.Update();
    }

    void AddCoins (){
        if (BunnyScript.BunnyAlive == true) {
            StatContainer.coins += 1;
        }
    }

    void AddScore (){
        if (BunnyScript.BunnyAlive == true) {
            StatContainer.score += 1;
        }
    }
    }
    [System.Serializable]
    public class StatContainer
    {
    public static int coins = 0;
    public static int totalcoins = 0;
    public static int score = 0;

    public static int personalbest = 0;
    public static float UmbrellaSpeed = 0.1f;
    public static float currentumbdur = 500;

    public static int CarrotSpawnRateLVL = 1;
    public static float CarrotSpawnRate = 60f;
    public static int CarrotSpawnRateUpgradeCost = 15;

    public static int UmbrellaDurabilityLVL = 1;
    public static float UmbrellaDurability = 500;
    public static int UmbrellaDurabilityUpgradeCost = 30;

    public static int UmbrellaSizeLVL = 1;
    public static float UmbrellaSize = 0f;
    public static int UmbrellaSizeUpgradeCost = 25;

    public static int CarrotEffectLVL = 1;
    public static float CarrotEffect = 20;
    public static int CarrotEffectUpgradeCost = 25;

    public static int HealthRegenLVL = 1;
    public static float HealthRegenTime = 4f;
    public static int HealthRegenCost = 100;

    public static int BuyTreesCost = 250;

    public static int Tree1Bought = 0;
    public static float Tree1Size = 0;
    public static int Tree1SizeLVL = 1;
    public static int Tree1SizeUpgradeCost = 50;

    public static int Tree2Bought = 0;
    public static float Tree2Size = 0;
    public static int Tree2SizeLVL = 1;
    public static int Tree2SizeUpgradeCost = 50;

    public static int Tree3Bought = 0;
    public static float Tree3Size =0;
    public static int Tree3SizeLVL = 1;
    public static int Tree3SizeUpgradeCost = 50;
    // and the rest

    public void Update(){
        if (score > personalbest) {
            personalbest = score;
        }
    }
}
</code>```

this is how i try to serialize it

```<code>using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

public static class SaveLoad {
    public static List<StatContainer> savedGames = new List<StatContainer>();

    //it's static so we can call it from anywhere
    public static void Save() {
        SaveLoad.savedGames.Add(StatContainer.current);
        BinaryFormatter bf = new BinaryFormatter();
        //Application.persistentDataPath is a string, so if you wanted you can put that into debug.log if you want to know where save games are located
        FileStream file = File.Create (Application.persistentDataPath + "/savedGames.gd"); //you can call it anything you want
        bf.Serialize(file, SaveLoad.savedGames);
        file.Close();
    }

    public static void Load() {
        if(File.Exists(Application.persistentDataPath + "/savedGames.gd")) {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Open(Application.persistentDataPath + "/savedGames.gd", FileMode.Open);
            SaveLoad.savedGames = (List<StatContainer>)bf.Deserialize(file);
            file.Close();
        }
    }
}
</code>```

i am calling the load fuction in the beggining of the game and the save using invoke repeating every 2 sec

答:
First remove static members in StatContainer

To access your data make Load function return StatContainer and in your class Stats you can put StatContainer in static or create a singleton of Stats.

Second I don't know your purpose but perhaps you can take a look to xml serialization instead of BinaryFormat, to have a file who is readable by human and so you can change easely the data.
 In that case I sugest to you, to take a look to Xml tags like below.

(And you can encrypt your xml when you release your game)

```<code>[System.Serializable]
[XmlRoot(ElementName = "stats-of-something")]
public class StatContainer
{
     [XmlAttribute(AttributeName = "coins")]
     public int coins = 0;
     [XmlElement(ElementName = "umbrella-speed")]
     public float UmbrellaSpeed = 0.1f;
}
</code>```

or

```<code>[System.Serializable]
[XmlRoot(ElementName = "stats-of-something")]
public class StatContainer
{
     [XmlAttribute(AttributeName = "coins")]
     private int _coins = 0;
     [XmlElement(ElementName = "umbrella-speed")]
     private float _umbrellaSpeed = 0.1f;

     public int coins { get { return _coins; } set { _coins = value; } }
     public float umbrellaSpeed  { get { return _umbrellaSpeed ; } set { _umbrellaSpeed = value; } }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Need help in serialization

Body:
Been spending my last two hours trying to learn how to serialize my data i need a code that serializes my data in "StatContainer" i tried this :

https://gamedevelopment.tutsplus.com/tutorials/how-to-save-and-load-your-players-progress-in-unity--cms-20934

and alot more but i wasnt able to understand how to serialize my data

using UnityEngine;
using System.Collections;

public class Stats : MonoBehaviour
{
    StatContainer stats = new StatContainer();

    // Use this for initialization
    void Start () {
        InvokeRepeating ("AddCoins", 4.0f, 2.0f);
        InvokeRepeating ("AddScore", 1.5f, 1.5f);
    }

    // Update is called once per frame
    void Update () {
        this.stats.Update();
    }

    void AddCoins (){
        if (BunnyScript.BunnyAlive == true) {
            StatContainer.coins += 1;
        }
    }

    void AddScore (){
        if (BunnyScript.BunnyAlive == true) {
            StatContainer.score += 1;
        }
    }
    }
    [System.Serializable]
    public class StatContainer
    {
    public static int coins = 0;
    public static int totalcoins = 0;
    public static int score = 0;

    public static int personalbest = 0;
    public static float UmbrellaSpeed = 0.1f;
    public static float currentumbdur = 500;

    public static int CarrotSpawnRateLVL = 1;
    public static float CarrotSpawnRate = 60f;
    public static int CarrotSpawnRateUpgradeCost = 15;

    public static int UmbrellaDurabilityLVL = 1;
    public static float UmbrellaDurability = 500;
    public static int UmbrellaDurabilityUpgradeCost = 30;

    public static int UmbrellaSizeLVL = 1;
    public static float UmbrellaSize = 0f;
    public static int UmbrellaSizeUpgradeCost = 25;

    public static int CarrotEffectLVL = 1;
    public static float CarrotEffect = 20;
    public static int CarrotEffectUpgradeCost = 25;

    public static int HealthRegenLVL = 1;
    public static float HealthRegenTime = 4f;
    public static int HealthRegenCost = 100;

    public static int BuyTreesCost = 250;

    public static int Tree1Bought = 0;
    public static float Tree1Size = 0;
    public static int Tree1SizeLVL = 1;
    public static int Tree1SizeUpgradeCost = 50;

    public static int Tree2Bought = 0;
    public static float Tree2Size = 0;
    public static int Tree2SizeLVL = 1;
    public static int Tree2SizeUpgradeCost = 50;

    public static int Tree3Bought = 0;
    public static float Tree3Size =0;
    public static int Tree3SizeLVL = 1;
    public static int Tree3SizeUpgradeCost = 50;
    // and the rest

    public void Update(){
        if (score > personalbest) {
            personalbest = score;
        }
    }
}

this is how i try to serialize it

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

public static class SaveLoad {
    public static List<StatContainer> savedGames = new List<StatContainer>();

    //it's static so we can call it from anywhere
    public static void Save() {
        SaveLoad.savedGames.Add(StatContainer.current);
        BinaryFormatter bf = new BinaryFormatter();
        //Application.persistentDataPath is a string, so if you wanted you can put that into debug.log if you want to know where save games are located
        FileStream file = File.Create (Application.persistentDataPath + "/savedGames.gd"); //you can call it anything you want
        bf.Serialize(file, SaveLoad.savedGames);
        file.Close();
    }

    public static void Load() {
        if(File.Exists(Application.persistentDataPath + "/savedGames.gd")) {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Open(Application.persistentDataPath + "/savedGames.gd", FileMode.Open);
            SaveLoad.savedGames = (List<StatContainer>)bf.Deserialize(file);
            file.Close();
        }
    }
}

i am calling the load fuction in the beggining of the game and the save using invoke repeating every 2 sec

Body:
First remove static members in StatContainer

To access your data make Load function return StatContainer and in your class Stats you can put StatContainer in static or create a singleton of Stats.

Second I don't know your purpose but perhaps you can take a look to xml serialization instead of BinaryFormat, to have a file who is readable by human and so you can change easely the data.
 In that case I sugest to you, to take a look to Xml tags like below.

(And you can encrypt your xml when you release your game)

[System.Serializable]
[XmlRoot(ElementName = "stats-of-something")]
public class StatContainer
{
     [XmlAttribute(AttributeName = "coins")]
     public int coins = 0;
     [XmlElement(ElementName = "umbrella-speed")]
     public float UmbrellaSpeed = 0.1f;
}

or

[System.Serializable]
[XmlRoot(ElementName = "stats-of-something")]
public class StatContainer
{
     [XmlAttribute(AttributeName = "coins")]
     private int _coins = 0;
     [XmlElement(ElementName = "umbrella-speed")]
     private float _umbrellaSpeed = 0.1f;

     public int coins { get { return _coins; } set { _coins = value; } }
     public float umbrellaSpeed  { get { return _umbrellaSpeed ; } set { _umbrellaSpeed = value; } }
}


问:
jquery function unexpected token error
So I am trying to write a reusable function in jquery for a style guide I'm creating.  The goal of the function is to hide/show a number of divs based on the value of a range slider.

The html code looks like this

```<code><div class="primary-colors">
    <h3>Primary Colors</h3>
    <div class="primary-range-container">
        <input type="range" min="1" max="15" value ="5" class="primary-slider"><span class="value">0</span>
    </div>
    <hr>
    <div class="color-container">
        <div class="color primary-color-1"></div>
        <div class="color primary-color-2"></div>
        <div class="color primary-color-3"></div>
        <div class="color primary-color-4"></div>
        <div class="color primary-color-5"></div>
        <div class="color primary-color-6"></div>
        <div class="color primary-color-7"></div>
        <div class="color primary-color-8"></div>
        <div class="color primary-color-9"></div>
        <div class="color primary-color-10"></div>
        <div class="color primary-color-11"></div>
    </div>
</div>
</code>```

And the javascript code looks like this

```<code>var primarySlider = $(".primary-slider");
var primaryColorContainer = $(".primary-colors .color");
var primaryValue = $('.primary-range-container .value');

$.fn.colorBlocks(colorContainer, rangeSlider) {
    this.change(function() {
        var number = $(rangeSlider).val();
        $(colorContainer).hide();
        $(colorContainer).hide().slice( 0, number ).show();
    }
    this.change();
}

primarySlider.colorBlocks(primaryColorContainer, primaryValue);
</code>```

The expected result in my head would be that the function would work, but so far I'm just not seeing anything and instead the compiler is giving me Parsing error: Unexpected Token {.

Any advice or better methods would be incredibly helpful.

答:
You have a couple issues with your syntax.

Where you define your prototype:

```<code>$.fn.colorBlocks(colorContainer, rangeSlider) {
</code>```

Should be:

```<code>$.fn.colorBlocks = function(colorContainer, rangeSlider) {
</code>```

And you're missing a closing parenthesis that is opened in the change listener:

```<code>this.change(function() {
...
};
</code>```

Should be:

```<code>this.change(function() {
...
});
</code>```

The error is coming from the fact that it is reaching the opening curly brace before it is expcted due to the incorrect syntax when defining the prototype.

Fixed example:

var primarySlider = $(".primary-slider");
var primaryColorContainer = $(".primary-colors .color");
var primaryValue = $('.primary-range-container .value');

$.fn.colorBlocks = function(colorContainer, rangeSlider, primaryValue) {
  this.change(function() {
    var number = $(rangeSlider).val();
    $(primaryValue).text(number);
    $(colorContainer).hide();
    $(colorContainer).hide().slice( 0, number ).show();
  });
  this.change();
}

primarySlider.colorBlocks(primaryColorContainer, primarySlider, primaryValue);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.color {
  width: 40px;
  height: 40px;
  min-width: 40px;
  min-height: 40px;
  background: red;
  margin: 1px;
}</code>```

Primary Colors

  <input type="range" min="1" max="15" value ="5" class="primary-slider">
  5

```

Title: jquery function unexpected token error

Body:
So I am trying to write a reusable function in jquery for a style guide I'm creating.  The goal of the function is to hide/show a number of divs based on the value of a range slider.

The html code looks like this

Primary Colors

        <input type="range" min="1" max="15" value ="5" class="primary-slider">0

And the javascript code looks like this

var primarySlider = $(".primary-slider");
var primaryColorContainer = $(".primary-colors .color");
var primaryValue = $('.primary-range-container .value');

$.fn.colorBlocks(colorContainer, rangeSlider) {
    this.change(function() {
        var number = $(rangeSlider).val();
        $(colorContainer).hide();
        $(colorContainer).hide().slice( 0, number ).show();
    }
    this.change();
}

primarySlider.colorBlocks(primaryColorContainer, primaryValue);

The expected result in my head would be that the function would work, but so far I'm just not seeing anything and instead the compiler is giving me Parsing error: Unexpected Token {.

Any advice or better methods would be incredibly helpful.

Body:
You have a couple issues with your syntax.

Where you define your prototype:

$.fn.colorBlocks(colorContainer, rangeSlider) {

Should be:

$.fn.colorBlocks = function(colorContainer, rangeSlider) {

And you're missing a closing parenthesis that is opened in the change listener:

this.change(function() {
...
};

Should be:

this.change(function() {
...
});

The error is coming from the fact that it is reaching the opening curly brace before it is expcted due to the incorrect syntax when defining the prototype.

Fixed example:

var primarySlider = $(".primary-slider");
var primaryColorContainer = $(".primary-colors .color");
var primaryValue = $('.primary-range-container .value');

$.fn.colorBlocks = function(colorContainer, rangeSlider, primaryValue) {
  this.change(function() {
    var number = $(rangeSlider).val();
    $(primaryValue).text(number);
    $(colorContainer).hide();
    $(colorContainer).hide().slice( 0, number ).show();
  });
  this.change();
}

primarySlider.colorBlocks(primaryColorContainer, primarySlider, primaryValue);

div.color {
  width: 40px;
  height: 40px;
  min-width: 40px;
  min-height: 40px;
  background: red;
  margin: 1px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="primary-colors">
 <h3>Primary Colors</h3>
 <div class="primary-range-container">
  <input type="range" min="1" max="15" value ="5" class="primary-slider">
  <span class="value">5</span>
 </div>
 <hr>
 <div class="color-container">
  <div class="color primary-color-1"></div>
  <div class="color primary-color-2"></div>
  <div class="color primary-color-3"></div>
  <div class="color primary-color-4"></div>
  <div class="color primary-color-5"></div>
  <div class="color primary-color-6"></div>
  <div class="color primary-color-7"></div>
  <div class="color primary-color-8"></div>
  <div class="color primary-color-9"></div>
  <div class="color primary-color-10"></div>
  <div class="color primary-color-11"></div>
 </div>
</div>


问:
How to delete single (many-) rows from one-to-many relations in Laravel 5.5
I got two models in Laravel: Label

```<code>class Label extends \Eloquent
{
    protected $fillable = [
        'channel_id',
        'name',
        'color',
    ];

    public function channel()
    {
        return $this->belongsTo('App\Channel');
    }
}
</code>```

And Channel

```<code>class Channel extends \Eloquent
{
    protected $fillable = [
        'name',
    ];

    public function labels()
    {
        return $this->hasMany('App\Label');
    }

}
</code>```

Now when a label is deleted, I want to make sure, the label belongs to the channel.

This works pretty good, as it even is atomic, so the row will just be deleted, if the label really belongs to the channel.

LabelController:

```<code>/**
 * Remove the specified resource from storage.
 *
 * @param  int $id
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    $channel = $this->getChannel();

    Label::where('id', $id)
        ->where('channel_id', $channel->id)
        ->delete();

    return back();
}
</code>```

And my question is now: How to build that with Eloquent, so it is elegant? Something like:

```<code>    $channel->labels()->destroy($id);
</code>```

But there is no destroy function on the relation.

Update:

I managed to achieve something in the right direction:

```<code>$channel->labels()->find($id)->delete();
</code>```

This deletes the label with $id BUT just if the label has the right channel_id assigned. If not, I get the following error, which I could catch and handle:

```<code>FatalThrowableError (E_ERROR) Call to a member function delete() on null
</code>```

Still, as Apache is threaded, there could be the case that another thread changes the channel_id after I read it. So the only way besides my query is to run a transaction?

答:
You mentioned that, you first want to check if a label has a channel. If so, then it should be deleted.

You can try something like this though:

```<code>$label = Label::find($id);
if ($label->has('channel')) {
    $label->delete();
}
</code>```

Body:
I got two models in Laravel: Label

class Label extends \Eloquent
{
    protected $fillable = [
        'channel_id',
        'name',
        'color',
    ];

    public function channel()
    {
        return $this->belongsTo('App\Channel');
    }
}

And Channel

class Channel extends \Eloquent
{
    protected $fillable = [
        'name',
    ];

    public function labels()
    {
        return $this->hasMany('App\Label');
    }

}

Now when a label is deleted, I want to make sure, the label belongs to the channel.

This works pretty good, as it even is atomic, so the row will just be deleted, if the label really belongs to the channel.

LabelController:

/**
 * Remove the specified resource from storage.
 *
 * @param  int $id
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    $channel = $this->getChannel();

    Label::where('id', $id)
        ->where('channel_id', $channel->id)
        ->delete();

    return back();
}

And my question is now: How to build that with Eloquent, so it is elegant? Something like:

    $channel->labels()->destroy($id);

But there is no destroy function on the relation.

Update:

I managed to achieve something in the right direction:

$channel->labels()->find($id)->delete();

This deletes the label with $id BUT just if the label has the right channel_id assigned. If not, I get the following error, which I could catch and handle:

FatalThrowableError (E_ERROR) Call to a member function delete() on null

Still, as Apache is threaded, there could be the case that another thread changes the channel_id after I read it. So the only way besides my query is to run a transaction?

Body:
You mentioned that, you first want to check if a label has a channel. If so, then it should be deleted.

You can try something like this though:

$label = Label::find($id);
if ($label->has('channel')) {
    $label->delete();
}


问:
How to send data from a C# MVC ASP.net Application to a C# WPF Application
I am wondering how I can send information from a C# MVC Web Application to a C# Desktop Application.

For example, I want to be able to send some strings from my web application that is hosted on some server to a client's personal computer where they will have my desktop application executable somewhere on their local machine. Also, I am trying to avoid the client having to open the desktop application (that will be running in the background) to click anything. I am wanting the desktop application to constantly be checking for data coming in from the web application. I would probably have a while() loop checking for that information in the desktop application and then once it has received data from the web application I will do stuff with it on the desktop side.

Can anyone point me to some good examples of this or provide a simple example of this being done with some strings?

答:
When thinking about this SignalR comes to mind, or perhaps implement in the MVC application a web hook and consume it in the WPF application.

A good starting point for Signalr you can find here.


问:
How can i make a the text bold which is stored in a string variable?
I want to make the text stored inside a string variable to bold.

String buttonText = t.getText().toString();
                String val = map.get(buttonText);

```<code>          new MaterialDialog.Builder(LearningMode.this)
                    .iconRes(BalloonColor.get(2))
                    .limitIconToDefaultSize()
                    .title("Meaning")

                    .content(buttonText+"\n"+val)

                    .positiveText("Continue")
                    .cancelable(false)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            mover.resume();
                        }
                    })

                    .show();
</code>```

at .content(buttonText+"\n"+val)
i want the string stored inside this to become bold.
i have tried html.fromhtml it is not working

like this Html.fromHtml("  "+buttonText+" ")

added space in the above  as it is converting to bold

and other methods like declaring in strings.xml with  wont work here as i'm dealing it programmatically here!

ultimately when the string button text is displayed in the output sholud be bold.

i have already referred this Set TextView text from html-formatted string resource in XML

Update:

There is no textview used.

Someone please help!

答:
You may use  SpannableString for it. say you ave a TextView called txt then the code is:

```<code> SpannableStringBuilder sb = new SpannableStringBuilder("HELLOO");
 StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD);

 sb.setSpan(bss, 0, sb.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);

 txt.setText(sb);
</code>```

Updated

As I seen in material dialog library it has bug for that so try below code

```<code>@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

        return new MaterialDialog.Builder(getActivity())
                .title(R.string.about)
                .positiveText(R.string.dismiss)
                .content(fromHtml(getString(R.string.about_body)))
                .contentLineSpacing(1.6f)
                .build();

    }
@SuppressWarnings("deprecation")
public static Spanned fromHtml(String html){
    Spanned result;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
        result = Html.fromHtml(html,Html.FROM_HTML_MODE_LEGACY);
    } else {
        result = Html.fromHtml(html);
    }
    return result;
}
}
</code>```

for more https://github.com/afollestad/material-dialogs/issues/1290

Body:
I want to make the text stored inside a string variable to bold.

String buttonText = t.getText().toString();
                String val = map.get(buttonText);

          new MaterialDialog.Builder(LearningMode.this)
                    .iconRes(BalloonColor.get(2))
                    .limitIconToDefaultSize()
                    .title("Meaning")

                    .content(buttonText+"\n"+val)

                    .positiveText("Continue")
                    .cancelable(false)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            mover.resume();
                        }
                    })

                    .show();

at .content(buttonText+"\n"+val)
i want the string stored inside this to become bold.
i have tried html.fromhtml it is not working

like this Html.fromHtml("  "+buttonText+" ")

added space in the above  as it is converting to bold

and other methods like declaring in strings.xml with  wont work here as i'm dealing it programmatically here!

ultimately when the string button text is displayed in the output sholud be bold.

i have already referred this Set TextView text from html-formatted string resource in XML

Update:

There is no textview used.

Someone please help!

Body:
You may use  SpannableString for it. say you ave a TextView called txt then the code is:

 SpannableStringBuilder sb = new SpannableStringBuilder("HELLOO");
 StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD);

 sb.setSpan(bss, 0, sb.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);

 txt.setText(sb);

Updated

As I seen in material dialog library it has bug for that so try below code

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

        return new MaterialDialog.Builder(getActivity())
                .title(R.string.about)
                .positiveText(R.string.dismiss)
                .content(fromHtml(getString(R.string.about_body)))
                .contentLineSpacing(1.6f)
                .build();

    }
@SuppressWarnings("deprecation")
public static Spanned fromHtml(String html){
    Spanned result;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
        result = Html.fromHtml(html,Html.FROM_HTML_MODE_LEGACY);
    } else {
        result = Html.fromHtml(html);
    }
    return result;
}
}

for more https://github.com/afollestad/material-dialogs/issues/1290


问:
Insert multiple rows for each of a result set?
my google-fu is failing me.
I'm trying to do the following in a more automatic way:

1) select a set of fields from 1 table

```<code>select ACCT_ID from MASTER_ACCT where CUST_NBR like '%ABC';
</code>```

2) use the results of that in a multiple row insert

```<code>// for each ACCT_ID in (1)
insert into TOGGLES (FIELD1, FIELD2, FIELD3)
values('abc', '123', ACCT_ID[i]);
</code>```

Is there a way to execute the 2nd statement for ACCT_ID[i] in each of the ACCT_ID results from the 1st statement?

答:
You might use the below syntax

INSERT INTO target_table[()] SELECT ... FROM ...;

find this link for more details.

Body:
my google-fu is failing me.
I'm trying to do the following in a more automatic way:

1) select a set of fields from 1 table

select ACCT_ID from MASTER_ACCT where CUST_NBR like '%ABC';

2) use the results of that in a multiple row insert

// for each ACCT_ID in (1)
insert into TOGGLES (FIELD1, FIELD2, FIELD3)
values('abc', '123', ACCT_ID[i]);

Is there a way to execute the 2nd statement for ACCT_ID[i] in each of the ACCT_ID results from the 1st statement?


问:
Django testing form with modelchoicefield
I amended a form to make a ModelChoiceField so that users can only select categories that they have set up.  This is working correctly when I run my app in the browser but fails the test (in that it says the form is not valid), which passes if you remove the ModelChoiceField and allow it to display all categories from the model.

I am happy that the code for the form works as expected and required in the browser; it is the test case that I would like to fix.  I imagine there is something obvious I can't see, because I have looked at it too many times.

Extract from test case

```<code>def setUp(self):
    user = User.objects.create(username='user', password='')
    self.category = Category.objects.create(id=1, user=user, title='category1')
    self.myitem = MyModel.objects.create(id=1, user=user, title='title1', amount=10, category=self.category)

def test_form_validation_with_valid_data(self):
    user = User.objects.get(username='user')
    now = timezone.now()
    form = MyModelForm({'title': 'title1', 'category': 1,  'amount': 100, 'date': now,}, user)
    self.assertTrue(form.is_valid())
</code>```

Extract from forms.py

```<code>class MyModelForm(forms.ModelForm):

    class Meta:
        model = MyModel
        fields = ('title', 'category', 'amount', 'date',)

    category = forms.ModelChoiceField(queryset=None)

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super(MyModelForm, self).__init__(*args, **kwargs)
        self.fields['category'].queryset = Category.objects.filter(user=self.user)
</code>```

答:
You need to pass user as a kwarg:

```<code>form = MyModelForm({'title': 'title1', 'category': 1,  'amount': 100, 'date': now,}, user=user)
</code>```

Body:
I amended a form to make a ModelChoiceField so that users can only select categories that they have set up.  This is working correctly when I run my app in the browser but fails the test (in that it says the form is not valid), which passes if you remove the ModelChoiceField and allow it to display all categories from the model.

I am happy that the code for the form works as expected and required in the browser; it is the test case that I would like to fix.  I imagine there is something obvious I can't see, because I have looked at it too many times.

Extract from test case

def setUp(self):
    user = User.objects.create(username='user', password='')
    self.category = Category.objects.create(id=1, user=user, title='category1')
    self.myitem = MyModel.objects.create(id=1, user=user, title='title1', amount=10, category=self.category)

def test_form_validation_with_valid_data(self):
    user = User.objects.get(username='user')
    now = timezone.now()
    form = MyModelForm({'title': 'title1', 'category': 1,  'amount': 100, 'date': now,}, user)
    self.assertTrue(form.is_valid())

Extract from forms.py

class MyModelForm(forms.ModelForm):

    class Meta:
        model = MyModel
        fields = ('title', 'category', 'amount', 'date',)

    category = forms.ModelChoiceField(queryset=None)

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super(MyModelForm, self).__init__(*args, **kwargs)
        self.fields['category'].queryset = Category.objects.filter(user=self.user)

Body:
You need to pass user as a kwarg:

form = MyModelForm({'title': 'title1', 'category': 1,  'amount': 100, 'date': now,}, user=user)


问:
Delphi - TCameraComponent auto focus
I'm trying to use auto focus in TCameraComponent with this code :

```<code>CameraComponent.FocusMode := TFocusMode.ContinuousAutoFocus;
</code>```

but I get the following error :  delphi java.lang.runtimeexception: setparameters failed.
How can I use autofocus. I'm in Delphi XE10 Seattle.
Thank you for your help.

答:
It's not FMX that's the issue. It's the capability of the device.

I have used the above code successfully on a samsung galaxy tab running android 7. I have also had the above error when running on an older device.

Title: Delphi - TCameraComponent auto focus

Body:
I'm trying to use auto focus in TCameraComponent with this code :

CameraComponent.FocusMode := TFocusMode.ContinuousAutoFocus;

but I get the following error :  delphi java.lang.runtimeexception: setparameters failed.
How can I use autofocus. I'm in Delphi XE10 Seattle.
Thank you for your help.


问:
How to remove the alerts 'trackingBackend' and 'markersAreaEnabled' with AR.js?
On my AR.JS example https://github.com/ybinstock/aframe_ar (github) https://ybinstock.github.io/aframe_ar (live site), I'm getting these two boxes seen in the attached image.

Here's my aframe scene

```<code><a-scene embedded arjs>

  <a-assets>
    <a-asset-item id="drone" src="busterDrone/busterDrone.gltf"></a-asset-item>
    <a-asset-item id="helmet" src="damagedHelmet/damagedHelmet.gltf"></a-asset-item>
    <a-asset-item id="skull" src="skull_downloadable/scene.gltf"></a-asset-item>
  </a-assets>

    <a-marker-camera preset='hiro'>

      <a-entity gltf-model-next="#drone"></a-entity>

    </a-marker-camera>

</a-scene>
</code>```

答:
You can turn off the debugging junk with configuration options. It isn't documented (which is very frustrating), but I found it when looking at examples of other AR.js projects. You need to add 'debugUIEnabled: false' into the arjs attribute on the  element. Here's an example:

```<code><a-scene embedded arjs='sourceType: webcam; debugUIEnabled: false;'>
  ... your a-frame markup ...
</a-scene>
</code>```

FYI, you don't need the embedded attribute, nor do you need the sourceType: webcam. A basic a-frame scene that only disables debugging would look like this:

```<code><a-scene arjs="debugUIEnabled: false;">
  ... your a-frame markup ...
</a-scene>
</code>```

The AR.js Readme that lists the properties you can use in the arjs attribute is here: https://github.com/jeromeetienne/AR.js/tree/master/aframe

This documentation fails to mention exactly how you use these configuration options. Huge oversight. But the answer is you put them in the arjs attribute on the  tag.

I know you can just hide the debugging stuff with CSS but this is truly the correct way of hiding it. I hope that helps!

Body:
You can turn off the debugging junk with configuration options. It isn't documented (which is very frustrating), but I found it when looking at examples of other AR.js projects. You need to add 'debugUIEnabled: false' into the arjs attribute on the <a-scene> element. Here's an example:

<a-scene embedded arjs='sourceType: webcam; debugUIEnabled: false;'>
  ... your a-frame markup ...
</a-scene>

FYI, you don't need the embedded attribute, nor do you need the sourceType: webcam. A basic a-frame scene that only disables debugging would look like this:

<a-scene arjs="debugUIEnabled: false;">
  ... your a-frame markup ...
</a-scene>

The AR.js Readme that lists the properties you can use in the arjs attribute is here: https://github.com/jeromeetienne/AR.js/tree/master/aframe

This documentation fails to mention exactly how you use these configuration options. Huge oversight. But the answer is you put them in the arjs attribute on the <a-scene> tag.

I know you can just hide the debugging stuff with CSS but this is truly the correct way of hiding it. I hope that helps!


问:
stream.exceptions.FeedConfigException error
My backend Django REST Framework prints this error.

stream.exceptions.FeedConfigException: The following feeds are not configured: 'user'.
      This could be the cause of a typo, but otherwise you should configure them on the dashboard of this app.

Here is my snippet of source code

```<code>class Post(models.Model, Activity):
    parent = models.ForeignKey("self", blank=True, null=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
    created_at = models.DateTimeField(auto_now=False, auto_now_add=True)
    ...

    @property
    def activity_actor_attr(self):
        return self.user
</code>```

I guess I need to create user feed in dashboard. But I don't understand why it's happening. user? feed? Should I put Activity to AUTH_USER_MODEL?? I don't have UserModel and I'm using the default UserModel.

:(

UPDATE I added user Feed and it solved the problem. And I don't see any row data.

I'm totally new in getStream() and need to learn it really fast.

答: I added user Feed group and it solved the problem.

Body:
My backend Django REST Framework prints this error.

stream.exceptions.FeedConfigException: The following feeds are not configured: 'user'.
      This could be the cause of a typo, but otherwise you should configure them on the dashboard of this app.

Here is my snippet of source code

class Post(models.Model, Activity):
    parent = models.ForeignKey("self", blank=True, null=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
    created_at = models.DateTimeField(auto_now=False, auto_now_add=True)
    ...

    @property
    def activity_actor_attr(self):
        return self.user

I guess I need to create user feed in dashboard. But I don't understand why it's happening. user? feed? Should I put Activity to AUTH_USER_MODEL?? I don't have UserModel and I'm using the default UserModel.

:(

UPDATE I added user Feed and it solved the problem. And I don't see any row data.

I'm totally new in getStream() and need to learn it really fast.


问:
Angular Material $mdDialog - Can't access 'this' items in confirm function
I'm trying to use the confirm function of an angular material $mdDialog to clear an array and then log this array to the console, but there seems to be an issue with accessing 'this' objects/arrays/expressions/functions within the $mdDialog function itself, with the console saying that whatever item references is undefined, even if used previously in other controller functions.

Does the $mdDialog directive have an issue with controllerAs syntax?

-

Controller:

```<code>app.controller('notificationsController', function($scope, $state, $http, $document, $mdDialog, $filter, $timeout) {

this.selectedNotification = null;
this.notifications = [
    {
        title: 'Notification One',
        description: 'Description...',
        time: '2017-10-27T16:39:32+00:00',
        importance: 'Low',
        read: false
    },

    etc...

$scope.clearNotifications = function(ev) {
    var confirm = $mdDialog.confirm()
        .parent(angular.element('body'))
        .clickOutsideToClose(true)
        .title('Are you sure you want to clear all notifications?')
        .textContent('This action cannot be undone.')
        .ariaLabel('Confirm notifications list clearance')
        .ok('Yes')
        .cancel('No')
        .targetEvent(ev)

    $mdDialog.show(confirm).then(function() {
        $scope.status = 'All notifications deleted';
        console.log($scope.status);
        this.notifications.length = 0;
        console.log(this.notifications);
    }, function() {
        $scope.status = 'Notifications list not cleared';
        console.log($scope.status);
    })
}
</code>```

答:
The this in:

```<code>$mdDialog.show(confirm).then(function() {
    ...
    this.notifications.length = 0; // <---- here
    ...
}, function() {
    ...
})
</code>```

refers to the promise resolve function of the promise returned by $mdDialog.show(), if you wanted to access the controller's notifications member you'd have to create a var that refers to the controller's this:

```<code>app.controller('notificationsController', function($scope, $state,
$http, $document, $mdDialog, $filter, $timeout) {

  var _this = this; // <--- Now _this is the controller
  this.notifications = [
  {
    title: 'Notification One',
    description: 'Description...',
    time: '2017-10-27T16:39:32+00:00',
    importance: 'Low',
    read: false
  },

etc...

$scope.clearNotifications = function(ev) {
  ...

  $mdDialog.show(confirm).then(function() {
    ...
    _this.notifications.length = 0; //<--- using _this and not this
    ...
  }, function() {
    ...
  })
}
</code>```

Body:
I'm trying to use the confirm function of an angular material $mdDialog to clear an array and then log this array to the console, but there seems to be an issue with accessing 'this' objects/arrays/expressions/functions within the $mdDialog function itself, with the console saying that whatever item references is undefined, even if used previously in other controller functions.

Does the $mdDialog directive have an issue with controllerAs syntax?

-

Controller:

app.controller('notificationsController', function($scope, $state, $http, $document, $mdDialog, $filter, $timeout) {

this.selectedNotification = null;
this.notifications = [
    {
        title: 'Notification One',
        description: 'Description...',
        time: '2017-10-27T16:39:32+00:00',
        importance: 'Low',
        read: false
    },

    etc...

$scope.clearNotifications = function(ev) {
    var confirm = $mdDialog.confirm()
        .parent(angular.element('body'))
        .clickOutsideToClose(true)
        .title('Are you sure you want to clear all notifications?')
        .textContent('This action cannot be undone.')
        .ariaLabel('Confirm notifications list clearance')
        .ok('Yes')
        .cancel('No')
        .targetEvent(ev)

    $mdDialog.show(confirm).then(function() {
        $scope.status = 'All notifications deleted';
        console.log($scope.status);
        this.notifications.length = 0;
        console.log(this.notifications);
    }, function() {
        $scope.status = 'Notifications list not cleared';
        console.log($scope.status);
    })
}

Body:
The this in:

$mdDialog.show(confirm).then(function() {
    ...
    this.notifications.length = 0; // <---- here
    ...
}, function() {
    ...
})

refers to the promise resolve function of the promise returned by $mdDialog.show(), if you wanted to access the controller's notifications member you'd have to create a var that refers to the controller's this:

app.controller('notificationsController', function($scope, $state,
$http, $document, $mdDialog, $filter, $timeout) {

  var _this = this; // <--- Now _this is the controller
  this.notifications = [
  {
    title: 'Notification One',
    description: 'Description...',
    time: '2017-10-27T16:39:32+00:00',
    importance: 'Low',
    read: false
  },

etc...

$scope.clearNotifications = function(ev) {
  ...

  $mdDialog.show(confirm).then(function() {
    ...
    _this.notifications.length = 0; //<--- using _this and not this
    ...
  }, function() {
    ...
  })
}


问:
PHP or C# or (X)? HTTP Request every 10 seconds and Chart image generation
Objective: HTTP Request every 10 seconds, chart image generation on server and upload back to user's browser for display

I wanted to go with LAMP + pChart but worried it might not handle > 1000 of simultaneous users and slow the server down to a crawl.

I thought about offloading the chart image generation to Google Charts but if the request is once every 10 seconds, I'd blast through the daily limit easily.

What server + lang is best for this implementation? Would I need to think about scaling at this point yet?

答: While it will depend on the charting library, honestly one request every 10 seconds is not that much. You won't go wrong with any of the languages and either LAMP or IIS.  </p>


问:
How to sort a multidimensional array on PHP where keys are not string labels
I have this multidimensional array:

```<code>$serviceTimes = Array (
  [0] => Array ( [0] => PM1900 [1] => 7:00pm )
  [1] => Array ( [0] => PM1900 [1] => 7:00pm )
  [2] => Array ( [0] => PM1415 [1] => 2:15pm )
  [3] => Array ( [0] => PM1919 [1] => 7:19pm )
  [6] => Array ( [0] => PM2020 [1] => 8:20pm )
)
</code>```

But I am unable to sort the array on the [0] element. This does not work:

array_multisort( $serviceTimes[0], SORT_ASC, $serviceTimes );

nor does this work

array_multisort( $serviceTimes[][0], SORT_ASC, $serviceTimes );

Any thoughts?

Ideally and ultimately, this is what I am looking to produce:

```<code>Array (
  [0] => 2:15pm )
  [1] => 7:00pm )
  [2] => 7:00pm )
  [3] => 7:19pm )
  [4] => 8:20pm )
)
</code>```

答:
Use array_column to extract the 0 column from the sub-arrays and sort on that:

```<code>array_multisort(array_column($serviceTimes, 0), SORT_ASC, $serviceTimes);
</code>```

You state sorting on the 0 element but your output shows times from the 1 element.  If so just change the array_column argument to a 1.

Body:
I have this multidimensional array:

$serviceTimes = Array (
  [0] => Array ( [0] => PM1900 [1] => 7:00pm )
  [1] => Array ( [0] => PM1900 [1] => 7:00pm )
  [2] => Array ( [0] => PM1415 [1] => 2:15pm )
  [3] => Array ( [0] => PM1919 [1] => 7:19pm )
  [6] => Array ( [0] => PM2020 [1] => 8:20pm )
)

But I am unable to sort the array on the [0] element. This does not work:

array_multisort( $serviceTimes[0], SORT_ASC, $serviceTimes );

nor does this work

array_multisort( $serviceTimes[][0], SORT_ASC, $serviceTimes );

Any thoughts?

Ideally and ultimately, this is what I am looking to produce:

Array (
  [0] => 2:15pm )
  [1] => 7:00pm )
  [2] => 7:00pm )
  [3] => 7:19pm )
  [4] => 8:20pm )
)

Body:
Use array_column to extract the 0 column from the sub-arrays and sort on that:

array_multisort(array_column($serviceTimes, 0), SORT_ASC, $serviceTimes);

You state sorting on the 0 element but your output shows times from the 1 element.  If so just change the array_column argument to a 1.


问:
array_unique() function in PHP does not work for my array
I have create a function for chat. I want to get only one value from set of values. I used array_unique function in it.

Error:

```<code>function get_chat_list($sender){
        global $conn;
        $sqlCode = "SELECT DISTINCT sender FROM chat WHERE connector LIKE '%$sender%' ";
        $sqlCode1 = "SELECT DISTINCT reciever FROM chat WHERE connector LIKE '$sender%'";
        var_dump($sqlCode1);
        $run = mysqli_query($conn,$sqlCode);
        $run1 = mysqli_query($conn,$sqlCode1);
        var_dump($run1);
        $recievers = array();
        while($reciever = mysqli_fetch_assoc($run)){
            if($reciever['sender'] == $sender){

            }else{
                $recievers[] = array('reciever'=>$reciever['sender']);
            }

        }

        while($reciever = mysqli_fetch_assoc($run1)){
            if($reciever['reciever'] == $sender){

            }else{
                $recievers[] = array('reciever'=>$reciever['reciever']);
            }

        }

        return array_unique($recievers);
    }
</code>```

Error image

答:
You are trying to make string comparisons on arrays (non-scalar).  I don't think array_unique works on an array of arrays, it has to be array of strings.  If you want unique receivers, you're going to need to turn that value into a string.

I don't know what you might be using the array for, but one solution would be to serialize/stringify the array and then you can run your unique, then unwrap/desalinize the string later.  I'm not sure why if there is only one value in that array, you are using a key for it.  How about just storing the string and it should work for you

EX:

```<code>function get_chat_list($sender){
      global $conn;
      $sqlCode = "SELECT DISTINCT sender FROM chat WHERE connector LIKE '%$sender%' ";
      $sqlCode1 = "SELECT DISTINCT reciever FROM chat WHERE connector LIKE '$sender%'";
      var_dump($sqlCode1);
      $run = mysqli_query($conn,$sqlCode);
      $run1 = mysqli_query($conn,$sqlCode1);
      var_dump($run1);
      $recievers = array();
      while($reciever = mysqli_fetch_assoc($run)){
          if($reciever['sender'] != $sender){
              $recievers[] = $reciever['sender'];
          }

      }

      while($reciever = mysqli_fetch_assoc($run1)){
          if($reciever['reciever'] != $sender){
            $recievers[] = $reciever['reciever'];
          }

      }

      return array_unique($recievers);
   }
</code>```

Body:
I have create a function for chat. I want to get only one value from set of values. I used array_unique function in it.

Error:

function get_chat_list($sender){
        global $conn;
        $sqlCode = "SELECT DISTINCT sender FROM chat WHERE connector LIKE '%$sender%' ";
        $sqlCode1 = "SELECT DISTINCT reciever FROM chat WHERE connector LIKE '$sender%'";
        var_dump($sqlCode1);
        $run = mysqli_query($conn,$sqlCode);
        $run1 = mysqli_query($conn,$sqlCode1);
        var_dump($run1);
        $recievers = array();
        while($reciever = mysqli_fetch_assoc($run)){
            if($reciever['sender'] == $sender){

            }else{
                $recievers[] = array('reciever'=>$reciever['sender']);
            }

        }

        while($reciever = mysqli_fetch_assoc($run1)){
            if($reciever['reciever'] == $sender){

            }else{
                $recievers[] = array('reciever'=>$reciever['reciever']);
            }

        }

        return array_unique($recievers);
    }

Error image

Body:
You are trying to make string comparisons on arrays (non-scalar).  I don't think array_unique works on an array of arrays, it has to be array of strings.  If you want unique receivers, you're going to need to turn that value into a string.

I don't know what you might be using the array for, but one solution would be to serialize/stringify the array and then you can run your unique, then unwrap/desalinize the string later.  I'm not sure why if there is only one value in that array, you are using a key for it.  How about just storing the string and it should work for you

EX:

function get_chat_list($sender){
      global $conn;
      $sqlCode = "SELECT DISTINCT sender FROM chat WHERE connector LIKE '%$sender%' ";
      $sqlCode1 = "SELECT DISTINCT reciever FROM chat WHERE connector LIKE '$sender%'";
      var_dump($sqlCode1);
      $run = mysqli_query($conn,$sqlCode);
      $run1 = mysqli_query($conn,$sqlCode1);
      var_dump($run1);
      $recievers = array();
      while($reciever = mysqli_fetch_assoc($run)){
          if($reciever['sender'] != $sender){
              $recievers[] = $reciever['sender'];
          }

      }

      while($reciever = mysqli_fetch_assoc($run1)){
          if($reciever['reciever'] != $sender){
            $recievers[] = $reciever['reciever'];
          }

      }

      return array_unique($recievers);
   }


问:
Optimization of long method chain in Java
Analyzing some pre-existing third-party Java code (which cannot be re-written) in an application, I discovered that it is almost entirely structured on long method chains, of the form

```<code>public Object process() {
  // Do some class-specific stuff
  return this.getChild().process();
}
</code>```

where there is a base class defining the process() method, inherited by subclasses that redefine that method and the getChild() call is repeated at the end.

Multiple such chains are created (branched off) at runtime as a result of conditional blocks, some of which may return relatively early (e.g., after 10-20 "links" in the chain), but most commonly the "length" of the chain is much bigger and can even exceed 100 consecutive method calls, before returning the result.

The application uses this code to process large files, with results changing for every invocation of the top level method, usually once every different line of each file.

So, two questions:

What performance implications should be expected from such a design, compared to a "regular" one?

Is there any trick to notably improve performance of that code as-is (e.g., by changing some JVM parameter)?

答:
A statement of the form

```<code>return getChild().process();
</code>```

is not different to

```<code>SomeType var = getChild();
return var.process();
</code>```

In both cases, one method will be invoked after the other and the return value of getChild() will be used as receiver of the process() call.

If you are hunting for irrelevant minor technical details, the first form doesn’t need a local variable. But since in HotSpot, a fixed-size stack memory is pre-allocated on thread creation, it is impossible to perceive any performce difference between these two forms.

The choice between these two forms is purely a stylistic one.

Body:
Analyzing some pre-existing third-party Java code (which cannot be re-written) in an application, I discovered that it is almost entirely structured on long method chains, of the form

public Object process() {
  // Do some class-specific stuff
  return this.getChild().process();
}

where there is a base class defining the process() method, inherited by subclasses that redefine that method and the getChild() call is repeated at the end.

Multiple such chains are created (branched off) at runtime as a result of conditional blocks, some of which may return relatively early (e.g., after 10-20 "links" in the chain), but most commonly the "length" of the chain is much bigger and can even exceed 100 consecutive method calls, before returning the result.

The application uses this code to process large files, with results changing for every invocation of the top level method, usually once every different line of each file.

So, two questions:

What performance implications should be expected from such a design, compared to a "regular" one?

Is there any trick to notably improve performance of that code as-is (e.g., by changing some JVM parameter)?

Body:
A statement of the form

return getChild().process();

is not different to

SomeType var = getChild();
return var.process();

In both cases, one method will be invoked after the other and the return value of getChild() will be used as receiver of the process() call.

If you are hunting for irrelevant minor technical details, the first form doesn’t need a local variable. But since in HotSpot, a fixed-size stack memory is pre-allocated on thread creation, it is impossible to perceive any performce difference between these two forms.

The choice between these two forms is purely a stylistic one.


问:
UIBarButtonItem still selected/highlighted after unwind segue
Small question here.

I have an UIBarButtonItem which makes a segue to another table view. When the user is done here I've implemented a unwind segue back to the first table view. Everything works fine except for the fact that the UIBarButtonItem is still selected/highlighted after the unwind segue which can be seen here. I have no idea why this is the case and was wondering how I could fix this?

Thanks in advance.

Edit: I meant this when I said it was embedded

答:
Using a navigation controller might be causing this. Using the popToViewController might solve the problem. Just replace MyViewController with the VievController you want to go to.</p>

```<code>let vc = self.navigationController?.viewControllers

for v in vc! {

    print("viewcontroller is: \(v)")
    if v as? MyViewController != nil {
        self.navigationController?.popToViewController(v, animated: false)
    }
}
</code>```

Body:
Using a navigation controller might be causing this. Using the popToViewController might solve the problem. Just replace MyViewController with the VievController you want to go to.

let vc = self.navigationController?.viewControllers

for v in vc! {

    print("viewcontroller is: \(v)")
    if v as? MyViewController != nil {
        self.navigationController?.popToViewController(v, animated: false)
    }
}


问:
Using subscribe on a GroupedObservable in map
I have an array of objects like the follwing:

```<code>private questions: Question[] = [
    {
        title: "...",
        category: "Technologie",
        answer: `...`
    },
    {
        title: "...",
        category: "Technologie",
        answer: `...`
    },
    {
        title: "...",
        category: "eID",
        answer: `...`
    }
];
</code>```

And I would like to group them by categories, filter them based on a value and return the result as an array. Currently, I'm using this:

```<code>Observable
    .from(this.questions)
    .groupBy(q => q.category)
    .map(go =>
    {
        let category: Category = { title: go.key, questions: [] };

        go.subscribe(d => category.questions.push(d));

        return category;
    })
    .filter(c =>  c.title.toLowerCase().indexOf(value.toLowerCase()) >= 0 || c.questions.filter(q => q.title.toLowerCase().indexOf(value.toLowerCase()) >= 0).length > 0)
    .toArray()
</code>```

This finds the question with the value in the category title but not the one with the value in the question title. I think that's because I'm using a subscribe in map, therefore, the questions are not yet available in the filter method, so I was wondering if there's a possibility to wait for the subscribe to end before going into filter. My research pointed me to flatMap but I can't get it to do what I want.

EDIT

I figured out that I can fix the issue like this:

```<code>Observable
    .from(this.questions)
    .filter(q =>  q.category.toLowerCase().indexOf(value.toLowerCase()) >= 0 || q.title.toLowerCase().indexOf(value.toLowerCase()) >= 0)
    .groupBy(q => q.category)
    .map(go =>
    {
        let category: Category = { title: go.key, questions: [] };

        go.subscribe(d => category.questions.push(d));

        return category;
    })
    .toArray()
</code>```

But I'm still interested in the answer.

答:
When you use groupBy, you get a grouped observable that can be flattened with operators like concatMap, mergeMap, switchMap etc. Within those operators, grouped observables can be transformed separately for each category, i.e. collect the questions together into an array with reduce, and then create the desired object with map.</p>

```<code>   Observable
        .from(questions)
        .groupBy(q => q.category)
        .mergeMap(go => {
            return go.reduce((acc, question) => { acc.push(question); return acc; }, [])
                .map(questions => ({ title: go.key, questions }));
        })
        .filter(c => "...")
        .toArray()
</code>```

Body:
I have an array of objects like the follwing:

private questions: Question[] = [
    {
        title: "...",
        category: "Technologie",
        answer: `...`
    },
    {
        title: "...",
        category: "Technologie",
        answer: `...`
    },
    {
        title: "...",
        category: "eID",
        answer: `...`
    }
];

And I would like to group them by categories, filter them based on a value and return the result as an array. Currently, I'm using this:

Observable
    .from(this.questions)
    .groupBy(q => q.category)
    .map(go =>
    {
        let category: Category = { title: go.key, questions: [] };

        go.subscribe(d => category.questions.push(d));

        return category;
    })
    .filter(c =>  c.title.toLowerCase().indexOf(value.toLowerCase()) >= 0 || c.questions.filter(q => q.title.toLowerCase().indexOf(value.toLowerCase()) >= 0).length > 0)
    .toArray()

This finds the question with the value in the category title but not the one with the value in the question title. I think that's because I'm using a subscribe in map, therefore, the questions are not yet available in the filter method, so I was wondering if there's a possibility to wait for the subscribe to end before going into filter. My research pointed me to flatMap but I can't get it to do what I want.

EDIT

I figured out that I can fix the issue like this:

Observable
    .from(this.questions)
    .filter(q =>  q.category.toLowerCase().indexOf(value.toLowerCase()) >= 0 || q.title.toLowerCase().indexOf(value.toLowerCase()) >= 0)
    .groupBy(q => q.category)
    .map(go =>
    {
        let category: Category = { title: go.key, questions: [] };

        go.subscribe(d => category.questions.push(d));

        return category;
    })
    .toArray()

But I'm still interested in the answer.

Body:
When you use groupBy, you get a grouped observable that can be flattened with operators like concatMap, mergeMap, switchMap etc. Within those operators, grouped observables can be transformed separately for each category, i.e. collect the questions together into an array with reduce, and then create the desired object with map.

   Observable
        .from(questions)
        .groupBy(q => q.category)
        .mergeMap(go => {
            return go.reduce((acc, question) => { acc.push(question); return acc; }, [])
                .map(questions => ({ title: go.key, questions }));
        })
        .filter(c => "...")
        .toArray()


问:
Locks at C# to use prevent multiple threads or events to use same variable value
I want to free my application from sql, because I do not have a large db. I want to hold my data on memory, so my application will run faster.

My question here is that I've a key pool, and a key can be used by only 4 clients, I want to lock each key when it is registered to a client so I will use:

```<code>lock(key)
{
  assignKeyToClient(clientId);
}
</code>```

If I use that, will lock use the copy of the key or lock the original "key" on ram and does free it after finishing assignment?

Thanks!

答:
If you don't have a large database then all your database queries should be < 1 second. You don't have any reason to put all the data in memory. The performance difference by querying the database directly or querying it from memory is negligible.

All you're really doing is over complicating your application. Premature optimization is the root of all evil.

Body:
I want to free my application from sql, because I do not have a large db. I want to hold my data on memory, so my application will run faster.

My question here is that I've a key pool, and a key can be used by only 4 clients, I want to lock each key when it is registered to a client so I will use:

lock(key)
{
  assignKeyToClient(clientId);
}

If I use that, will lock use the copy of the key or lock the original "key" on ram and does free it after finishing assignment?

Thanks!


问:
Ruby | Trying to check password by comparing to a file
I have some troubles with my code using Ruby. its just for a terminal program, so no website or anything.

In my code I Will have the user create a login. Then I will have the user to login, but I cant seem to figure out how to check if password or username is correct.

The program should compare whatever the user types in as a username/password with the file (userdatabase) - I think i got that right.

Now I am trying to stop the user if the input is not found in the user database, using a while loop, but i cant seem to make that work.

Code:

```<code>puts "What will be your user name?"
</code>```

username = gets.chomp

```<code>puts "What will be your password?"

password = gets.chomp

puts "Please repeat your password."

passwordsafe = gets.chomp

f = File.new("student.txt", "w+")
f.puts username + ";" + password + ";"  + passwordsafe
f.close

puts "well done, you have created a new user."

lines = IO.readlines("student.txt")
lines.each{|line| print(line)}

puts "now you need to login."
puts "What is your username?"
username = gets.chomp

File.open("student.txt") do |f|
  f.any? do |line|
    while line.include?(username)
  end
end

elsif puts "Sorry your username was incorrect"
end

#lines = IO.readlines("student.txt")
#lines.each{|line| (line)}

puts "what is your password?"
password = gets.chomp
</code>```

答:
The while is unnecessary.

The username check currently like this:

```<code>File.open("student.txt") do |f|
  f.any? do |line|
    while line.include?(username)
  end
end
</code>```

Could be like this:

```<code>File.open("student.txt").each_line.any? do |line|
  line.include?(username)
end
</code>```

Or collapsed to a single line like this:

```<code>File.open("student.txt").each_line.any?{ |l| l.include?(username) }
</code>```

Check the docs on the any? method to make sure you understand what it's expecting: http://ruby-doc.org/core-2.4.2/Enumerable.html#method-i-any-3F

As for the rest of the syntax errors, I'll leave those up to you ;)

Body:
I have some troubles with my code using Ruby. its just for a terminal program, so no website or anything.

In my code I Will have the user create a login. Then I will have the user to login, but I cant seem to figure out how to check if password or username is correct.

The program should compare whatever the user types in as a username/password with the file (userdatabase) - I think i got that right.

Now I am trying to stop the user if the input is not found in the user database, using a while loop, but i cant seem to make that work.

Code:

puts "What will be your user name?"

username = gets.chomp

puts "What will be your password?"

password = gets.chomp

puts "Please repeat your password."

passwordsafe = gets.chomp

f = File.new("student.txt", "w+")
f.puts username + ";" + password + ";"  + passwordsafe
f.close

puts "well done, you have created a new user."

lines = IO.readlines("student.txt")
lines.each{|line| print(line)}

puts "now you need to login."
puts "What is your username?"
username = gets.chomp

File.open("student.txt") do |f|
  f.any? do |line|
    while line.include?(username)
  end
end

elsif puts "Sorry your username was incorrect"
end

#lines = IO.readlines("student.txt")
#lines.each{|line| (line)}

puts "what is your password?"
password = gets.chomp

Body:
The while is unnecessary.

The username check currently like this:

File.open("student.txt") do |f|
  f.any? do |line|
    while line.include?(username)
  end
end

Could be like this:

File.open("student.txt").each_line.any? do |line|
  line.include?(username)
end

Or collapsed to a single line like this:

File.open("student.txt").each_line.any?{ |l| l.include?(username) }

Check the docs on the any? method to make sure you understand what it's expecting: http://ruby-doc.org/core-2.4.2/Enumerable.html#method-i-any-3F

As for the rest of the syntax errors, I'll leave those up to you ;)


问:
Organize Models in subdirectories CakePHP 3
we are using subdirectories in our projects no separete views and controllers but in models we didn’t learn yet. Recently I’ve found this https://github.com/cakephp/cakephp/issues/60451 and actually routes and plugins we are already using, we just want to separete our models like this:

```<code>Model
-Entity
–Financial
—Money.php
-Table
–Financial
—MoneyTable.php
</code>```

I’ve tryed put like this then controller is not able to find his model. How can I do to organize it, and make it work?

Things that we've tried:
Use $this->setAlias('TableModel');
Call in controller:

```<code>$this->TableModel = $this->loadModel('Subfolder/TableModel');
</code>```

didn't work for SQL build, and other classes.

答:
CakePHP uses the TableRegister to load models. That class can be configured to use a class that implements the LocatorInterface, and CakePHP uses the TableLocator as the default.

The only thing you can do is configure your own LocatorInterface instance in your bootstrap.php. You would have to create your MyTableLocator and have it change the className for tables to point to subdirectories. What rules for this class name rewritting are used is purely up to you.

bootstrap.php:

```<code>TableRegister::setTableLocator(new MyTableLocator());
</code>```

MyTableLocator.php:

```<code>class MyTableLocator extends TableLocator {
    protected function _getClassName($alias, array $options = [])
    {
       if($alias === 'Subfolder/TableModel') {
           return TableModel::class;
       }
       return parent::_getClassName($alias, $options);
    }
}
</code>```

The above isn't working code.

I'm just demonstrating what the function is you need to override, and that you need logic in place to return a different class name.

You can check if the $alias contains the / character, and if so. Return a class name by extracting the subfolder name from the $alias. Take a look at the TableLocator to see how it's using the App::className function.

Body:
we are using subdirectories in our projects no separete views and controllers but in models we didn’t learn yet. Recently I’ve found this https://github.com/cakephp/cakephp/issues/60451 and actually routes and plugins we are already using, we just want to separete our models like this:

Model
-Entity
–Financial
—Money.php
-Table
–Financial
—MoneyTable.php

I’ve tryed put like this then controller is not able to find his model. How can I do to organize it, and make it work?

Things that we've tried:
Use $this->setAlias('TableModel');
Call in controller:

$this->TableModel = $this->loadModel('Subfolder/TableModel');

didn't work for SQL build, and other classes.

Body:
CakePHP uses the TableRegister to load models. That class can be configured to use a class that implements the LocatorInterface, and CakePHP uses the TableLocator as the default.

The only thing you can do is configure your own LocatorInterface instance in your bootstrap.php. You would have to create your MyTableLocator and have it change the className for tables to point to subdirectories. What rules for this class name rewritting are used is purely up to you.

bootstrap.php:

TableRegister::setTableLocator(new MyTableLocator());

MyTableLocator.php:

class MyTableLocator extends TableLocator {
    protected function _getClassName($alias, array $options = [])
    {
       if($alias === 'Subfolder/TableModel') {
           return TableModel::class;
       }
       return parent::_getClassName($alias, $options);
    }
}

The above isn't working code.

I'm just demonstrating what the function is you need to override, and that you need logic in place to return a different class name.

You can check if the $alias contains the / character, and if so. Return a class name by extracting the subfolder name from the $alias. Take a look at the TableLocator to see how it's using the App::className function.