问:
iOS Crash: " this class is not key value coding-compliant for the key url"
I am getting the following crash on crashlytics.

Fatal Exception: NSUnknownKeyException
      [<__NSCFString 0x1742aeb80> valueForUndefinedKey:]: this class is not key value coding-compliant for the key url.

This is where the crash occurred for some of the users.

```<code> id url = [[json[@"data"]valueForKey:@"value"]valueForKey:@"url"];
</code>```

I'm not sure what is the best way to prevent this crash. I believe this is because json[@"data"] is an NSString in certain cases. So I believe I should check if this is an NSDictionary like this.

```<code>if ([json[@"data"] isKindOfClass:[NSDictionary class]]) {
     id url = [[json[@"data"]valueForKey:@"value"]valueForKey:@"url"];
    }
</code>```

Any tips or suggestions are appreciated.

This is my end result after getting answers from here. Does this look okay? I didn't include all my code at first to keep things simple.

```<code>        if ([json isKindOfClass:[NSDictionary class]]) {
            id url = nil;
            id type = nil;

            NSDictionary *data = json[@"data"];

            if ([data isKindOfClass:[NSDictionary class]]) {
                type = data[@"type"];
                NSDictionary *value = data[@"value"];

                if ([value isKindOfClass:[NSArray class]]) {
                    url = [value valueForKey:@"url"];
                }

                if ([type isKindOfClass:[NSString class]] && [url isKindOfClass:[NSArray class]] && [url count] != 0) {
                   // do stuff
              }
            }
         }
</code>```

答:
Your error means that json[@"data"]valueForKey:@"value"] doesn't NSDictionarry, so it  have no @"url" key.

valueForKey it's KVC method, use objectForKey for dictionaries, and add more checks like:

```<code>        id url = nil;
        NSDictionary *data = [json objectForkey:@"data"];
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSDictionary *value = [data objectForKey:@"value"];
            if ([value isKindOfClass:[NSDictionary class]]) {
                url = [value objectForKey:@"url"];
            }
        }
</code>```

Body:
I am getting the following crash on crashlytics.

Fatal Exception: NSUnknownKeyException
      [<__NSCFString 0x1742aeb80> valueForUndefinedKey:]: this class is not key value coding-compliant for the key url.

This is where the crash occurred for some of the users.

 id url = [[json[@"data"]valueForKey:@"value"]valueForKey:@"url"];

I'm not sure what is the best way to prevent this crash. I believe this is because json[@"data"] is an NSString in certain cases. So I believe I should check if this is an NSDictionary like this.

if ([json[@"data"] isKindOfClass:[NSDictionary class]]) {
     id url = [[json[@"data"]valueForKey:@"value"]valueForKey:@"url"];
    }

Any tips or suggestions are appreciated.

This is my end result after getting answers from here. Does this look okay? I didn't include all my code at first to keep things simple.

        if ([json isKindOfClass:[NSDictionary class]]) {
            id url = nil;
            id type = nil;

            NSDictionary *data = json[@"data"];

            if ([data isKindOfClass:[NSDictionary class]]) {
                type = data[@"type"];
                NSDictionary *value = data[@"value"];

                if ([value isKindOfClass:[NSArray class]]) {
                    url = [value valueForKey:@"url"];
                }

                if ([type isKindOfClass:[NSString class]] && [url isKindOfClass:[NSArray class]] && [url count] != 0) {
                   // do stuff
              }
            }
         }

Body:
Your error means that json[@"data"]valueForKey:@"value"] doesn't NSDictionarry, so it  have no @"url" key.

valueForKey it's KVC method, use objectForKey for dictionaries, and add more checks like:

        id url = nil;
        NSDictionary *data = [json objectForkey:@"data"];
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSDictionary *value = [data objectForKey:@"value"];
            if ([value isKindOfClass:[NSDictionary class]]) {
                url = [value objectForKey:@"url"];
            }
        }


来源: stackexchange

问:
Sending asynchronous message from server to client
I am writing program to solve the dining philosophers problem without a server. It should work by message passing. My application should run 5 times and then connect to each other and solve the problem by themselves. I put a server side and client side in each app, and I  gave them a port number. This image will show what i am talking about:

https://www.photobox.co.uk/my/photo/full?photo_id=500223105218

All I want is sending messages between client sides and server sides.

But I have an error in sending message asynchronously from server side by socket handler.(mentioned it below)

I searched about that but could not find any code similar, so how can I send messages directly from server side to client side?

And, how is my idea? is that right? or it is wrong.

This is part of my code which works well:

```<code>  String status = "Thinking";
        Boolean right = false;
        Boolean left = false;
        // Receiving byte array
        byte[] bytes = new byte[1024];
        SocketPermission permission;
        Socket sListener;
        Socket sListener1;
        Socket sListener2;
        Socket sListener3;
        Socket sListener4;
        Socket handler1;
        Socket handler2;
        Socket handler3;
        Socket handler4;
        Socket handler5;
        Socket senderSock;
        Socket senderSock1;
        Socket senderSock2;
        Socket senderSock3;
        Socket senderSock4;

        public Form1()
        {
            InitializeComponent();
        }

        //start button
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                IPEndPoint ipEndPoint=null;
                IPEndPoint ipEndPoint1=null;
                IPEndPoint ipEndPoint2 = null;
                IPEndPoint ipEndPoint3 = null;
                IPEndPoint ipEndPoint4 = null;
                // Creates one SocketPermission object for access restrictions
                permission = new SocketPermission(
                NetworkAccess.Accept,     // Allowed to accept connections
                TransportType.Tcp,        // Defines transport types
                "",                       // The IP addresses of local host
                SocketPermission.AllPorts // Specifies all ports
                );

                // Listening Socket object
                sListener = null;
                sListener1 = null;
                sListener2 = null;
                sListener3 = null;
                sListener4 = null;
                // Ensures the code to have permission to access a Socket
                permission.Demand();

                // Resolves a host name to an IPHostEntry instance
                IPHostEntry ipHost = Dns.GetHostEntry("");

                // Gets first IP address associated with a localhost
                IPAddress ipAddr = ipHost.AddressList[0];

                // Creates a network endpoint
                if (Sport.Text == "1000")
                {
                    ipEndPoint = new IPEndPoint(ipAddr, Convert.ToInt32(Sport.Text));
                }else if (Sport.Text == "1001")
                {
                    ipEndPoint1 = new IPEndPoint(ipAddr, Convert.ToInt32(Sport.Text));
                }
                else if (Sport.Text == "1002")
                {
                    ipEndPoint2 = new IPEndPoint(ipAddr, Convert.ToInt32(Sport.Text));
                }
                else if (Sport.Text == "1003")
                {
                    ipEndPoint3 = new IPEndPoint(ipAddr, Convert.ToInt32(Sport.Text));
                }
                else if (Sport.Text == "1004")
                {
                    ipEndPoint4 = new IPEndPoint(ipAddr, Convert.ToInt32(Sport.Text));
                }

                // Associates a Socket with a local endpoint
                if (Sport.Text == "1000")
                {
                    // Create one Socket object to listen the incoming connection
                    sListener = new Socket(
                    ipAddr.AddressFamily,
                    SocketType.Stream,
                    ProtocolType.Tcp
                    );
                    sListener.Bind(ipEndPoint);
                    sListener.Listen(10);
                }else if(Sport.Text == "1001")
                {
                    sListener1 = new Socket(
                    ipAddr.AddressFamily,
                    SocketType.Stream,
                    ProtocolType.Tcp
                    );
                    sListener1.Bind(ipEndPoint1);
                    sListener1.Listen(10);
                }
                else if (Sport.Text == "1002")
                {
                    sListener2 = new Socket(
                    ipAddr.AddressFamily,
                    SocketType.Stream,
                    ProtocolType.Tcp
                    );
                    sListener2.Bind(ipEndPoint2);
                    sListener2.Listen(10);
                }
                else if (Sport.Text == "1003")
                {
                    sListener3 = new Socket(
                   ipAddr.AddressFamily,
                   SocketType.Stream,
                   ProtocolType.Tcp
                   );
                    sListener3.Bind(ipEndPoint3);
                    sListener3.Listen(10);
                }
                else if (Sport.Text == "1004")
                {
                    sListener4 = new Socket(
                    ipAddr.AddressFamily,
                    SocketType.Stream,
                    ProtocolType.Tcp
                    );
                    sListener4.Bind(ipEndPoint4);
                    sListener4.Listen(10);
                }

                label3.Text = "Server started.";
                statusLabel.Text = "READY";
                button1.Enabled = false;
            }
            catch (Exception exc) { MessageBox.Show(exc.ToString()); }
        }

        //connect button
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                IPEndPoint ipEndPoint = null;
                IPEndPoint ipEndPoint1 = null;
                IPEndPoint ipEndPoint2 = null;
                IPEndPoint ipEndPoint3 = null;
                IPEndPoint ipEndPoint4 = null;
                // Create one SocketPermission for socket access restrictions
                SocketPermission permission = new SocketPermission(
                    NetworkAccess.Connect,    // Connection permission
                    TransportType.Tcp,        // Defines transport types
                    "",                       // Gets the IP addresses
                    SocketPermission.AllPorts // All ports
                    );

                // Ensures the code to have permission to access a Socket
                permission.Demand();

                // Resolves a host name to an IPHostEntry instance
                IPHostEntry ipHost = Dns.GetHostEntry("");

                // Gets first IP address associated with a localhost

                IPAddress ipAddr = ipHost.AddressList[0];

                // Creates a network endpoint
                if (Cport.Text == "1000")
                {
                     ipEndPoint = new IPEndPoint(ipAddr, Convert.ToInt32(Cport.Text));
                }else if (Cport.Text == "1001")
                {
                     ipEndPoint1 = new IPEndPoint(ipAddr, Convert.ToInt32(Cport.Text));
                }
                else if (Cport.Text == "1002")
                {
                     ipEndPoint2 = new IPEndPoint(ipAddr, Convert.ToInt32(Cport.Text));
                }
                else if (Cport.Text == "1003")
                {
                     ipEndPoint3 = new IPEndPoint(ipAddr, Convert.ToInt32(Cport.Text));
                }
                else if (Cport.Text == "1004")
                {
                     ipEndPoint4 = new IPEndPoint(ipAddr, Convert.ToInt32(Cport.Text));
                }

                if (Cport.Text == "1000")//A
                {
                    // Create one Socket object to setup Tcp connection
                    senderSock = new Socket(
                        ipAddr.AddressFamily,// Specifies the addressing scheme
                        SocketType.Stream,   // The type of socket
                        ProtocolType.Tcp     // Specifies the protocols
                        );
                    senderSock.NoDelay = false;   // Using the Nagle algorithm
                    // Establishes a connection to a remote host
                    senderSock.Connect(ipEndPoint);
                    statusLabel.Text = "Socket connected to " + senderSock.RemoteEndPoint.ToString();
                }
                else if (Cport.Text == "1001")//B
                {
                    senderSock1 = new Socket(
                        ipAddr.AddressFamily,
                        SocketType.Stream,
                        ProtocolType.Tcp
                        );
                    senderSock1.NoDelay = false;
                    senderSock1.Connect(ipEndPoint1);
                    statusLabel.Text = "Socket connected to " + senderSock1.RemoteEndPoint.ToString();
                }
                else if (Cport.Text == "1002")//C
                {
                    senderSock2 = new Socket(
                        ipAddr.AddressFamily,
                        SocketType.Stream,
                        ProtocolType.Tcp
                        );
                    senderSock2.NoDelay = false;
                    senderSock2.Connect(ipEndPoint2);
                    statusLabel.Text = "Socket connected to " + senderSock2.RemoteEndPoint.ToString();
                }
                else if (Cport.Text == "1003")//D
                {
                    senderSock3 = new Socket(
                        ipAddr.AddressFamily,
                        SocketType.Stream,
                        ProtocolType.Tcp
                        );
                    senderSock3.NoDelay = false;
                    senderSock3.Connect(ipEndPoint3);
                    statusLabel.Text = "Socket connected to " + senderSock3.RemoteEndPoint.ToString();
                }
                else if (Cport.Text == "1004")//E
                {
                    senderSock4 = new Socket(
                        ipAddr.AddressFamily,
                        SocketType.Stream,
                        ProtocolType.Tcp
                        );
                    senderSock4.NoDelay = false;
                    senderSock4.Connect(ipEndPoint4);
                    statusLabel.Text = "Socket connected to " + senderSock4.RemoteEndPoint.ToString();
                }
               button2.Enabled = false;
            }
            catch (Exception exc) { MessageBox.Show(exc.ToString()); }

            label3.Text = "wait...";
            Thread.Sleep(4000);
            send_st();
        }
</code>```

And here is my code where I get an Error in "Send(handler1, status);"
The error is: "Object reference not set to an instance of an object"

```<code>//send status from clnt to server
        public void sendCToS(String str)
        {
            try
            {
                // Sending message
                //<Client Quit> is the sign for end of data
                byte[] msg = Encoding.Unicode.GetBytes(str + "<Client Quit>");
                // Sends data to a connected Socket.
                //send status from client to server
                int bytesSend = senderSock.Send(msg);//receiver server tasmim giri va response send mikone

            }
            catch (Exception exc) { MessageBox.Show(exc.ToString()); }
        }

        //it send hungry status from both to both!
        public void send_st()
        {
            // Resolves a host name to an IPHostEntry instance
            IPHostEntry ipHost = Dns.GetHostEntry("");
            // Gets first IP address associated with a localhost
            IPAddress ipAddr = ipHost.AddressList[0];

            Random rnd = new Random();
            int delay = rnd.Next(2000, 5000);
            while (true)
            {
                //System.Threading.Thread.Sleep(2000);
                statusLabel.Text = status;
                statusLabel.ForeColor = System.Drawing.Color.Blue;
                Thread.Sleep(delay);

                if (Sport.Text == "1000")//A
                {
                    status = "hungry";
                    statusLabel.Text = "HUNGRY";
                    statusLabel.ForeColor = System.Drawing.Color.Red;
                    //send status from server to clint
                    Send(handler1, status);
                    //send status from clnt to server
                    sendCToS(status);
                    label3.Text = "status Sent to left and right";
                }
                else if (Sport.Text == "1001")//B
                {
                    Thread.Sleep(2000);
                    status = "hungry";
                    statusLabel.Text = "HUNGRY";
                    statusLabel.ForeColor = System.Drawing.Color.Red;
                    //send status from server to clint
                    Send(handler2, status);
                    //send status from clnt to server
                    sendCToS(status);
                    label3.Text = "status Sent to left and right";
                }
                else if (Sport.Text == "1002")//C
                {
                    status = "hungry";
                    statusLabel.Text = "HUNGRY";
                    statusLabel.ForeColor = System.Drawing.Color.Red;
                    //send status from server to clint
                    Send(handler3, status);
                    //send status from clnt to server
                    sendCToS(status);
                    label3.Text = "status Sent to left and right";
                }
                else if (Sport.Text == "1003")//D
                {
                    Thread.Sleep(2000);
                    status = "hungry";
                    statusLabel.Text = "HUNGRY";
                    statusLabel.ForeColor = System.Drawing.Color.Red;
                    //send status from server to clint
                    Send(handler4, status);
                    //send status from clnt to server
                    sendCToS(status);
                    label3.Text = "status Sent to left and right";
                }
                else if (Sport.Text == "1004")//E
                {
                    Thread.Sleep(3000);
                    status = "hungry";
                    statusLabel.Text = "HUNGRY";
                    statusLabel.ForeColor = System.Drawing.Color.Red;
                    //send status from server to clint
                    Send(handler5, status);
                    //send status from clnt to server
                    sendCToS(status);
                    label3.Text = "status Sent to left and right";
                }

            }
        }

        //server side
        // Thread signal.
        public static ManualResetEvent allDone = new ManualResetEvent(false);

        public void AcceptCallback(IAsyncResult ar)
        {
            Socket listener = null;
            // A new Socket to handle remote host communication
            Socket handler = null;
            try
            {
                // Receiving byte array
                byte[] buffer = new byte[1024];
                // Get Listening Socket object
                listener = (Socket)ar.AsyncState;
                // Create a new socket
                handler = listener.EndAccept(ar);

                // Using the Nagle algorithm
                handler.NoDelay = false;

                StateObject state = new StateObject();

                // Begins to asynchronously receive data
                handler.BeginReceive(
                    buffer,        // An array of type Byt for received data
                    0,             // The zero-based position in the buffer
                    buffer.Length, // The number of bytes to receive
                    0,// Specifies send and receive behaviors
                    new AsyncCallback(ReceiveCallback),//An AsyncCallback delegate
                    state            // Specifies infomation for receive operation
                    );

            }
            catch (Exception exc) { MessageBox.Show(exc.ToString()); }
        }

        public void ReceiveCallback(IAsyncResult ar)
        {
            String response = "ok";
            try
            {
                // Retrieve the state object and the handler socket
                // from the asynchronous state object.
                StateObject state = (StateObject)ar.AsyncState;
                Socket handler = state.workSocket;

                // Read data from the client socket.
                int bytesRead = handler.EndReceive(ar);

                // Received message
                string content = string.Empty;

                if (bytesRead > 0)
                {
                    // There  might be more data, so store the data received so far.
                    state.sb.Append(Encoding.ASCII.GetString(
                        state.buffer, 0, bytesRead));

                    // Check for end-of-file tag. If it is not there, read
                    // more data.
                    content = state.sb.ToString();
                    if (content.IndexOf("<Client Quit>") > -1)
                    {
                        // All the data has been read from the client
                        label3.Text = content;
                    }
                    else {
                        // Not all data received. Get more.
                        handler.BeginReceive(state.buffer, 0,StateObject.BufferSize, 0,
                        new AsyncCallback(ReceiveCallback), state);
                    }
</code>```

And this is the rest of the server side functions:

```<code>//func for echo back to client
        private void Send(Socket handler, String data)
        {
            // Convert the string data to byte data using ASCII encoding.
            byte[] byteData = Encoding.ASCII.GetBytes(data);

            // Begin sending the data to the remote device.
            handler.BeginSend(byteData, 0, byteData.Length, 0,
                new AsyncCallback(SendCallback), handler);
        }

        public void SendCallback(IAsyncResult ar)
        {

            try
            {
                // A Socket which has sent the data to remote host
                Socket handler = (Socket)ar.AsyncState;
                // The number of bytes sent to the Socket
                int bytesSend = handler.EndSend(ar);
                label3.Text = "Sent {0} bytes to Client" + bytesSend;
            }
            catch (Exception exc) { MessageBox.Show(exc.ToString()); }
</code>```

答:
I belive the problem is with this line:
senderSock.Send(msg);

You never instantiated the senderSock, you only declared it.
try this:

```<code> senderSock= new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
senderSock.Send(msg);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am writing program to solve the dining philosophers problem without a server. It should work by message passing. My application should run 5 times and then connect to each other and solve the problem by themselves. I put a server side and client side in each app, and I  gave them a port number. This image will show what i am talking about:

https://www.photobox.co.uk/my/photo/full?photo_id=500223105218

All I want is sending messages between client sides and server sides.

But I have an error in sending message asynchronously from server side by socket handler.(mentioned it below)

I searched about that but could not find any code similar, so how can I send messages directly from server side to client side?

And, how is my idea? is that right? or it is wrong.

This is part of my code which works well:

  String status = "Thinking";
        Boolean right = false;
        Boolean left = false;
        // Receiving byte array
        byte[] bytes = new byte[1024];
        SocketPermission permission;
        Socket sListener;
        Socket sListener1;
        Socket sListener2;
        Socket sListener3;
        Socket sListener4;
        Socket handler1;
        Socket handler2;
        Socket handler3;
        Socket handler4;
        Socket handler5;
        Socket senderSock;
        Socket senderSock1;
        Socket senderSock2;
        Socket senderSock3;
        Socket senderSock4;

        public Form1()
        {
            InitializeComponent();
        }

        //start button
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                IPEndPoint ipEndPoint=null;
                IPEndPoint ipEndPoint1=null;
                IPEndPoint ipEndPoint2 = null;
                IPEndPoint ipEndPoint3 = null;
                IPEndPoint ipEndPoint4 = null;
                // Creates one SocketPermission object for access restrictions
                permission = new SocketPermission(
                NetworkAccess.Accept,     // Allowed to accept connections
                TransportType.Tcp,        // Defines transport types
                "",                       // The IP addresses of local host
                SocketPermission.AllPorts // Specifies all ports
                );

                // Listening Socket object
                sListener = null;
                sListener1 = null;
                sListener2 = null;
                sListener3 = null;
                sListener4 = null;
                // Ensures the code to have permission to access a Socket
                permission.Demand();

                // Resolves a host name to an IPHostEntry instance
                IPHostEntry ipHost = Dns.GetHostEntry("");

                // Gets first IP address associated with a localhost
                IPAddress ipAddr = ipHost.AddressList[0];

                // Creates a network endpoint
                if (Sport.Text == "1000")
                {
                    ipEndPoint = new IPEndPoint(ipAddr, Convert.ToInt32(Sport.Text));
                }else if (Sport.Text == "1001")
                {
                    ipEndPoint1 = new IPEndPoint(ipAddr, Convert.ToInt32(Sport.Text));
                }
                else if (Sport.Text == "1002")
                {
                    ipEndPoint2 = new IPEndPoint(ipAddr, Convert.ToInt32(Sport.Text));
                }
                else if (Sport.Text == "1003")
                {
                    ipEndPoint3 = new IPEndPoint(ipAddr, Convert.ToInt32(Sport.Text));
                }
                else if (Sport.Text == "1004")
                {
                    ipEndPoint4 = new IPEndPoint(ipAddr, Convert.ToInt32(Sport.Text));
                }

                // Associates a Socket with a local endpoint
                if (Sport.Text == "1000")
                {
                    // Create one Socket object to listen the incoming connection
                    sListener = new Socket(
                    ipAddr.AddressFamily,
                    SocketType.Stream,
                    ProtocolType.Tcp
                    );
                    sListener.Bind(ipEndPoint);
                    sListener.Listen(10);
                }else if(Sport.Text == "1001")
                {
                    sListener1 = new Socket(
                    ipAddr.AddressFamily,
                    SocketType.Stream,
                    ProtocolType.Tcp
                    );
                    sListener1.Bind(ipEndPoint1);
                    sListener1.Listen(10);
                }
                else if (Sport.Text == "1002")
                {
                    sListener2 = new Socket(
                    ipAddr.AddressFamily,
                    SocketType.Stream,
                    ProtocolType.Tcp
                    );
                    sListener2.Bind(ipEndPoint2);
                    sListener2.Listen(10);
                }
                else if (Sport.Text == "1003")
                {
                    sListener3 = new Socket(
                   ipAddr.AddressFamily,
                   SocketType.Stream,
                   ProtocolType.Tcp
                   );
                    sListener3.Bind(ipEndPoint3);
                    sListener3.Listen(10);
                }
                else if (Sport.Text == "1004")
                {
                    sListener4 = new Socket(
                    ipAddr.AddressFamily,
                    SocketType.Stream,
                    ProtocolType.Tcp
                    );
                    sListener4.Bind(ipEndPoint4);
                    sListener4.Listen(10);
                }

                label3.Text = "Server started.";
                statusLabel.Text = "READY";
                button1.Enabled = false;
            }
            catch (Exception exc) { MessageBox.Show(exc.ToString()); }
        }

        //connect button
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                IPEndPoint ipEndPoint = null;
                IPEndPoint ipEndPoint1 = null;
                IPEndPoint ipEndPoint2 = null;
                IPEndPoint ipEndPoint3 = null;
                IPEndPoint ipEndPoint4 = null;
                // Create one SocketPermission for socket access restrictions
                SocketPermission permission = new SocketPermission(
                    NetworkAccess.Connect,    // Connection permission
                    TransportType.Tcp,        // Defines transport types
                    "",                       // Gets the IP addresses
                    SocketPermission.AllPorts // All ports
                    );

                // Ensures the code to have permission to access a Socket
                permission.Demand();

                // Resolves a host name to an IPHostEntry instance
                IPHostEntry ipHost = Dns.GetHostEntry("");

                // Gets first IP address associated with a localhost

                IPAddress ipAddr = ipHost.AddressList[0];

                // Creates a network endpoint
                if (Cport.Text == "1000")
                {
                     ipEndPoint = new IPEndPoint(ipAddr, Convert.ToInt32(Cport.Text));
                }else if (Cport.Text == "1001")
                {
                     ipEndPoint1 = new IPEndPoint(ipAddr, Convert.ToInt32(Cport.Text));
                }
                else if (Cport.Text == "1002")
                {
                     ipEndPoint2 = new IPEndPoint(ipAddr, Convert.ToInt32(Cport.Text));
                }
                else if (Cport.Text == "1003")
                {
                     ipEndPoint3 = new IPEndPoint(ipAddr, Convert.ToInt32(Cport.Text));
                }
                else if (Cport.Text == "1004")
                {
                     ipEndPoint4 = new IPEndPoint(ipAddr, Convert.ToInt32(Cport.Text));
                }

                if (Cport.Text == "1000")//A
                {
                    // Create one Socket object to setup Tcp connection
                    senderSock = new Socket(
                        ipAddr.AddressFamily,// Specifies the addressing scheme
                        SocketType.Stream,   // The type of socket
                        ProtocolType.Tcp     // Specifies the protocols
                        );
                    senderSock.NoDelay = false;   // Using the Nagle algorithm
                    // Establishes a connection to a remote host
                    senderSock.Connect(ipEndPoint);
                    statusLabel.Text = "Socket connected to " + senderSock.RemoteEndPoint.ToString();
                }
                else if (Cport.Text == "1001")//B
                {
                    senderSock1 = new Socket(
                        ipAddr.AddressFamily,
                        SocketType.Stream,
                        ProtocolType.Tcp
                        );
                    senderSock1.NoDelay = false;
                    senderSock1.Connect(ipEndPoint1);
                    statusLabel.Text = "Socket connected to " + senderSock1.RemoteEndPoint.ToString();
                }
                else if (Cport.Text == "1002")//C
                {
                    senderSock2 = new Socket(
                        ipAddr.AddressFamily,
                        SocketType.Stream,
                        ProtocolType.Tcp
                        );
                    senderSock2.NoDelay = false;
                    senderSock2.Connect(ipEndPoint2);
                    statusLabel.Text = "Socket connected to " + senderSock2.RemoteEndPoint.ToString();
                }
                else if (Cport.Text == "1003")//D
                {
                    senderSock3 = new Socket(
                        ipAddr.AddressFamily,
                        SocketType.Stream,
                        ProtocolType.Tcp
                        );
                    senderSock3.NoDelay = false;
                    senderSock3.Connect(ipEndPoint3);
                    statusLabel.Text = "Socket connected to " + senderSock3.RemoteEndPoint.ToString();
                }
                else if (Cport.Text == "1004")//E
                {
                    senderSock4 = new Socket(
                        ipAddr.AddressFamily,
                        SocketType.Stream,
                        ProtocolType.Tcp
                        );
                    senderSock4.NoDelay = false;
                    senderSock4.Connect(ipEndPoint4);
                    statusLabel.Text = "Socket connected to " + senderSock4.RemoteEndPoint.ToString();
                }
               button2.Enabled = false;
            }
            catch (Exception exc) { MessageBox.Show(exc.ToString()); }

            label3.Text = "wait...";
            Thread.Sleep(4000);
            send_st();
        }

And here is my code where I get an Error in "Send(handler1, status);"
The error is: "Object reference not set to an instance of an object"

//send status from clnt to server
        public void sendCToS(String str)
        {
            try
            {
                // Sending message
                //<Client Quit> is the sign for end of data
                byte[] msg = Encoding.Unicode.GetBytes(str + "<Client Quit>");
                // Sends data to a connected Socket.
                //send status from client to server
                int bytesSend = senderSock.Send(msg);//receiver server tasmim giri va response send mikone

            }
            catch (Exception exc) { MessageBox.Show(exc.ToString()); }
        }

        //it send hungry status from both to both!
        public void send_st()
        {
            // Resolves a host name to an IPHostEntry instance
            IPHostEntry ipHost = Dns.GetHostEntry("");
            // Gets first IP address associated with a localhost
            IPAddress ipAddr = ipHost.AddressList[0];

            Random rnd = new Random();
            int delay = rnd.Next(2000, 5000);
            while (true)
            {
                //System.Threading.Thread.Sleep(2000);
                statusLabel.Text = status;
                statusLabel.ForeColor = System.Drawing.Color.Blue;
                Thread.Sleep(delay);

                if (Sport.Text == "1000")//A
                {
                    status = "hungry";
                    statusLabel.Text = "HUNGRY";
                    statusLabel.ForeColor = System.Drawing.Color.Red;
                    //send status from server to clint
                    Send(handler1, status);
                    //send status from clnt to server
                    sendCToS(status);
                    label3.Text = "status Sent to left and right";
                }
                else if (Sport.Text == "1001")//B
                {
                    Thread.Sleep(2000);
                    status = "hungry";
                    statusLabel.Text = "HUNGRY";
                    statusLabel.ForeColor = System.Drawing.Color.Red;
                    //send status from server to clint
                    Send(handler2, status);
                    //send status from clnt to server
                    sendCToS(status);
                    label3.Text = "status Sent to left and right";
                }
                else if (Sport.Text == "1002")//C
                {
                    status = "hungry";
                    statusLabel.Text = "HUNGRY";
                    statusLabel.ForeColor = System.Drawing.Color.Red;
                    //send status from server to clint
                    Send(handler3, status);
                    //send status from clnt to server
                    sendCToS(status);
                    label3.Text = "status Sent to left and right";
                }
                else if (Sport.Text == "1003")//D
                {
                    Thread.Sleep(2000);
                    status = "hungry";
                    statusLabel.Text = "HUNGRY";
                    statusLabel.ForeColor = System.Drawing.Color.Red;
                    //send status from server to clint
                    Send(handler4, status);
                    //send status from clnt to server
                    sendCToS(status);
                    label3.Text = "status Sent to left and right";
                }
                else if (Sport.Text == "1004")//E
                {
                    Thread.Sleep(3000);
                    status = "hungry";
                    statusLabel.Text = "HUNGRY";
                    statusLabel.ForeColor = System.Drawing.Color.Red;
                    //send status from server to clint
                    Send(handler5, status);
                    //send status from clnt to server
                    sendCToS(status);
                    label3.Text = "status Sent to left and right";
                }

            }
        }

        //server side
        // Thread signal.
        public static ManualResetEvent allDone = new ManualResetEvent(false);

        public void AcceptCallback(IAsyncResult ar)
        {
            Socket listener = null;
            // A new Socket to handle remote host communication
            Socket handler = null;
            try
            {
                // Receiving byte array
                byte[] buffer = new byte[1024];
                // Get Listening Socket object
                listener = (Socket)ar.AsyncState;
                // Create a new socket
                handler = listener.EndAccept(ar);

                // Using the Nagle algorithm
                handler.NoDelay = false;

                StateObject state = new StateObject();

                // Begins to asynchronously receive data
                handler.BeginReceive(
                    buffer,        // An array of type Byt for received data
                    0,             // The zero-based position in the buffer
                    buffer.Length, // The number of bytes to receive
                    0,// Specifies send and receive behaviors
                    new AsyncCallback(ReceiveCallback),//An AsyncCallback delegate
                    state            // Specifies infomation for receive operation
                    );

            }
            catch (Exception exc) { MessageBox.Show(exc.ToString()); }
        }

        public void ReceiveCallback(IAsyncResult ar)
        {
            String response = "ok";
            try
            {
                // Retrieve the state object and the handler socket
                // from the asynchronous state object.
                StateObject state = (StateObject)ar.AsyncState;
                Socket handler = state.workSocket;

                // Read data from the client socket.
                int bytesRead = handler.EndReceive(ar);

                // Received message
                string content = string.Empty;

                if (bytesRead > 0)
                {
                    // There  might be more data, so store the data received so far.
                    state.sb.Append(Encoding.ASCII.GetString(
                        state.buffer, 0, bytesRead));

                    // Check for end-of-file tag. If it is not there, read
                    // more data.
                    content = state.sb.ToString();
                    if (content.IndexOf("<Client Quit>") > -1)
                    {
                        // All the data has been read from the client
                        label3.Text = content;
                    }
                    else {
                        // Not all data received. Get more.
                        handler.BeginReceive(state.buffer, 0,StateObject.BufferSize, 0,
                        new AsyncCallback(ReceiveCallback), state);
                    }

And this is the rest of the server side functions:

//func for echo back to client
        private void Send(Socket handler, String data)
        {
            // Convert the string data to byte data using ASCII encoding.
            byte[] byteData = Encoding.ASCII.GetBytes(data);

            // Begin sending the data to the remote device.
            handler.BeginSend(byteData, 0, byteData.Length, 0,
                new AsyncCallback(SendCallback), handler);
        }

        public void SendCallback(IAsyncResult ar)
        {

            try
            {
                // A Socket which has sent the data to remote host
                Socket handler = (Socket)ar.AsyncState;
                // The number of bytes sent to the Socket
                int bytesSend = handler.EndSend(ar);
                label3.Text = "Sent {0} bytes to Client" + bytesSend;
            }
            catch (Exception exc) { MessageBox.Show(exc.ToString()); }

Body:
I belive the problem is with this line:
senderSock.Send(msg);

You never instantiated the senderSock, you only declared it.
try this:

 senderSock= new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
senderSock.Send(msg);


问:
How can I save an async return value in a variable?
```<code>var bcrypt = require('bcryptjs');
var password = "Bacon";
var securePassword;
bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash(bacon, salt, function(err, hash) {
        securePassword = hash
    });
});
console.log(securePassword)
</code>```

This returns undefined probably due to Async. How can I store the hash value, in the variable securePassword?

答:
You are dealing with asynchronous function.

GOOD

```<code>var securePassword;

bcrypt.genSalt(10, function(err, salt) {
    if (err) return callback(err);

    bcrypt.hash(bacon, salt, function(err, hash) {
        securePassword = hash;

        console.log(securePassword);
    });
});
</code>```

GOOD

```<code>function generateSalt(callback) {
    bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(bacon, salt, callback);
    });
}

generateSalt((err, hash) => {
  if (err) // Handle error

  console.log(hash);
});
</code>```

Body:
var bcrypt = require('bcryptjs');
var password = "Bacon";
var securePassword;
bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash(bacon, salt, function(err, hash) {
        securePassword = hash
    });
});
console.log(securePassword)

This returns undefined probably due to Async. How can I store the hash value, in the variable securePassword?

Body:
You are dealing with asynchronous function.

GOOD

var securePassword;

bcrypt.genSalt(10, function(err, salt) {
    if (err) return callback(err);

    bcrypt.hash(bacon, salt, function(err, hash) {
        securePassword = hash;

        console.log(securePassword);
    });
});

GOOD

function generateSalt(callback) {
    bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(bacon, salt, callback);
    });
}

generateSalt((err, hash) => {
  if (err) // Handle error

  console.log(hash);
});


问:
Remove 1 second delay on countdown displaying
Here is my code: https://jsfiddle.net/3kb337bt/

```<code><span>Hurry, Sale Ends In: </span><div id="countdown"></div>
</code>```

When the page loads the timer doesn't display right away. How can I remove the 1-2 second delay and make it display immediately?

答: This is due to your showRemaining() function not being called on page load. It will take the specified delay (1000 in this case) until it gets called the first time. You can stop this by changing the delay since the countdown isn't affected by it.

Body:
Here is my code: https://jsfiddle.net/3kb337bt/

Hurry, Sale Ends In:

When the page loads the timer doesn't display right away. How can I remove the 1-2 second delay and make it display immediately?


答:
You are storing the value of hash to securePassword in the  bcrypt.hash callback function which is correct.. but as that is a callback function your console.log will execute before securePassword is assigned..

solution to this is to do your logic in that callback handle.

You can also use different methods like promise to resolve it you can read more from MDN

var bcrypt = require('bcryptjs');
var password = "Bacon";
var securePassword;
bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash(bacon, salt, function(err, hash) {
        securePassword = hash
        dologic()
        //console.log(securePassword)
        //or have a function with this statement
    });
});
function dologic(){
console.log(securePassword)
}```

Title: How can I save an async return value in a variable?


问:
Connect AD FS 3.0 to Shibboleth via SamAccountName Name ID
I need to connect an AD FS 3.0 identity provider (idP) to a Shibboleth service provider / relying party I don't control. Unfortunatley, AD FS and Shibboleth don't quite use the same format for claims/attributes.

There's a lot of information out there one the web about this, and the need for two rules (one to retrieve the value from Active Directory, and one to transform it to match what Shibboleth expects), but much of it is written for AD FS 2.0 or uses the e-mail address as the Name ID (I really need SamAccountName for this).

How can I get my AD FS idP to produce a claim using the windows-account-name that Shibboleth will accept?

答:
I finally found the answer here:

https://cccnext.jira.com/wiki/spaces/CSF/pages/147817839/Attributes+for+the+Proxy+AD+FS

That link lists custom rule pairs for a number of Active Directory fields, including SamAccountName / windows-account-name.

The rules I used look like this:

```<code>@Rulename="Get sAMAaccountName"

c:[Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname", Issuer == "AD AUTHORITY"]
 => add(store = "Active Directory", types = ("urn:oid:1.2.840.113556.1.4.221"), query = ";sAMAccountName;{0}", param = c.Value);

@Rulename="Convert sAMAccountName / uid xml"

c:[Type == "urn:oid:1.2.840.113556.1.4.221"]
 => issue(Type = "urn:oid:0.9.2342.19200300.100.1.1", Value = c.Value, Properties["http://schemas.xmlsoap.org/ws/2005/05/identity/claimproperties/attributename"] = "urn:oasis:names:tc:SAML:2.0:attrname-format:uri");
</code>```

These were included as part of a PowerShell script, but you can add them via the AD FS interface by adding custom claim rules.

This may still require a change on the Shibboleth end. Before I got this far, a service tech on the other end reported seeing attributes that were excluded, and making a change to allow that attribute. However, that was a different set of rules. I don't know if this set of rules is taking advantage of that change or not.

Body:
I finally found the answer here:

https://cccnext.jira.com/wiki/spaces/CSF/pages/147817839/Attributes+for+the+Proxy+AD+FS

That link lists custom rule pairs for a number of Active Directory fields, including SamAccountName / windows-account-name.

The rules I used look like this:

@Rulename="Get sAMAaccountName"

c:[Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname", Issuer == "AD AUTHORITY"]
 => add(store = "Active Directory", types = ("urn:oid:1.2.840.113556.1.4.221"), query = ";sAMAccountName;{0}", param = c.Value);

@Rulename="Convert sAMAccountName / uid xml"

c:[Type == "urn:oid:1.2.840.113556.1.4.221"]
 => issue(Type = "urn:oid:0.9.2342.19200300.100.1.1", Value = c.Value, Properties["http://schemas.xmlsoap.org/ws/2005/05/identity/claimproperties/attributename"] = "urn:oasis:names:tc:SAML:2.0:attrname-format:uri");

These were included as part of a PowerShell script, but you can add them via the AD FS interface by adding custom claim rules.

This may still require a change on the Shibboleth end. Before I got this far, a service tech on the other end reported seeing attributes that were excluded, and making a change to allow that attribute. However, that was a different set of rules. I don't know if this set of rules is taking advantage of that change or not.


问:
Grails UrlMappings to external remote files
In Grails, I'm trying to make it so that any requests to /images/* actually goes to another website on another host.

I know how to do it in Apache with Mod Rewrite, but how can I achieve this with UrlMappings?

I want

/images/*  to go to http://somedomain/images/*

答:
You can't directly. You'll have to map it to a controller which will in turn redirect to the desired location. Something like:

```<code>"/images/$urlTail**"  (controller: "image", action: "external")
</code>```

And then in the external method of the ImageController:

```<code>def actualUri = request.forwardURI.replace("/images/", "")
redirect "http://example.com/" + actualUri;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You can't directly. You'll have to map it to a controller which will in turn redirect to the desired location. Something like:

"/images/$urlTail**"  (controller: "image", action: "external")

And then in the external method of the ImageController:

def actualUri = request.forwardURI.replace("/images/", "")
redirect "http://example.com/" + actualUri;


问:
How to change output format of material 2 date-picker
I am using angular material 2 Date-Picker component

The only string input it understands is in ISO date format

Ex. "2017-11-13T10:39:28.300Z"

But i want to patch my form control with locale date value

Ex. "11/13/2017, 4:09:46 PM"

So that it output the later format and even expects this format.

How can i do this? Is there a way to not use ISO but custom formats?

Some Thoughts:

Should i write customDateAdaptor?

Update:

https://stackblitz.com/edit/angular-material-moment-adapter-example-bqvm2f

i have tried to implement custom dateAdaptor by extending nativeDateAdaptor

答:
You need to create a class extending NativeDateAdapter (from "@angular/material/core")

If you override the format function you will change the way the date is displayed on the input after selecting a date.
The parse function is called when you edit the input value manually, to display a valid date.

See the 2nd comment for more details: https://github.com/angular/material2/issues/5722

EDIT:

I couldn't find a way to format the output so I've wrapped the material datepicker component to a custom component.

This custom component has a 2 way binding on a property to get the date:
@Input() selectedValue and @Output() selectedValueChange: EventEmitter<any> = new EventEmitter<any>();

A private _selectedValue; is set on ngInit, it will contain the datepicker date.

Then in the template, the html datepicker input element has [(ngModel)]="_selectedValue" (dateChange)="onChange($event)"

The onChange function gets the datepicker value _selectedValue, formats it and emit it to selectedValueChange.

The final component looks like this:

```<code>import { Component, OnInit, Input, Output, EventEmitter } from "@angular/core";
import {
  DateAdapter,
  NativeDateAdapter,
  MAT_DATE_FORMATS,
  MAT_DATE_LOCALE
} from "@angular/material/core";
import * as moment from "moment";

const CUSTOM_DATE_FORMATS = {
  parse: {
    dateInput: { month: "short", year: "numeric", day: "numeric" }
  },
  display: {
    dateInput: "input",
    monthYearLabel: { year: "numeric", month: "short" },
    dateA11yLabel: { year: "numeric", month: "long", day: "numeric" },
    monthYearA11yLabel: { year: "numeric", month: "long" }
  }
};
const dateFormat = "YYYY-MM-DD";
// date adapter formatting material2 datepickers label when a date is selected
class AppDateAdapter extends NativeDateAdapter {
  format(date: Date, displayFormat: Object): string {
    if (displayFormat === "input") {
      return moment(date).format(dateFormat);
    } else {
      return date.toDateString();
    }
  }
}
@Component({
  selector: "datepicker",
  templateUrl: "./datepicker.component.html",
  styleUrls: ["./datepicker.component.scss"],
  providers: [
    { provide: MAT_DATE_FORMATS, useValue: CUSTOM_DATE_FORMATS },
    { provide: DateAdapter, useClass: AppDateAdapter }
  ]
})
export class DatepickerComponent implements OnInit {
  @Input() placeholder;
  @Output() onFilter: EventEmitter<any> = new EventEmitter<any>();
  @Input() selectedValue;
  @Output() selectedValueChange: EventEmitter<any> = new EventEmitter<any>();

  private _selectedValue;
  constructor() {}

  ngOnInit() {
    this._selectedValue = this.selectedValue;
  }

  onChange($event) {
    this.selectedValue = this.updateDate($event.value);
    this.onFilter.emit(this.selectedValue);
  }

  updateDate(date) {
    let formatedDate;
    if (date !== undefined) {
      formatedDate = moment(date).format(dateFormat);
    }
    this.selectedValueChange.emit(formatedDate);
    return formatedDate;
  }
}
</code>```

Body:
You need to create a class extending NativeDateAdapter (from "@angular/material/core")

If you override the format function you will change the way the date is displayed on the input after selecting a date.
The parse function is called when you edit the input value manually, to display a valid date.

See the 2nd comment for more details: https://github.com/angular/material2/issues/5722

EDIT:

I couldn't find a way to format the output so I've wrapped the material datepicker component to a custom component.

This custom component has a 2 way binding on a property to get the date:
@Input() selectedValue and @Output() selectedValueChange: EventEmitter<any> = new EventEmitter<any>();

A private _selectedValue; is set on ngInit, it will contain the datepicker date.

Then in the template, the html datepicker input element has [(ngModel)]="_selectedValue" (dateChange)="onChange($event)"

The onChange function gets the datepicker value _selectedValue, formats it and emit it to selectedValueChange.

The final component looks like this:

import { Component, OnInit, Input, Output, EventEmitter } from "@angular/core";
import {
  DateAdapter,
  NativeDateAdapter,
  MAT_DATE_FORMATS,
  MAT_DATE_LOCALE
} from "@angular/material/core";
import * as moment from "moment";

const CUSTOM_DATE_FORMATS = {
  parse: {
    dateInput: { month: "short", year: "numeric", day: "numeric" }
  },
  display: {
    dateInput: "input",
    monthYearLabel: { year: "numeric", month: "short" },
    dateA11yLabel: { year: "numeric", month: "long", day: "numeric" },
    monthYearA11yLabel: { year: "numeric", month: "long" }
  }
};
const dateFormat = "YYYY-MM-DD";
// date adapter formatting material2 datepickers label when a date is selected
class AppDateAdapter extends NativeDateAdapter {
  format(date: Date, displayFormat: Object): string {
    if (displayFormat === "input") {
      return moment(date).format(dateFormat);
    } else {
      return date.toDateString();
    }
  }
}
@Component({
  selector: "datepicker",
  templateUrl: "./datepicker.component.html",
  styleUrls: ["./datepicker.component.scss"],
  providers: [
    { provide: MAT_DATE_FORMATS, useValue: CUSTOM_DATE_FORMATS },
    { provide: DateAdapter, useClass: AppDateAdapter }
  ]
})
export class DatepickerComponent implements OnInit {
  @Input() placeholder;
  @Output() onFilter: EventEmitter<any> = new EventEmitter<any>();
  @Input() selectedValue;
  @Output() selectedValueChange: EventEmitter<any> = new EventEmitter<any>();

  private _selectedValue;
  constructor() {}

  ngOnInit() {
    this._selectedValue = this.selectedValue;
  }

  onChange($event) {
    this.selectedValue = this.updateDate($event.value);
    this.onFilter.emit(this.selectedValue);
  }

  updateDate(date) {
    let formatedDate;
    if (date !== undefined) {
      formatedDate = moment(date).format(dateFormat);
    }
    this.selectedValueChange.emit(formatedDate);
    return formatedDate;
  }
}


问:
How can I encode text data as features for ML algorithms in Python?
I have a csv file which have columns filled with text data. How can I replace them with constant data so I can apply machine learning algorithm on that dataset.
Dataset Example: Date, Name, Color Name, User Name and Product Name.</p>

答:
You are trying to categorize your data. Try the following:

Example 1: For the color name and product name assuming there are only a few types, you can map as follows:

```<code># Color_name mapping
color_mapping = {"red": 1, "yellow": 2, "blue": 3, "green": 4, "pink": 5}
dataset['color_name'] = dataset['color_name'].map(color_mapping)
# Product_name mapping
product_mapping = {"product1": 1, "product2": 2, "product3": 3, "product4": 4, "product5": 5}
dataset['product_name'] = dataset['product_name'].map(product_mapping)
</code>```

Example 2: For user_name if they cannot be categorized as above, you can do the following:

Try extracting titles from the name.

Ex: Names starting with titles Mr., Ms., Mrs. etc can be extracted and can be grouped accordingly

```<code>title_mapping = {"Mr": 1, "Miss": 2, "Mrs": 3}
dataset['user_name'] = dataset['user_name'].map(title_mapping)
</code>```

Example 3: For date, you can group them as dates belonging to different years or months or for some particular period etc.

Body:
You are trying to categorize your data. Try the following:

Example 1: For the color name and product name assuming there are only a few types, you can map as follows:

# Color_name mapping
color_mapping = {"red": 1, "yellow": 2, "blue": 3, "green": 4, "pink": 5}
dataset['color_name'] = dataset['color_name'].map(color_mapping)
# Product_name mapping
product_mapping = {"product1": 1, "product2": 2, "product3": 3, "product4": 4, "product5": 5}
dataset['product_name'] = dataset['product_name'].map(product_mapping)

Example 2: For user_name if they cannot be categorized as above, you can do the following:

Try extracting titles from the name.

Ex: Names starting with titles Mr., Ms., Mrs. etc can be extracted and can be grouped accordingly

title_mapping = {"Mr": 1, "Miss": 2, "Mrs": 3}
dataset['user_name'] = dataset['user_name'].map(title_mapping)

Example 3: For date, you can group them as dates belonging to different years or months or for some particular period etc.


问:
System.Net.Mail.MailAddress send to multiple emails with one parameter
I've just switched from the deprecated System.Web.Mail.MailAddress to System.Net.Mail.MailAddress, but it doesn't seem to be particularly flexible when passing in a parameter holding multiple addresses when using the new System.Net.Mail.MailAddress.To.Add.

```<code>string emailAdd= "email1@emailus.com; email2@emailus.com";

System.Net.Mail.MailAddress.To.Add(emailAdd);
</code>```

In the above example, email2@emailus.com is emailed successfully, but email1@emailus.com is not.  I really need a way to do this since my addresses are defined in another class and passed to an email() method via a parameter.  I'm simply not passing five parameters for 5 separate emails.  Or indeed one and splicing on my end, .Web version is proving to be way more versatile.

This question is not a duplicate of the suggested one.  The answer to the "duplicate" is add them individually, I want to add multiple addresses simultaneously.  Since there is a way to do this, this question is more relevant than the one I'm accused of duplicating.

答:
According to MSDN, the .Add() method accepts a string of comma-delimited addresses, rather than semicolon-delimited.

Therefore either changing the parameter that you are passing in to a comma-delimited string, if possible, or adding functionality to your email method to replace the semicolons with commas should resolve the issue.

ContentLicense: CC BY-SA 4.0

Body:
I've just switched from the deprecated System.Web.Mail.MailAddress to System.Net.Mail.MailAddress, but it doesn't seem to be particularly flexible when passing in a parameter holding multiple addresses when using the new System.Net.Mail.MailAddress.To.Add.

string emailAdd= "email1@emailus.com; email2@emailus.com";

System.Net.Mail.MailAddress.To.Add(emailAdd);

In the above example, email2@emailus.com is emailed successfully, but email1@emailus.com is not.  I really need a way to do this since my addresses are defined in another class and passed to an email() method via a parameter.  I'm simply not passing five parameters for 5 separate emails.  Or indeed one and splicing on my end, .Web version is proving to be way more versatile.

This question is not a duplicate of the suggested one.  The answer to the "duplicate" is add them individually, I want to add multiple addresses simultaneously.  Since there is a way to do this, this question is more relevant than the one I'm accused of duplicating.


问:
"Can not find variable: X" error while using fetch from a URL
In React native, I would like to retrieve the js data from the web URL and use it. Here is my code:

```<code>export default class Test extends Component {

    constructor(props) {
        super();
        this.subscription = 0;
        this.state = {
        };
        changePage = props.cb;
        console.log("props", props);

      render(){

        return (
            <Container  ref="park-places-ref">

                <View style={styles.viewmain}>

                <View style={styles.viewborder}>

                </View>

          fetch('https://online.ssm.it/php/mobile/parkinfo') // Call the fetch function passing the url of the API as a parameter
          .then((response) => response.json()) // Transform the data into json
            data={response.body}
          })
            .catch(function() {
                // This is where you run code if the server returns any errors
            });

                <FlatList
                ItemSeparatorComponent={ () => <View style={ styles.rowSep } /> }

                Mydata={data}

                renderItem={

                    ({item}) => (
                    <View style={styles.row}>
                        <View style={styles.circle}   backgroundColor= {item.color}/>
                        <View style={styles.column}>
                            <Text style={styles.itemBold}>{item.extensioname}</Text>
                            <Text style={styles.itemNormal}>{item.free}</Text>

                            <Text style={styles.itemBold}>{item.freeplaces}</Text>

                        </View>
                    </View>
                    )
                }
                keyExtractor={item => item.extensioname}
                />
                </View>

            </Container>
        );
    }
}
</code>```

}

Whenever I tried to retrieve the body of the data, I couldn't retrieve it and it shows me an error that:
I need to use the data in table as below:

Can not find variable: response

Can you help me to solve the problem? Please let me know if you need any more information.

答:
You actually need one more chain on your fetch() function call.

```<code>fetch( ... )
.then((response)=>response.json())
.then((resp)=> data={resp})
.catch( ... );
</code>```

Check out the docs: https://facebook.github.io/react-native/docs/network.html

Body:
In React native, I would like to retrieve the js data from the web URL and use it. Here is my code:

export default class Test extends Component {

    constructor(props) {
        super();
        this.subscription = 0;
        this.state = {
        };
        changePage = props.cb;
        console.log("props", props);

      render(){

        return (
            <Container  ref="park-places-ref">

                <View style={styles.viewmain}>

                <View style={styles.viewborder}>

                </View>

          fetch('https://online.ssm.it/php/mobile/parkinfo') // Call the fetch function passing the url of the API as a parameter
          .then((response) => response.json()) // Transform the data into json
            data={response.body}
          })
            .catch(function() {
                // This is where you run code if the server returns any errors
            });

                <FlatList
                ItemSeparatorComponent={ () => <View style={ styles.rowSep } /> }

                Mydata={data}

                renderItem={

                    ({item}) => (
                    <View style={styles.row}>
                        <View style={styles.circle}   backgroundColor= {item.color}/>
                        <View style={styles.column}>
                            <Text style={styles.itemBold}>{item.extensioname}</Text>
                            <Text style={styles.itemNormal}>{item.free}</Text>

                            <Text style={styles.itemBold}>{item.freeplaces}</Text>

                        </View>
                    </View>
                    )
                }
                keyExtractor={item => item.extensioname}
                />
                </View>

            </Container>
        );
    }
}

}

Whenever I tried to retrieve the body of the data, I couldn't retrieve it and it shows me an error that:
I need to use the data in table as below:

Can not find variable: response

Can you help me to solve the problem? Please let me know if you need any more information.

Body:
You actually need one more chain on your fetch() function call.

fetch( ... )
.then((response)=>response.json())
.then((resp)=> data={resp})
.catch( ... );

Check out the docs: https://facebook.github.io/react-native/docs/network.html


问:
For high scalability & performance needs, is it preferable to have C++ or Java implementation at the backend of a PHP application?
For high scalability & performance needs for a social portal, is it advisable to have C++ or Java implementation at the backend of an PHP application ?

What are the benefits & trade-offs of the same ?

答:
In raw performance terms, C++ will get you a fair bit further than Java or PHP, and slightly further than C#. By this I mean that if you implement the same algorithm in these different languages you are most likely to see the best performance from C++ (although it will depend exactly on what you're doing and how you do it - a different language on its own is not a magic bullet; you need to learn how to make the best use of that language, which can take years).

As @spender has said, using well thought out algorithms and architecture will usually give a greater gain in performance and a much greater gain in scalability than simply switching to a different language might achieve. Performance is fundamentally about being efficient (minimising your usage of resources like bandwidth, memory, disk and CPU) and scalabilty is primarily about making things work well in parallel (minimising contention for resources like data, bandwidth, memory and CPU, and minimising the need for different parts of your system to communicate with each other)

As @Kugel said, if you have a truly scalable architecture then you can to some extent just throw more hardware at the problem, which might initially be a cheaper approach than rewriting everything in a different language. However, if your site is successful, making your code as efficient as possible will reduce your hardware and running costs.

Another consideration may be development/maintainability related - if you are an expert in PHP and a newbie at C++, you may well squeeze more out of PHP than you can out of C++. You have to consider the whole picture and work out what is the most "commercially viable" solution, not just what is the theoretically highest performing one. Or you may find that your "thrown together and works surprisingly well" PHP solution is up and running in a week while your highly optimised C++ never quite gets finished.


问:
Array multiplication table
I want understand more about arrays. I came up with this question of creating multiplication table that would display this way

```<code>1  2  3  4  5

2  4  6  8  10

3  6  9  12 15

4  8  12 16 20

5  10 15 20 25
</code>```

I though of using arrays this way

```<code>int myArray[] = {1,2,3,4,5};
int myArray2[] = {1,2,3,4,5}
</code>```

The first array would serve as the horizontal set and the 2nd would be the vertical.
The problem is I dont know how exactly am I going to multiply each index and display them as a multiplication table.

答:
Below are some examples that you should be able to peak through to get more knowledge on arrays and two dimensional arrays</p>

```<code>//X HEADING PLUS MATH
    for (int i =0; i < 13; i ++){
        System.out.print(i + "\t");
    }
    System.out.print("\n");

    //MATH PORTION PLUS HEADING
    for (int y =1; y < 13; y++){
        System.out.print(y + "\t");
        for (int x=1; x<13; x++){
            System.out.print((x*y) + "\t");
        }
        System.out.print("\n");
    }

    System.out.print("\n");

    //MATH PORTION
    //

    for (int y =1; y < 13; y++){
        for (int x=1; x<11; x++){
            System.out.print((x*y) + "\t");
        }
        System.out.print("\n");
    }

    System.out.print("\n");*/

    //************************************//
    //EXAMPLE USING TWO DIMENSIONAL ARRAY //
    //W/OUT HEADERS***********************//
    //************************************//
    //JFrame frame = new JFrame ("HW09");
    //int length = Integer.parseInt(JOptionPane.showInputDialog(frame, "Enter the multiplication table length")) + 1;
    int length = 13;
    int[][] multi = new int[length][length];//created 2 dim array

    //formatting heading
    for (int i = 0; i<length; i++) {
    multi[0][i] = i;
    multi[i][0] = i;
    }
    //fills array with values
    for (int yPos = 1; yPos<length; yPos++){//loops through all y positions
        for ( int xPos =1; xPos < length; xPos++){//loops through x positions of y position
            multi[xPos][yPos] =(xPos)*(yPos);
        }
    }
    //prints out values
    for (int yPos = 0; yPos<length; yPos++){//loops through all y positions
        for ( int xPos =0; xPos < length; xPos++){//loops through horizontal positions of y position
            System.out.print(multi[xPos][yPos] + "\t");
        }
        System.out.print("\n");
    }

    System.out.print("\n");

    //************************************/
    //    EXAMPLE USING TWO ARRAYS        //
    //************************************//

    int[] y = new int[] {1,5,6,9};//array for x
    int[] x = new int[] {2,5,7,8,10};//array for y
    //prints out horizontal header
    System.out.print("x\t");
    for (int i =0; i < x.length; i ++){
        System.out.print(x[i] + "\t");
    }
    System.out.print("\n");
    //prints out y header and then does math
    for (int i =0; i < y.length; i ++){
        System.out.print(y[i] + "\t");
        //loop to do math for what above me
        for (int i2 =0; i2 < x.length; i2++ ){
            System.out.print((y[i] * x[i2]) + "\t");
        }
        System.out.print("\n");

    }
</code>```

Title: Array multiplication table

Body:
I want understand more about arrays. I came up with this question of creating multiplication table that would display this way

1  2  3  4  5

2  4  6  8  10

3  6  9  12 15

4  8  12 16 20

5  10 15 20 25

I though of using arrays this way

int myArray[] = {1,2,3,4,5};
int myArray2[] = {1,2,3,4,5}

The first array would serve as the horizontal set and the 2nd would be the vertical.
The problem is I dont know how exactly am I going to multiply each index and display them as a multiplication table.

Body:
Below are some examples that you should be able to peak through to get more knowledge on arrays and two dimensional arrays

//X HEADING PLUS MATH
    for (int i =0; i < 13; i ++){
        System.out.print(i + "\t");
    }
    System.out.print("\n");

    //MATH PORTION PLUS HEADING
    for (int y =1; y < 13; y++){
        System.out.print(y + "\t");
        for (int x=1; x<13; x++){
            System.out.print((x*y) + "\t");
        }
        System.out.print("\n");
    }

    System.out.print("\n");

    //MATH PORTION
    //

    for (int y =1; y < 13; y++){
        for (int x=1; x<11; x++){
            System.out.print((x*y) + "\t");
        }
        System.out.print("\n");
    }

    System.out.print("\n");*/

    //************************************//
    //EXAMPLE USING TWO DIMENSIONAL ARRAY //
    //W/OUT HEADERS***********************//
    //************************************//
    //JFrame frame = new JFrame ("HW09");
    //int length = Integer.parseInt(JOptionPane.showInputDialog(frame, "Enter the multiplication table length")) + 1;
    int length = 13;
    int[][] multi = new int[length][length];//created 2 dim array

    //formatting heading
    for (int i = 0; i<length; i++) {
    multi[0][i] = i;
    multi[i][0] = i;
    }
    //fills array with values
    for (int yPos = 1; yPos<length; yPos++){//loops through all y positions
        for ( int xPos =1; xPos < length; xPos++){//loops through x positions of y position
            multi[xPos][yPos] =(xPos)*(yPos);
        }
    }
    //prints out values
    for (int yPos = 0; yPos<length; yPos++){//loops through all y positions
        for ( int xPos =0; xPos < length; xPos++){//loops through horizontal positions of y position
            System.out.print(multi[xPos][yPos] + "\t");
        }
        System.out.print("\n");
    }

    System.out.print("\n");

    //************************************/
    //    EXAMPLE USING TWO ARRAYS        //
    //************************************//

    int[] y = new int[] {1,5,6,9};//array for x
    int[] x = new int[] {2,5,7,8,10};//array for y
    //prints out horizontal header
    System.out.print("x\t");
    for (int i =0; i < x.length; i ++){
        System.out.print(x[i] + "\t");
    }
    System.out.print("\n");
    //prints out y header and then does math
    for (int i =0; i < y.length; i ++){
        System.out.print(y[i] + "\t");
        //loop to do math for what above me
        for (int i2 =0; i2 < x.length; i2++ ){
            System.out.print((y[i] * x[i2]) + "\t");
        }
        System.out.print("\n");

    }


问:
Retrofit uploading a picture
I'm using Retrofit v.2.2.0 to upload a picture to my server but the server returns a null value stating no image has been uploaded. The logs shows the image is uploaded and the file name is correct when uploaded. What can be the problem yet it works in postman?

UploadProfilePicture.java

```<code>public class UploadProfilePicture extends ContextWrapper {

private GetOnUpload onUpload;
private File imageFile,filesDir,file;
private Uri fileUri;
private String profilePic = "profile_pic";
private String fileName;
private ParcelFileDescriptor parcelFileDescriptor;
private FileDescriptor fileDescriptor;
private  Bitmap profileImage;
private OutputStream os;
private OkHttpLogClientAPI okHttpLogClientAPI;
private GetOnUpload mInterfaceService;

public UploadProfilePicture(Context base) {
    super(base);

    okHttpLogClientAPI = new OkHttpLogClientAPI(getBaseContext());

    mInterfaceService = okHttpLogClientAPI.logger().create(GetOnUpload.class);

}

public void uploadPic(Uri fileUri,String fileName, final OnSetUploadProfilePic setOnUpload) {
    //Build Req estBodies for the map object and a MultipartBody.Part to encapsulate the prof_pic_drawer

    this.fileUri = fileUri;
    this.fileName = fileName;
    try {
        getBitmapFromUri();
    } catch (IOException e) {
        e.printStackTrace();
    }
    file = persistImage();

    RequestBody finalRequestBody = builder.build();
    RequestBody requestFile =
            RequestBody.create(MediaType.parse("multipart/form-data"), getBytesFromBitmap(profileImage));

    // MultipartBody.Part is used to send also the actual file name
    MultipartBody.Part body =
            MultipartBody.Part.createFormData("file", "avatar.jpg", requestFile);
        Call<ResponseUserModel> call = mInterfaceService.upload(body);

        call.enqueue(new Callback<ResponseUserModel>() {

            @Override
            public void onResponse(Call<Response> call, Response<Response> response) {

                if (response.isSuccessful()) {
                    setOnUpload.uploadMessage(response.body());

                } else {
                    Toast.makeText(getBaseContext(), getString(R.string.failed_to_upload), Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onFailure(Call<Response> call, Throwable t) {

                Toast.makeText(getBaseContext(), getString(R.string.failed_to_upload), Toast.LENGTH_SHORT).show();

            }
        });
    }
}

public static byte[] getBytesFromBitmap(Bitmap bitmap) {
    if (bitmap!=null) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
        return stream.toByteArray();
    }
    return null;
}

private MultipartBody.Part prepareFilePart() {

    //TODO: Use FileUtils to get the actual file by uri

    try {
        getBitmapFromUri();
        file = persistImage();

    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        RequestBody requestFile = RequestBody.create(
                MediaType.parse(getBaseContext().getContentResolver().getType(fileUri)), file);
            return MultipartBody.Part.createFormData("file", file.getName(), requestFile);

    } catch (NullPointerException e) {

        Toast.makeText(getBaseContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();

        return null;
    }

}

private RequestBody createPartFromString(String descriptionString) {
    return RequestBody.create(MultipartBody.FORM, descriptionString);
}

private void getBitmapFromUri() throws IOException {
    profileImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), fileUri);
}

private File persistImage() {
    filesDir = getFilesDir();
     imageFile = new File(filesDir, fileName + ".jpg");

    OutputStream os;
    try {
        os = new FileOutputStream(imageFile);
        profileImage.compress(Bitmap.CompressFormat.JPEG, 70, os);
        os.flush();
        os.close();
    } catch (Exception e) {
        Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
    }

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

GetOnUpload.java

```<code>public interface GetOnUpload {
 @Multipart
@POST(Constants.UPLOAD_URL)
Call<Response> upload(@Part MultipartBody.Part file);}
</code>```

Log

http://local.com/api/v1/avatar http/1.1
11-14 18:40:02.742 8851-9593/com.local.test D/OkHttp: Content-Type: multipart/form-data; boundary=d43da080-f2c3-4743-8cfd-9526cc0bd2f7
11-14 18:40:02.742 8851-9593/com.local.test D/OkHttp: Content-Length: 12424
11-14 18:40:02.743 8851-9593/com.local.test D/OkHttp: --d43da080-f2c3-4743-8cfd-9526cc0bd2f7
11-14 18:40:02.743 8851-9593/com.local.test D/OkHttp: Content-Disposition: form-data; name="file"; filename="avatar.jpg"
11-14 18:40:02.743 8851-9593/com.local.test D/OkHttp: Content-Type: multipart/form-data
11-14 18:40:02.743 8851-9593/com.local.test D/OkHttp: Content-Length: 12201
11-14 18:40:02.743 8851-9593/com.local.test D/OkHttp:
11-14 18:40:02.744 8851-9593/com.local.test D/OkHttp: --d43da080-f2c3-4743-8cfd-9526cc0bd2f7--
11-14 18:40:02.744 8851-9593/com.local.test D/OkHttp: --> END POST (12424-byte body)

11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: <-- 200 OK http://local.com/api/v1/avatar (587ms)
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: Server: nginx/1.10.3 (Ubuntu)
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: Content-Type: application/json
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: Transfer-Encoding: chunked
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: Connection: keep-alive
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: Cache-Control: no-cache, private
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: Date: Tue, 14 Nov 2017 15:40:03 GMT
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: X-RateLimit-Limit: 60
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: X-RateLimit-Remaining: 59
11-14 18:40:03.333 8851-9593/com.local.test D/OkHttp: {"user":"Failed","status":"Image file not uploaded"}

答:
This example worked for me</p>

```<code>//My data manager
public void doUpload(
    Context context,
    String url) {

    Uri uri = Uri.parse(url);
    File file = new File(getPath(context, uri));
    RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
    MultipartBody.Part body = MultipartBody.Part.createFormData("imageParameterName", file.getName(), reqFile);

    uploadService(body)

}

//REST service
@Multipart
@POST("upload.aspx")
Call<DefaultDTO> uploadService(@Part MultipartBody.Part image);
</code>```

Title: Retrofit uploading a picture

Body:
I'm using Retrofit v.2.2.0 to upload a picture to my server but the server returns a null value stating no image has been uploaded. The logs shows the image is uploaded and the file name is correct when uploaded. What can be the problem yet it works in postman?

UploadProfilePicture.java

public class UploadProfilePicture extends ContextWrapper {

private GetOnUpload onUpload;
private File imageFile,filesDir,file;
private Uri fileUri;
private String profilePic = "profile_pic";
private String fileName;
private ParcelFileDescriptor parcelFileDescriptor;
private FileDescriptor fileDescriptor;
private  Bitmap profileImage;
private OutputStream os;
private OkHttpLogClientAPI okHttpLogClientAPI;
private GetOnUpload mInterfaceService;

public UploadProfilePicture(Context base) {
    super(base);

    okHttpLogClientAPI = new OkHttpLogClientAPI(getBaseContext());

    mInterfaceService = okHttpLogClientAPI.logger().create(GetOnUpload.class);

}

public void uploadPic(Uri fileUri,String fileName, final OnSetUploadProfilePic setOnUpload) {
    //Build Req estBodies for the map object and a MultipartBody.Part to encapsulate the prof_pic_drawer

    this.fileUri = fileUri;
    this.fileName = fileName;
    try {
        getBitmapFromUri();
    } catch (IOException e) {
        e.printStackTrace();
    }
    file = persistImage();

    RequestBody finalRequestBody = builder.build();
    RequestBody requestFile =
            RequestBody.create(MediaType.parse("multipart/form-data"), getBytesFromBitmap(profileImage));

    // MultipartBody.Part is used to send also the actual file name
    MultipartBody.Part body =
            MultipartBody.Part.createFormData("file", "avatar.jpg", requestFile);
        Call<ResponseUserModel> call = mInterfaceService.upload(body);

        call.enqueue(new Callback<ResponseUserModel>() {

            @Override
            public void onResponse(Call<Response> call, Response<Response> response) {

                if (response.isSuccessful()) {
                    setOnUpload.uploadMessage(response.body());

                } else {
                    Toast.makeText(getBaseContext(), getString(R.string.failed_to_upload), Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onFailure(Call<Response> call, Throwable t) {

                Toast.makeText(getBaseContext(), getString(R.string.failed_to_upload), Toast.LENGTH_SHORT).show();

            }
        });
    }
}

public static byte[] getBytesFromBitmap(Bitmap bitmap) {
    if (bitmap!=null) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
        return stream.toByteArray();
    }
    return null;
}

private MultipartBody.Part prepareFilePart() {

    //TODO: Use FileUtils to get the actual file by uri

    try {
        getBitmapFromUri();
        file = persistImage();

    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        RequestBody requestFile = RequestBody.create(
                MediaType.parse(getBaseContext().getContentResolver().getType(fileUri)), file);
            return MultipartBody.Part.createFormData("file", file.getName(), requestFile);

    } catch (NullPointerException e) {

        Toast.makeText(getBaseContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();

        return null;
    }

}

private RequestBody createPartFromString(String descriptionString) {
    return RequestBody.create(MultipartBody.FORM, descriptionString);
}

private void getBitmapFromUri() throws IOException {
    profileImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), fileUri);
}

private File persistImage() {
    filesDir = getFilesDir();
     imageFile = new File(filesDir, fileName + ".jpg");

    OutputStream os;
    try {
        os = new FileOutputStream(imageFile);
        profileImage.compress(Bitmap.CompressFormat.JPEG, 70, os);
        os.flush();
        os.close();
    } catch (Exception e) {
        Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
    }

    return imageFile;
}}

GetOnUpload.java

public interface GetOnUpload {
 @Multipart
@POST(Constants.UPLOAD_URL)
Call<Response> upload(@Part MultipartBody.Part file);}

Log

http://local.com/api/v1/avatar http/1.1
11-14 18:40:02.742 8851-9593/com.local.test D/OkHttp: Content-Type: multipart/form-data; boundary=d43da080-f2c3-4743-8cfd-9526cc0bd2f7
11-14 18:40:02.742 8851-9593/com.local.test D/OkHttp: Content-Length: 12424
11-14 18:40:02.743 8851-9593/com.local.test D/OkHttp: --d43da080-f2c3-4743-8cfd-9526cc0bd2f7
11-14 18:40:02.743 8851-9593/com.local.test D/OkHttp: Content-Disposition: form-data; name="file"; filename="avatar.jpg"
11-14 18:40:02.743 8851-9593/com.local.test D/OkHttp: Content-Type: multipart/form-data
11-14 18:40:02.743 8851-9593/com.local.test D/OkHttp: Content-Length: 12201
11-14 18:40:02.743 8851-9593/com.local.test D/OkHttp:
11-14 18:40:02.744 8851-9593/com.local.test D/OkHttp: --d43da080-f2c3-4743-8cfd-9526cc0bd2f7--
11-14 18:40:02.744 8851-9593/com.local.test D/OkHttp: --> END POST (12424-byte body)

11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: <-- 200 OK http://local.com/api/v1/avatar (587ms)
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: Server: nginx/1.10.3 (Ubuntu)
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: Content-Type: application/json
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: Transfer-Encoding: chunked
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: Connection: keep-alive
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: Cache-Control: no-cache, private
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: Date: Tue, 14 Nov 2017 15:40:03 GMT
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: X-RateLimit-Limit: 60
11-14 18:40:03.332 8851-9593/com.local.test D/OkHttp: X-RateLimit-Remaining: 59
11-14 18:40:03.333 8851-9593/com.local.test D/OkHttp: {"user":"Failed","status":"Image file not uploaded"}

Body:
This example worked for me

//My data manager
public void doUpload(
    Context context,
    String url) {

    Uri uri = Uri.parse(url);
    File file = new File(getPath(context, uri));
    RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
    MultipartBody.Part body = MultipartBody.Part.createFormData("imageParameterName", file.getName(), reqFile);

    uploadService(body)

}

//REST service
@Multipart
@POST("upload.aspx")
Call<DefaultDTO> uploadService(@Part MultipartBody.Part image);


问:
Making Phone Call Ionic App
I'm using this code in the view:

Phone Call

And I can't make the call.
This is my config.xml

```<code><access origin="tel:*" launch-external="yes" />
<allow-intent href="tel:*" />
</code>```

答:
Try using the native plugin:

https://ionicframework.com/docs/native/call-number/

You can create a function that receive the phone number as a parameter.

Title: Making Phone Call Ionic App

Body:
I'm using this code in the view:

Phone Call

And I can't make the call.
This is my config.xml

<access origin="tel:*" launch-external="yes" />
<allow-intent href="tel:*" />