问:
Python integration testing : Using paramiko to fake a ssh server, and log the command given to it
Here is the context :
I'm writing a procedure that connects to a distant server via SSH (with paramiko), execute some commands, and then returns the result of the commands to the procedure. It works fine as much as I can tell.

I'm now trying to make an "end to end" test, by faking the ssh server, in order to check if the ssh commands are sent, and that their resulkt is given back to the procedure.

I have found a fake SSH server that uses paramiko, it works well when I connect to it via a real SSH client, but I got errors when I try to connect to it  with a paramiko ssh client :/

Do you have any idea of what I'm doing wrong ?

Here is my code :

Server :

#!/usr/bin/env python
"""Fake SSH Server Utilizing Paramiko"""
import threading
import socket
import sys
import traceback
import paramiko
import os

__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
LOG = open("log.txt", "a")
#HOST_KEY = paramiko.RSAKey(filename='keys/private.key')
HOST_KEY = paramiko.RSAKey(filename=os.path.join(__location__, 'id_rsa.new'))
PORT = 2200

def handle_cmd(cmd, chan):
    """Branching statements to handle and prepare a response for a command"""
    response = ""
    if cmd.startswith("sudo"):
        send_ascii("sudo.txt", chan)
        return
    elif cmd.startswith("ls"):
        response = "pw.txt"
    elif cmd.startswith("version"):
        response = "Super Amazing Awesome (tm) Shell v1.1"
    elif cmd.startswith("pwd"):
        response = "/home/clippy"
    elif cmd.startswith("cd"):
        send_ascii("cd.txt", chan)
        return
    elif cmd.startswith("cat"):
        send_ascii("cat.txt", chan)
        return
    elif cmd.startswith("rm"):
        send_ascii("bomb.txt", chan)
        response = "You blew up our files! How could you???"
    elif cmd.startswith("whoami"):
        send_ascii("wizard.txt", chan)
        response = "You are a wizard of the internet!"
    elif ".exe" in cmd:
        response = "Hmm, trying to access .exe files from an ssh terminal..... Your methods are unconventional"
    elif cmd.startswith("cmd"):
        response = "Command Prompt? We only use respectable shells on this machine.... Sorry"
    elif cmd == "help":
        send_ascii("help.txt", chan)
        return
    else:
        send_ascii("clippy.txt", chan)
        response = "Use the 'help' command to view available commands"

    LOG.write(response + "\n")
    LOG.flush()
    chan.send(response + "\r\n")

def send_ascii(filename, chan):
    """Print ascii from a file and send it to the channel"""
    with open('ascii/{}'.format(filename)) as text:
        chan.send("\r")
        for line in enumerate(text):
            LOG.write(line[1])
            chan.send(line[1] + "\r")
    LOG.flush()

class FakeSshServer(paramiko.ServerInterface):
    """Settings for paramiko server interface"""
    def __init__(self):
        self.event = threading.Event()

    def check_channel_request(self, kind, chanid):
        if kind == 'session':
            return paramiko.OPEN_SUCCEEDED
        return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED

    def check_auth_password(self, username, password):
        # Accept all passwords as valid by default
        return paramiko.AUTH_SUCCESSFUL

    def get_allowed_auths(self, username):
        return 'password'

    def check_channel_shell_request(self, channel):
        self.event.set()
        return True

    def check_channel_pty_request(self, channel, term, width, height, pixelwidth, pixelheight, modes):
        return True

def start_server():
    """Init and run the ssh server"""
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind(('', PORT))
    except Exception as err:
        print('*** Bind failed: {}'.format(err))
        traceback.print_exc()
        sys.exit(1)

    while True:
        try:
            sock.listen(100)
            print('Listening for connection ...')
            client, addr = sock.accept()
        except Exception as err:
            print('*** Listen/accept failed: {}'.format(err))
            traceback.print_exc()

        LOG.write("\n\nConnection from: " + addr[0] + "\n")
        print('Got a connection!')
        try:
            transport = paramiko.Transport(client)
            transport.add_server_key(HOST_KEY)
            # Change banner to appear legit on nmap (or other network) scans
            transport.local_version = "SSH-2.0-OpenSSH_7.6p1 Ubuntu-4ubuntu0.3"
            server = FakeSshServer()
            try:
                transport.start_server(server=server)
            except paramiko.SSHException:
                print('*** SSH negotiation failed.')
                raise Exception("SSH negotiation failed")
            # wait for auth
            chan = transport.accept(20)
            if chan is None:
                print('*** No channel.')
                raise Exception("No channel")

            server.event.wait(10)
            if not server.event.is_set():
                print('*** Client never asked for a shell.')
                raise Exception("No shell request")

            try:
                chan.send("Welcome to the my control server\r\n\r\n")
                run = True
                while run:
                    chan.send("$ ")
                    command = ""
                    while not command.endswith("\r"):
                        transport = chan.recv(1024)
                        # Echo input to psuedo-simulate a basic terminal
                        chan.send(transport)
                        command += transport.decode("utf-8")

                    chan.send("\r\n")
                    command = command.rstrip()
                    LOG.write("$ " + command + "\n")
                    print(command)
                    if command == "exit":
                        run = False
                    else:
                        handle_cmd(command, chan)

            except Exception as err:
                print('!!! Exception: {}: {}'.format(err.__class__, err))
                traceback.print_exc()
                try:
                    transport.close()
                except Exception:
                    pass

            chan.close()

        except Exception as err:
            print('!!! Exception: {}: {}'.format(err.__class__, err))
            traceback.print_exc()
            try:
                transport.close()
            except Exception:
                pass

if __name__ == "__main__":
    start_server()
```

<p>Here is the code I have tried to connect to it with paramiko :</p>

<pre class="lang-py prettyprint-override"><code>    sshClient = paramiko.SSHClient()
    sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    sshClient.connect('127.0.0.1', username='bnc', password='pass', port=2200)

    sshClient.exec_command('ls')
</code>```

and also

    sshClient = paramiko.SSHClient()
    sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    sshClient.connect('127.0.0.1', username='bnc', password='pass', port=2200)

    channel = sshClient.get_transport().open_session()
    channel.get_pty()
    channel.invoke_shell()
    channel.send('ls\r\n')
```

<p>with both tests, I got the same error :</p>

```Listening for connection ...
Got a connection!
!!! Exception: <class 'socket.error'>: Socket is closed
Traceback (most recent call last):
Listening for connection ...
  File "/home/cbrunain/Projects/daa/Python/test/ssh_mock_server.py", line 152, in start_server
    chan.send(transport)
  File "/home/cbrunain/.local/share/virtualenvs/daa-hnBs4Nn2/lib/python2.7/site-packages/paramiko/channel.py", line 801, in send
    return self._send(s, m)
  File "/home/cbrunain/.local/share/virtualenvs/daa-hnBs4Nn2/lib/python2.7/site-packages/paramiko/channel.py", line 1198, in _send
    raise socket.error("Socket is closed")
error: Socket is closed
No handlers could be found for logger "paramiko.transport"
```

答:
I finally found something that is working : https://gist.github.com/cschwede/3e2c025408ab4af531651098331cce45</p>

```<code>import logging
import socket
import sys
import threading

import paramiko

logging.basicConfig()
logger = logging.getLogger()

running = True
host_key = paramiko.RSAKey(filename='id_rsa')

def ssh_command_handler(command):
    print('default : ', command)

class Server(paramiko.ServerInterface):
    def __init__(self):
        self.event = threading.Event()

    def check_channel_request(self, kind, chanid):
        if kind == 'session':
            return paramiko.OPEN_SUCCEEDED

    def check_auth_publickey(self, username, key):
        return paramiko.AUTH_SUCCESSFUL

    def get_allowed_auths(self, username):
        return 'publickey'

    def check_channel_exec_request(self, channel, command):
        global running
        # This is the command we need to parse
        if command == 'exit':
            running = False
        ssh_command_handler(command)
        self.event.set()
        return True

def listener():
    print('listener')
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(('', 2222))

    sock.listen(100)
    client, addr = sock.accept()

    t = paramiko.Transport(client)
    t.set_gss_host(socket.getfqdn(""))
    t.load_server_moduli()
    t.add_server_key(host_key)
    server = Server()
    t.start_server(server=server)

    # Wait 30 seconds for a command
    server.event.wait(30)
    t.close()
    print('end listener')

def run_server(command_handler):
    global running
    global ssh_command_handler
    ssh_command_handler = command_handler
    while running:
        try:
            listener()
        except KeyboardInterrupt:
            sys.exit(0)
        except Exception as exc:
            logger.error(exc)

def run_in_thread(command_handler):
    thread = threading.Thread(target=run_server, args=(command_handler,))
    thread.start()

if __name__ == '__main__':
    run_in_thread(ssh_command_handler)
</code>```

Body:
Here is the context :
I'm writing a procedure that connects to a distant server via SSH (with paramiko), execute some commands, and then returns the result of the commands to the procedure. It works fine as much as I can tell.

I'm now trying to make an "end to end" test, by faking the ssh server, in order to check if the ssh commands are sent, and that their resulkt is given back to the procedure.

I have found a fake SSH server that uses paramiko, it works well when I connect to it via a real SSH client, but I got errors when I try to connect to it  with a paramiko ssh client :/

Do you have any idea of what I'm doing wrong ?

Here is my code :

Server :

#!/usr/bin/env python
"""Fake SSH Server Utilizing Paramiko"""
import threading
import socket
import sys
import traceback
import paramiko
import os

__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
LOG = open("log.txt", "a")
#HOST_KEY = paramiko.RSAKey(filename='keys/private.key')
HOST_KEY = paramiko.RSAKey(filename=os.path.join(__location__, 'id_rsa.new'))
PORT = 2200

def handle_cmd(cmd, chan):
    """Branching statements to handle and prepare a response for a command"""
    response = ""
    if cmd.startswith("sudo"):
        send_ascii("sudo.txt", chan)
        return
    elif cmd.startswith("ls"):
        response = "pw.txt"
    elif cmd.startswith("version"):
        response = "Super Amazing Awesome (tm) Shell v1.1"
    elif cmd.startswith("pwd"):
        response = "/home/clippy"
    elif cmd.startswith("cd"):
        send_ascii("cd.txt", chan)
        return
    elif cmd.startswith("cat"):
        send_ascii("cat.txt", chan)
        return
    elif cmd.startswith("rm"):
        send_ascii("bomb.txt", chan)
        response = "You blew up our files! How could you???"
    elif cmd.startswith("whoami"):
        send_ascii("wizard.txt", chan)
        response = "You are a wizard of the internet!"
    elif ".exe" in cmd:
        response = "Hmm, trying to access .exe files from an ssh terminal..... Your methods are unconventional"
    elif cmd.startswith("cmd"):
        response = "Command Prompt? We only use respectable shells on this machine.... Sorry"
    elif cmd == "help":
        send_ascii("help.txt", chan)
        return
    else:
        send_ascii("clippy.txt", chan)
        response = "Use the 'help' command to view available commands"

    LOG.write(response + "\n")
    LOG.flush()
    chan.send(response + "\r\n")

def send_ascii(filename, chan):
    """Print ascii from a file and send it to the channel"""
    with open('ascii/{}'.format(filename)) as text:
        chan.send("\r")
        for line in enumerate(text):
            LOG.write(line[1])
            chan.send(line[1] + "\r")
    LOG.flush()

class FakeSshServer(paramiko.ServerInterface):
    """Settings for paramiko server interface"""
    def __init__(self):
        self.event = threading.Event()

    def check_channel_request(self, kind, chanid):
        if kind == 'session':
            return paramiko.OPEN_SUCCEEDED
        return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED

    def check_auth_password(self, username, password):
        # Accept all passwords as valid by default
        return paramiko.AUTH_SUCCESSFUL

    def get_allowed_auths(self, username):
        return 'password'

    def check_channel_shell_request(self, channel):
        self.event.set()
        return True

    def check_channel_pty_request(self, channel, term, width, height, pixelwidth, pixelheight, modes):
        return True

def start_server():
    """Init and run the ssh server"""
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind(('', PORT))
    except Exception as err:
        print('*** Bind failed: {}'.format(err))
        traceback.print_exc()
        sys.exit(1)

    while True:
        try:
            sock.listen(100)
            print('Listening for connection ...')
            client, addr = sock.accept()
        except Exception as err:
            print('*** Listen/accept failed: {}'.format(err))
            traceback.print_exc()

        LOG.write("\n\nConnection from: " + addr[0] + "\n")
        print('Got a connection!')
        try:
            transport = paramiko.Transport(client)
            transport.add_server_key(HOST_KEY)
            # Change banner to appear legit on nmap (or other network) scans
            transport.local_version = "SSH-2.0-OpenSSH_7.6p1 Ubuntu-4ubuntu0.3"
            server = FakeSshServer()
            try:
                transport.start_server(server=server)
            except paramiko.SSHException:
                print('*** SSH negotiation failed.')
                raise Exception("SSH negotiation failed")
            # wait for auth
            chan = transport.accept(20)
            if chan is None:
                print('*** No channel.')
                raise Exception("No channel")

            server.event.wait(10)
            if not server.event.is_set():
                print('*** Client never asked for a shell.')
                raise Exception("No shell request")

            try:
                chan.send("Welcome to the my control server\r\n\r\n")
                run = True
                while run:
                    chan.send("$ ")
                    command = ""
                    while not command.endswith("\r"):
                        transport = chan.recv(1024)
                        # Echo input to psuedo-simulate a basic terminal
                        chan.send(transport)
                        command += transport.decode("utf-8")

                    chan.send("\r\n")
                    command = command.rstrip()
                    LOG.write("$ " + command + "\n")
                    print(command)
                    if command == "exit":
                        run = False
                    else:
                        handle_cmd(command, chan)

            except Exception as err:
                print('!!! Exception: {}: {}'.format(err.__class__, err))
                traceback.print_exc()
                try:
                    transport.close()
                except Exception:
                    pass

            chan.close()

        except Exception as err:
            print('!!! Exception: {}: {}'.format(err.__class__, err))
            traceback.print_exc()
            try:
                transport.close()
            except Exception:
                pass

if __name__ == "__main__":
    start_server()

Here is the code I have tried to connect to it with paramiko :

    sshClient = paramiko.SSHClient()
    sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    sshClient.connect('127.0.0.1', username='bnc', password='pass', port=2200)

    sshClient.exec_command('ls')

and also

    sshClient = paramiko.SSHClient()
    sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    sshClient.connect('127.0.0.1', username='bnc', password='pass', port=2200)

    channel = sshClient.get_transport().open_session()
    channel.get_pty()
    channel.invoke_shell()
    channel.send('ls\r\n')

with both tests, I got the same error :

Listening for connection ...
Got a connection!
!!! Exception: <class 'socket.error'>: Socket is closed
Traceback (most recent call last):
Listening for connection ...
  File "/home/cbrunain/Projects/daa/Python/test/ssh_mock_server.py", line 152, in start_server
    chan.send(transport)
  File "/home/cbrunain/.local/share/virtualenvs/daa-hnBs4Nn2/lib/python2.7/site-packages/paramiko/channel.py", line 801, in send
    return self._send(s, m)
  File "/home/cbrunain/.local/share/virtualenvs/daa-hnBs4Nn2/lib/python2.7/site-packages/paramiko/channel.py", line 1198, in _send
    raise socket.error("Socket is closed")
error: Socket is closed
No handlers could be found for logger "paramiko.transport"

Body:
I finally found something that is working : https://gist.github.com/cschwede/3e2c025408ab4af531651098331cce45

import logging
import socket
import sys
import threading

import paramiko

logging.basicConfig()
logger = logging.getLogger()

running = True
host_key = paramiko.RSAKey(filename='id_rsa')

def ssh_command_handler(command):
    print('default : ', command)

class Server(paramiko.ServerInterface):
    def __init__(self):
        self.event = threading.Event()

    def check_channel_request(self, kind, chanid):
        if kind == 'session':
            return paramiko.OPEN_SUCCEEDED

    def check_auth_publickey(self, username, key):
        return paramiko.AUTH_SUCCESSFUL

    def get_allowed_auths(self, username):
        return 'publickey'

    def check_channel_exec_request(self, channel, command):
        global running
        # This is the command we need to parse
        if command == 'exit':
            running = False
        ssh_command_handler(command)
        self.event.set()
        return True

def listener():
    print('listener')
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(('', 2222))

    sock.listen(100)
    client, addr = sock.accept()

    t = paramiko.Transport(client)
    t.set_gss_host(socket.getfqdn(""))
    t.load_server_moduli()
    t.add_server_key(host_key)
    server = Server()
    t.start_server(server=server)

    # Wait 30 seconds for a command
    server.event.wait(30)
    t.close()
    print('end listener')

def run_server(command_handler):
    global running
    global ssh_command_handler
    ssh_command_handler = command_handler
    while running:
        try:
            listener()
        except KeyboardInterrupt:
            sys.exit(0)
        except Exception as exc:
            logger.error(exc)

def run_in_thread(command_handler):
    thread = threading.Thread(target=run_server, args=(command_handler,))
    thread.start()

if __name__ == '__main__':
    run_in_thread(ssh_command_handler)


来源: stackexchange

问:
Create a continuous list (like a wheel) in vb/c#.net
In a windows forms application, I need a list that shows only one list item at a time but can be scrolled continuously.  For example if my list items were:

A
B
C
D

If D was the displayed item and I scrolled down, it would go back to A.  This would be similar to a wheel of fortune wheel (although that is not what I am using it for).  I figured that the list control would have a continuous scroll option but I have not found such.

I want to mimic this (just the numbers, not the actual lock):

答:
You could use a LinkList<T> to simulate this. I believe you could use the same logic in your winforms such that every event to ScrollSown it can display the next item

Console

```<code>var linkList = new LinkedList<int>(new int[] { 1, 2, 3, 4 }.AsEnumerable());

var first = linkList.First;
LinkedListNode<int> current = first;

while (true)
{

   Console.WriteLine($"Current value {current.Value}, press enter to Go Gext");
   Console.ReadLine();
   current = current.Next ?? first;

}
</code>```

Console Output

WinForms

```<code>public LinkedList<object> linkList;
public LinkedListNode<object> current;
public LinkedListNode<object> first;

public Form1()
{
    InitializeComponent();

    linkList = new LinkedList<object>(new object[] { "A", "B", "C", "D" }.AsEnumerable());
    first = linkList.First;
    current = first;
    listBox1.Items.Add(current.Value);
}

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{

  current = current.Next ?? first;
  listBox1.Items.Add(current.Value);

}
</code>```

WinForm Output

ContentLicense: CC BY-SA 4.0

Body:
You could use a LinkList<T> to simulate this. I believe you could use the same logic in your winforms such that every event to ScrollSown it can display the next item

Console

var linkList = new LinkedList<int>(new int[] { 1, 2, 3, 4 }.AsEnumerable());

var first = linkList.First;
LinkedListNode<int> current = first;

while (true)
{

   Console.WriteLine($"Current value {current.Value}, press enter to Go Gext");
   Console.ReadLine();
   current = current.Next ?? first;

}

Console Output

WinForms

public LinkedList<object> linkList;
public LinkedListNode<object> current;
public LinkedListNode<object> first;

public Form1()
{
    InitializeComponent();

    linkList = new LinkedList<object>(new object[] { "A", "B", "C", "D" }.AsEnumerable());
    first = linkList.First;
    current = first;
    listBox1.Items.Add(current.Value);
}

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{

  current = current.Next ?? first;
  listBox1.Items.Add(current.Value);

}

WinForm Output


问:
Page builder by Siteorigin showing problem in wp 5
I made my site with a theme which recommended page builder by siteorigin for batter experience. recently i updated wordpress to latest version and also i updated page builder.Now i made a page with this page builder before the wordpress 5.0 and now i tried a lot to edit the page with page builder but it is not showing when i click on edit button it's redirecting me to class Editor.

Note: i used classic editor and Disable Gutenberg plugin also to fix this but i failed

答: Hopefully, you've made progress since posting. If not, try temporarily deactivating all plugins except for the Classic Editor plugin and those plugins authored by SiteOrigin. In this state, does the issue resolve?</p>


问:
Eager loaded data errors saying context already disposed
EDIT
Driver class as requested:

```<code>public class Driver
{
    public int Id { get; set; }
    public ApplicationUser User { get; set; }
    public string DriverDirectoryTitle { get; set; }
    public string FullNames { get; set; }
    public string AlternatePhoneNumber { get; set; }
    public string IdNumber { get; set; }
    public DateTime DateOfBirth { get; set; }
    public DateTime RegistrationDate { get; set; }
    public Gender Gender { get; set; }
    public Ethnicity Ethnicity { get; set; }
    public bool Disability { get; set; }
    public string Address { get; set; }
    public City City { get; set; }
    public string Nationality { get; set; }
    public bool OwnVehicle { get; set; }
    public bool DriversLicense { get; set; }
    public Experience Experience { get; set; }
    public string Availability { get; set; }
    public Vehicle Vehicle { get; set; }
    public bool IsPremium { get; set; }
    public bool Deleted { get; set; }
}
</code>```

QUESTION

My app is sort of like a Euro Truck Simulator thing which lists drivers for jobs.

I'm returning a DTO onto my page (this is ASPX Web Forms by the way) which maps closely to the Driver data model:

```<code>public class DriverViewModel
{
    public int Id { get; set; }
    public string UserId { get; set; }
    public string FullNames { get; set; }
    public string DriverDirectoryTitle { get; set; }
    public string RegistrationDate { get; set; }
    public string AlternatePhoneNumber { get; set; }
    public string IdNumber { get; set; }
    public DateTime DateOfBirth { get; set; }
    public Ethnicity Ethnicity { get; set; }
    public Experience Experience { get; set; }
    public City City { get; set; }
    public Gender Gender { get; set; }
    public List<DriverLicensesViewModel> LicenseCodes { get; set; }
    public Vehicle Vehicle { get; set; }
    public bool Disability { get; set; }
    public string Address { get; set; }
    public string Nationality { get; set; }
    public bool OwnVehicle { get; set; }
    public bool DriversLicense { get; set; }
    public string Availability { get; set; }
    public bool IsPremium { get; set; }
    public bool ReferenceChecked { get; set; }
    public bool PoliceClearance { get; set; }
}
</code>```

Note that none of the relational properties are defined as virtual - so none of the data is being lazy loaded.

There's some work that I'm doing before I return the viewmodel on the page but in particular, the mapping of only some relational properties is resulting in the error below.

Here's the code for the mapping:

```<code>using (var db = new ApplicationDbContext())
{
    var drivers = db.Drivers
        .Include(x => x.User).Include(x => x.City)
        .Include(x => x.Ethnicity).Include(x => x.Experience)
        .Include(x => x.Gender).Include(x => x.Vehicle)
        .OrderBy(x => x.FullNames).ToList();

    var driverModels = new List<DriverViewModel>();
    foreach (var driver in drivers)
    {
        var driverModel = new DriverViewModel
        {
            Id = driver.Id,
            FullNames = driver.FullNames,
            DriverDirectoryTitle = driver.DriverDirectoryTitle,
            RegistrationDate = driver.RegistrationDate.ToString("ddd, dd MMM yyy"),
            AlternatePhoneNumber = driver.AlternatePhoneNumber,
            IdNumber = driver.IdNumber,
            DateOfBirth = driver.DateOfBirth,
            Ethnicity = driver.Ethnicity,
            Experience = driver.Experience,
            Gender = driver.Gender,
            Vehicle = driver.Vehicle,
            Disability = driver.Disability,
            Address = driver.Address,
            Nationality = driver.Nationality,
            OwnVehicle = driver.OwnVehicle,
            DriversLicense = driver.DriversLicense,
            Availability = driver.Availability,
            IsPremium = driver.IsPremium,
            LicenseCodes = new List<DriverLicensesViewModel>()
        };
    }
}
</code>```

The code as presented here works fine and the data is loaded on the page perfectly, however, if I add the mapping for the City property into the mappings, the error occurs:

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

I've checked a few other questions such as the one linked below, but all seem to involve lazy loading the data which I'm clearly not doing:

https://stackoverflow.com/a/18398729/475766

So why does my City relation that I've added here cause the problem but none of the other relations do and how do I fix it?

答:
If any entities within the tree contain virtual properties, they will be lazy-loaded by Entity Framework, not just the root entity.

It seems that City does contains virtual properties, so once they are first accessed (i.e. within your mapping) it will result in another SQL query to the database for the necessary data.

This will fail if your context is disposed, so the solution is to remove the virtual keyword, or eager load using Select:

```<code>db.Drivers
    .Include(x => x.City.Select(c => c.LazyProperty));
</code>```

For completeness, with EF Core this would be:

```<code>db.Drivers
    .Include(x => x.City)
        .ThenInclude(c => c.LazyProperty);
</code>```

Body:
EDIT
Driver class as requested:

public class Driver
{
    public int Id { get; set; }
    public ApplicationUser User { get; set; }
    public string DriverDirectoryTitle { get; set; }
    public string FullNames { get; set; }
    public string AlternatePhoneNumber { get; set; }
    public string IdNumber { get; set; }
    public DateTime DateOfBirth { get; set; }
    public DateTime RegistrationDate { get; set; }
    public Gender Gender { get; set; }
    public Ethnicity Ethnicity { get; set; }
    public bool Disability { get; set; }
    public string Address { get; set; }
    public City City { get; set; }
    public string Nationality { get; set; }
    public bool OwnVehicle { get; set; }
    public bool DriversLicense { get; set; }
    public Experience Experience { get; set; }
    public string Availability { get; set; }
    public Vehicle Vehicle { get; set; }
    public bool IsPremium { get; set; }
    public bool Deleted { get; set; }
}

QUESTION

My app is sort of like a Euro Truck Simulator thing which lists drivers for jobs.

I'm returning a DTO onto my page (this is ASPX Web Forms by the way) which maps closely to the Driver data model:

public class DriverViewModel
{
    public int Id { get; set; }
    public string UserId { get; set; }
    public string FullNames { get; set; }
    public string DriverDirectoryTitle { get; set; }
    public string RegistrationDate { get; set; }
    public string AlternatePhoneNumber { get; set; }
    public string IdNumber { get; set; }
    public DateTime DateOfBirth { get; set; }
    public Ethnicity Ethnicity { get; set; }
    public Experience Experience { get; set; }
    public City City { get; set; }
    public Gender Gender { get; set; }
    public List<DriverLicensesViewModel> LicenseCodes { get; set; }
    public Vehicle Vehicle { get; set; }
    public bool Disability { get; set; }
    public string Address { get; set; }
    public string Nationality { get; set; }
    public bool OwnVehicle { get; set; }
    public bool DriversLicense { get; set; }
    public string Availability { get; set; }
    public bool IsPremium { get; set; }
    public bool ReferenceChecked { get; set; }
    public bool PoliceClearance { get; set; }
}

Note that none of the relational properties are defined as virtual - so none of the data is being lazy loaded.

There's some work that I'm doing before I return the viewmodel on the page but in particular, the mapping of only some relational properties is resulting in the error below.

Here's the code for the mapping:

using (var db = new ApplicationDbContext())
{
    var drivers = db.Drivers
        .Include(x => x.User).Include(x => x.City)
        .Include(x => x.Ethnicity).Include(x => x.Experience)
        .Include(x => x.Gender).Include(x => x.Vehicle)
        .OrderBy(x => x.FullNames).ToList();

    var driverModels = new List<DriverViewModel>();
    foreach (var driver in drivers)
    {
        var driverModel = new DriverViewModel
        {
            Id = driver.Id,
            FullNames = driver.FullNames,
            DriverDirectoryTitle = driver.DriverDirectoryTitle,
            RegistrationDate = driver.RegistrationDate.ToString("ddd, dd MMM yyy"),
            AlternatePhoneNumber = driver.AlternatePhoneNumber,
            IdNumber = driver.IdNumber,
            DateOfBirth = driver.DateOfBirth,
            Ethnicity = driver.Ethnicity,
            Experience = driver.Experience,
            Gender = driver.Gender,
            Vehicle = driver.Vehicle,
            Disability = driver.Disability,
            Address = driver.Address,
            Nationality = driver.Nationality,
            OwnVehicle = driver.OwnVehicle,
            DriversLicense = driver.DriversLicense,
            Availability = driver.Availability,
            IsPremium = driver.IsPremium,
            LicenseCodes = new List<DriverLicensesViewModel>()
        };
    }
}

The code as presented here works fine and the data is loaded on the page perfectly, however, if I add the mapping for the City property into the mappings, the error occurs:

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

I've checked a few other questions such as the one linked below, but all seem to involve lazy loading the data which I'm clearly not doing:

https://stackoverflow.com/a/18398729/475766

So why does my City relation that I've added here cause the problem but none of the other relations do and how do I fix it?

Body:
If any entities within the tree contain virtual properties, they will be lazy-loaded by Entity Framework, not just the root entity.

It seems that City does contains virtual properties, so once they are first accessed (i.e. within your mapping) it will result in another SQL query to the database for the necessary data.

This will fail if your context is disposed, so the solution is to remove the virtual keyword, or eager load using Select:

db.Drivers
    .Include(x => x.City.Select(c => c.LazyProperty));

For completeness, with EF Core this would be:

db.Drivers
    .Include(x => x.City)
        .ThenInclude(c => c.LazyProperty);


问:
How to create a new model for multiple models response from Web API call
There is a GET method from TMDB API, which could return 3 mix types of data in one array, movie, tv and actor. Currently, I had create those 3 models, but how could I create one data model with all those three types data?

Well my purpose is to list all types of search result in a table view, e.g. when I give "Billions", it should list TV series named Billions as well as Movie and Actor with same name.

/ / / as below result return from Web API, element with 14 or 15 Items could be Movie or TV item, and the left one is Actor with 9 items.

```<code>(root): {} 4 Items
  page: 1
  total_results: 16
  total_pages: 1
results [] 16 Items
  0: {} 14 Items
  1: {} 15 Items
  2: {} 15 Items
  3: {} 9 Items
  4: {} 15 Items
  5: {} 15 Items
  6: {} 9 Items
  7: {} 9 Items
  8: {} 15 Items
  ...
</code>```

Multi search: GET /search/multi

Search multiple models in a single request. Multi search currently
  supports searching for movies, tv shows and people in a single
  request.

/ / / Update the json response from server for the multi-search.
The returned json data is like results[Movie, Movie, Movie, TV, Actor...], which contains 3 types of item and without sequence, also same type item could occurs many times in the array base on your search query name. Thus, how to create a model to adopt above results[] json data?

```{
  "page": 1,
  "total_results": 16,
  "total_pages": 1,
  "results": [
    {
      "original_name": "Billions",
      "genre_ids": [
        18
      ],
      "media_type": "tv",
      "name": "Billions",
      "popularity": 32.444,
      "origin_country": [
        "US"
      ],
      "vote_count": 328,
      "first_air_date": "2016-01-17",
      "backdrop_path": "/6f3s7NbujF9NGBIdBQhRJcZAbFy.jpg",
      "original_language": "en",
      "id": 62852,
      "vote_average": 7.7,
      "overview": "A complex drama about power politics in the world of New York high finance. \n\nShrewd, savvy U.S. Attorney Chuck Rhoades and the brilliant, ambitious hedge fund king Bobby \"Axe\" Axelrod are on an explosive collision course, with each using all of his considerable smarts, power and influence to outmaneuver the other. The stakes are in the billions in this timely, provocative series.",
      "poster_path": "/3VlVadslWLbOJtp4VQ6VkdAwmpV.jpg"
    },
    {
      "vote_count": 5,
      "popularity": 3.034,
      "id": 173327,
      "video": false,
      "media_type": "movie",
      "vote_average": 7.1,
      "title": "From Bedrooms to Billions",
      "release_date": "2014-10-03",
      "original_language": "en",
      "original_title": "From Bedrooms to Billions",
      "genre_ids": [
        99
      ],
      "backdrop_path": "/iRVufH3NyLHIhyVpJHOdm3dRTgz.jpg",
      "adult": false,
      "overview": "From Bedrooms to Billions is a 2014 documentary film by British filmmakers Anthony Caulfield and Nicola Caulfield that tells the story of the British video games industry from 1979 to the present day. The film focuses on how the creativity and vision of a relatively small number of individuals allowed the UK to play a key, pioneering role in the shaping of the billion dollar video games industry which today dominates the modern world's entertainment landscape. The film features interviews with major British game designers, journalists and musicians from across the last 30 years.",
      "poster_path": "/fYImGFVmmYbksWJwA5DQE4A3jqS.jpg"
    },
    {
      "vote_count": 0,
      "popularity": 0.841,
      "id": 566190,
      "video": false,
      "media_type": "movie",
      "vote_average": 0,
      "title": "Billions",
      "release_date": "1920-12-06",
      "original_language": "en",
      "original_title": "Billions",
      "genre_ids": [
        35
      ],
      "backdrop_path": null,
      "adult": false,
      "overview": "Billions is a lost 1920 American silent comedy film produced by and starring Alla Nazimova and distributed by Metro Pictures. Ray Smallwood directed. It is based on a French play, L'Homme riche, by Jean Jose Frappa and Henry Dupuy-Mazuel.",
      "poster_path": "/tyg1N4tp4NU52xpxPr3CAO0o4QG.jpg"
    },
    {
      "known_for_department": "Acting",
      "id": 1547859,
      "name": "Jonathan Billions",
      "known_for": [
        {
          "original_name": "The Walking Dead",
          "genre_ids": [
            18,
            10759,
            10765
          ],
          "media_type": "tv",
          "name": "The Walking Dead",
          "origin_country": [
            "US"
          ],
          "vote_count": 4517,
          "first_air_date": "2010-10-31",
          "backdrop_path": "/wXXaPMgrv96NkH8KD1TMdS2d7iq.jpg",
          "original_language": "en",
          "id": 1402,
          "vote_average": 7.3,
          "overview": "Sheriff's deputy Rick Grimes awakens from a coma to find a post-apocalyptic world dominated by flesh-eating zombies. He sets out to find his family and encounters many other survivors along the way.",
          "poster_path": "/5l10EjdgPxu8Gbl5Ww6SWkVQH6T.jpg"
        },
        {
          "poster_path": "/y1VT2NoBOx3aC2exhkyN9AGUkMR.jpg",
          "vote_count": 834,
          "video": false,
          "media_type": "movie",
          "id": 333385,
          "adult": false,
          "backdrop_path": "/pEQVSTEuYOOBAzbD7VzBea2KlCs.jpg",
          "original_language": "en",
          "original_title": "Mr. Right",
          "genre_ids": [
            28,
            35,
            10749
          ],
          "title": "Mr. Right",
          "vote_average": 6.4,
          "overview": "A girl falls for the \"perfect\" guy, who happens to have a very fatal flaw: he's a hitman on the run from the crime cartels who employ him.",
          "release_date": "2016-02-29"
        },
        {
          "poster_path": "/cbpv3Ocs772JVRLT6xlRJsiPwFp.jpg",
          "vote_count": 102,
          "video": false,
          "media_type": "movie",
          "id": 367551,
          "adult": false,
          "backdrop_path": "/xVqO8aah6HgLfP0bsG9YBidpNQJ.jpg",
          "original_language": "en",
          "original_title": "American Hero",
          "genre_ids": [
            28,
            35,
            878
          ],
          "title": "American Hero",
          "vote_average": 5.2,
          "overview": "Melvin, a reluctant hero who is far from super, has been suppressing his telekinetic powers for years with booze, drugs, and women. In the process, he has failed at practically everything, most of all as a parent to his son. After a brush with death, Melvin decides to use his powers for good and clean up the streets of New Orleans with the help of his best friend/definitely-not-a-sidekick, Lucille. For a man who can do the impossible, it might be a fight even he can’t win.",
          "release_date": "2015-12-11"
        }
      ],
      "popularity": 1.4,
      "profile_path": "/51C28GwY9XYx9ELLiaHEaPsa2nu.jpg",
      "adult": false,
      "media_type": "person",
      "gender": 0
    },
    {
      "poster_path": "/xys6Ii7J0tYgaXVcStts7r5sAcn.jpg",
      "popularity": 4.262,
      "vote_count": 11,
      "video": false,
      "media_type": "movie",
      "id": 339586,
      "adult": false,
      "backdrop_path": "/2RdKldFMbdm2eXB1NJljf367tJ7.jpg",
      "original_language": "en",
      "original_title": "From Bedrooms to Billions: The Amiga Years",
      "genre_ids": [
        99
      ],
      "title": "From Bedrooms to Billions: The Amiga Years",
      "vote_average": 7.4,
      "overview": "A feature documentary that explores the influence of the Commodore Amiga and how it took video game development, music and publishing to a whole new level and changed the video games industry forever.",
      "release_date": "2016-05-10"
    },
    {
      "vote_count": 7,
      "popularity": 1.16,
      "id": 363551,
      "video": false,
      "media_type": "movie",
      "vote_average": 8.3,
      "title": "Billions in Change",
      "release_date": "2015-10-04",
      "original_language": "en",
      "original_title": "Billions in Change",
      "genre_ids": [
        99
      ],
      "backdrop_path": null,
      "adult": false,
      "overview": "The world is facing some huge problems. There’s a lot of talk about how to solve them. But talk doesn’t reduce pollution, or grow food, or heal the sick. That takes doing. This film is the story about a group of doers, the elegantly simple inventions they have made to change the lives of billions of people, and the unconventional billionaire spearheading the project.",
      "poster_path": "/ryiRPF1CDBY5pXIaumQRoVJtqno.jpg"
    },
    {
      "known_for_department": "Acting",
      "id": 1547858,
      "name": "Bill Billions",
      "known_for": [
        {
          "release_date": "2015-12-11",
          "id": 367551,
          "vote_count": 100,
          "video": false,
          "media_type": "movie",
          "vote_average": 5.2,
          "title": "American Hero",
          "genre_ids": [
            28,
            35,
            878
          ],
          "original_title": "American Hero",
          "original_language": "en",
          "adult": false,
          "backdrop_path": "/xVqO8aah6HgLfP0bsG9YBidpNQJ.jpg",
          "overview": "Melvin, a reluctant hero who is far from super, has been suppressing his telekinetic powers for years with booze, drugs, and women. In the process, he has failed at practically everything, most of all as a parent to his son. After a brush with death, Melvin decides to use his powers for good and clean up the streets of New Orleans with the help of his best friend/definitely-not-a-sidekick, Lucille. For a man who can do the impossible, it might be a fight even he can’t win.",
          "poster_path": "/cbpv3Ocs772JVRLT6xlRJsiPwFp.jpg"
        },
        {
          "release_date": "2018-03-24",
          "id": 513510,
          "vote_count": 14,
          "video": false,
          "media_type": "movie",
          "vote_average": 5.7,
          "title": "All Light Will End",
          "genre_ids": [
            27,
            53
          ],
          "original_title": "All Light Will End",
          "original_language": "en",
          "adult": false,
          "backdrop_path": "/2uvfioN7TjQCSlLmRFedRCya2Hd.jpg",
          "overview": "When a capricious young author with a dark secret returns home for her brother's graduation, she finds herself haunted by the past and tormented by night terrors.",
          "poster_path": "/OiReATeSgIyIPePtNeaUfQfDGX.jpg"
        },
        {
          "poster_path": "/tnxNqC3S9qgyx4PdwT1MybcpCYJ.jpg",
          "id": 554979,
          "vote_count": 8,
          "video": false,
          "media_type": "movie",
          "adult": false,
          "backdrop_path": "/mFCR7qscnhseuGXbE0v2afvr0wH.jpg",
          "genre_ids": [
            18,
            10751,
            878
          ],
          "original_title": "Mail Order Monster",
          "original_language": "en",
          "title": "Mail Order Monster",
          "vote_average": 5,
          "overview": "A girl seeks help and guidance from a robot monster to cope with the bullies at school and her father's new girlfriend.",
          "release_date": "2018-11-06"
        }
      ],
      "popularity": 0.6,
      "profile_path": null,
      "gender": 0,
      "media_type": "person",
      "adult": false
    },
    {
      "known_for_department": "Production",
      "id": 2285018,
      "name": "Ayoka Billions",
      "known_for": [
        {
          "release_date": "2019-09-27",
          "id": 565383,
          "vote_count": 15,
          "video": false,
          "media_type": "movie",
          "vote_average": 6.1,
          "title": "The Death of Dick Long",
          "genre_ids": [
            35,
            80,
            18
          ],
          "original_title": "The Death of Dick Long",
          "original_language": "en",
          "adult": false,
          "backdrop_path": "/gTNCO9iTeOq9m4pyUZwNoMCvdGf.jpg",
          "overview": "Dick died last night, and Zeke and Earl don’t want anybody finding out how. That’s too bad though, cause news travels fast in small-town Alabama.",
          "poster_path": "/vURitOcmtcH8Dr1bWryTvfkeyJX.jpg"
        }
      ],
      "popularity": 0.6,
      "profile_path": null,
      "gender": 0,
      "media_type": "person",
      "adult": false
    },
    {
      "vote_count": 0,
      "popularity": 0.6,
      "id": 238821,
      "video": false,
      "media_type": "movie",
      "vote_average": 0,
      "title": "Thousands... Not Billions",
      "release_date": "2005-01-01",
      "original_language": "en",
      "original_title": "Thousands... Not Billions",
      "genre_ids": [
        99
      ],
      "backdrop_path": null,
      "adult": false,
      "overview": "Radiometric dating is one of the linchpins of evolutionary education today. Dr. Don DeYoung shatters this and other dating methods employed by evolutionists to cast doubt on the reliability of the Bible and its chronology of earth history. Evolutionists seek to undermine faith in Genesis as the true documentary of the history of the universe. When people are told that a dinosaur bone has been determined to be tens of millions of years old, that obviously doesn’t square with the biblical record of man being created on Day 6 with the land animals. But DeYoung now demonstrates that Christians no longer have to puzzle over this glaring contradiction.",
      "poster_path": "/qn15fLI8x90BBag3Q4E0NJSDrsp.jpg"
    },
    {
      "poster_path": "/hM4rIzzRZ7CifI46JgaY6pL9lP2.jpg",
      "popularity": 1.001,
      "vote_count": 0,
      "video": false,
      "media_type": "movie",
      "id": 612537,
      "adult": false,
      "backdrop_path": null,
      "original_language": "en",
      "original_title": "From Bedrooms to Billions: The PlayStation Revolution",
      "genre_ids": [
        99
      ],
      "title": "From Bedrooms to Billions: The PlayStation Revolution",
      "vote_average": 0,
      "overview": "Feature film focusing on how the Sony PlayStation took Video Gaming to a whole new level for Gamers and Developers!",
      "release_date": "2019-09-01"
    },
    {
      "original_name": "The Foods that Make Billions",
      "id": 38601,
      "media_type": "tv",
      "name": "The Foods that Make Billions",
      "popularity": 0.6,
      "vote_count": 0,
      "vote_average": 0,
      "first_air_date": "2010-11-23",
      "poster_path": null,
      "genre_ids": [],
      "original_language": "en",
      "backdrop_path": null,
      "overview": "A documentary series which tells the story of how big business feeds us by transforming simple commodities into everyday necessities and highly profitable brands",
      "origin_country": [
        "GB"
      ]
    },
    {
      "vote_count": 0,
      "popularity": 0.6,
      "id": 395824,
      "video": false,
      "media_type": "movie",
      "vote_average": 0,
      "title": "From Billions to None: The Passenger Pigeon's Flight to Extinction",
      "release_date": "2014-09-01",
      "original_language": "en",
      "original_title": "From Billions to None: The Passenger Pigeon's Flight to Extinction",
      "genre_ids": [],
      "backdrop_path": null,
      "adult": false,
      "overview": "From Billions to None follows naturalist and author Joel Greenberg and his friends on a quest to reveal the incredible, mostly forgotten story of how the passenger pigeon, the most abundant bird species in North America for thousands of years, became extinct by human hands in a geologic heartbeat. From Billions to None retells the remarkable story of the passenger pigeon and explores its striking relevance to conservation challenges today, and plans for its possible revival. Interweaving rare archival material, CGI animation that brings the flocks of millions to life and aerial cinematography, the film recreates the awe-inspiring nature of these birds, and presents passionate scientists, teachers and young people who reveal why, 100 years later, it's important to remember the event - and act.",
      "poster_path": "/xGjOGXoLtBPhZdfzmoZEeKIAMiA.jpg"
    },
    {
      "poster_path": "/vH7s14m6trJhdteH4rbEJxzzGoR.jpg",
      "popularity": 0.6,
      "vote_count": 0,
      "video": false,
      "media_type": "movie",
      "id": 488790,
      "adult": false,
      "backdrop_path": "/3aV4z6c7zcla8sVepUIXFqa65i.jpg",
      "original_language": "en",
      "original_title": "Jay Billion's Anything But Love",
      "genre_ids": [
        35
      ],
      "title": "Jay Billion's Anything But Love",
      "vote_average": 0,
      "overview": "Two divorcees are jaded on love. They meet each other and have to figure how to let their guard down.",
      "release_date": "2013-12-04"
    },
    {
      "known_for_department": "Acting",
      "id": 1381030,
      "name": "Maki Billiones",
      "known_for": [
        {
          "vote_count": 2,
          "video": false,
          "media_type": "movie",
          "id": 63897,
          "adult": false,
          "genre_ids": [
            35,
            10749
          ],
          "original_title": "Who's That Girl?",
          "original_language": "tl",
          "title": "Who's That Girl?",
          "vote_average": 4.3,
          "overview": "Elizabeth Pedroza (Curtis) is a UST Architecture graduate infatuated with her long-time school crush, John Eduque (Luis Manzano). Her world comes crushing down when she learns about the death of Eduque. She immediately goes to the wake and gets the shock of her life. She sees an older man, instead of a young man, lying in the coffin. The wife of the deceased John Eduque Sr gets piqued with her visit. A family friend’s simple question ‘who’s that girl?’ soon escalates into a grand-scale inquisition complete with kidnapping and high-profile rescue.",
          "release_date": "2011-03-02"
        }
      ],
      "popularity": 0.6,
      "profile_path": null,
      "gender": 0,
      "media_type": "person",
      "adult": false
    },
    {
      "known_for_department": "Acting",
      "id": 1083881,
      "name": "Cheska Billiones",
      "known_for": [
        {
          "vote_count": 3,
          "video": false,
          "media_type": "movie",
          "adult": false,
          "vote_average": 6,
          "title": "The Adventures of Pureza - Queen Of The Riles",
          "original_language": "tl",
          "original_title": "The Adventures of Pureza - Queen Of The Riles",
          "genre_ids": [
            35
          ],
          "id": 73086,
          "backdrop_path": "/og7bD3t0yIeSQX1WpBZdV7UOR4N.jpg",
          "overview": "The story revolves with Pura, (Melai) who plays the comedic role of a bubbly, caring, kind-hearted, very hardworking “dakilang ate” who wants nothing but only the best for her one and only beloved brother, Ulam, and uplift their dismal life. In all her endeavors, Pura’s best friend, Ruben (Jason Francisco), has always been by her side. Pura and Ruben then stumbles into a one-time big time opportunity to usher a Brazilian model who manages to escape them. With this unfortunate turn of event, Pura steps into the role … literally. She is now the model Pureza Mayriles! Basking in the promise of a better fortune plus a serendipitous love, little did Pura know that she has dragged herself into a life-threatening mess? Now running for their lives, Pura and Ruben has to detangle themselves from the dangers that faces them and how! Read More: The Adventures of Pureza: Queen of The Riles Trailer | Pinoymovieblog.com Under Creative Commons License: Attribution Share Alike",
          "release_date": "2011-07-13"
        },
        {
          "release_date": "2008-05-28",
          "id": 50720,
          "vote_count": 3,
          "video": false,
          "media_type": "movie",
          "vote_average": 6.3,
          "title": "Caregiver",
          "genre_ids": [
            18
          ],
          "original_title": "Caregiver",
          "original_language": "en",
          "adult": false,
          "backdrop_path": "/bvwGldHNcsobXJyjaScBcSJePx3.jpg",
          "overview": "A grade school English teacher Sarah Gonzales joins the 150,000 Pinoy OFWs working in the United Kingdom to support her Husband, Teddy Gonzales in making a better living for their family. More than just a chronicle of the Filipinos experience working as nurses and caregivers in the UK, this story also charts Sarah's journey to self-discovery from a submissive wife who makes sacrifices for her Husband; Teddy's aspirations to an empowered woman who finds dignity and pride in a humbling job as a Caregiver in London.",
          "poster_path": "/vwBeNAlTXFl1Zedb33U5YBigm7k.jpg"
        },
        {
          "vote_count": 2,
          "video": false,
          "media_type": "movie",
          "id": 127074,
          "vote_average": 8.3,
          "original_language": "en",
          "original_title": "My Kuya's Wedding",
          "title": "My Kuya's Wedding",
          "genre_ids": [
            18,
            10749
          ],
          "adult": false,
          "overview": "Inseparable as siblings, Jeff  and Kat grew up very close to each other through thick and thin. Kat being overzealous and very wary of girls who likes her brother Jeff. Her Kuya simply means the world to her.  Years later, Kat is all grown-up and lovely, and soon awaits her Kuyas return after four years of hard work from abroad. But all this excitement of a sibling reunion is foiled at the airport upon sight of Heidi, Kats worst nightmare and her brothers fiancée.  Fueled with envy, Kat embarks on an all-out scheme to pull out all the stops to their impending wedding with the help of her gay bestfriend of all seasons. However, as Kat schemes to freeze the marital icing off her siblings cake, she finds herself falling for the charms of an evicted reality show superstar - Aris  who happens to be Heidis brother.  As she desperately clings to her last semblance of family, her Kuya Jeff, will Kat be able to stop this bridezilla from snatching away her only Kuya in her life?",
          "release_date": "2007-08-29"
        }
      ],
      "popularity": 0.6,
      "profile_path": null,
      "gender": 0,
      "media_type": "person",
      "adult": false
    },
    {
      "poster_path": "/pTFv3fksOhUHkSLeWiY7hzowSq6.jpg",
      "popularity": 3.235,
      "vote_count": 31,
      "video": false,
      "media_type": "movie",
      "id": 35201,
      "adult": false,
      "backdrop_path": "/6tPw2MyxnPYLxKXIK4UCQSw0fWx.jpg",
      "original_language": "en",
      "original_title": "The Holcroft Covenant",
      "genre_ids": [
        28,
        53
      ],
      "title": "The Holcroft Covenant",
      "vote_average": 5.2,
      "overview": "A man who was a confidant of Adolf Hitler dies and leaves a fortune to make amends for his Nazi past--but his son has to search the world to find it",
      "release_date": "1985-09-20"
    }
  ]
}
```

<p>One of model, the MovieResults model.</p>

```struct MovieResults: Codable {

    let page: Int
    let results: [Movie]
    let totalPages: Int
    let totalResults: Int

    enum CodingKeys: String, CodingKey {
        case page
        case results
        case totalPages = "total_pages"
        case totalResults = "total_results"
    }
}
```

<p>/// Movie model</p>

```struct Movie: Codable, Equatable {

    let posterPath: String?
    let adult: Bool
    let overview: String
    let releaseDate: String
    let genreIds: [Int]
    let id: Int
    let originalTitle: String
    let originalLanguage: String
    let title: String
    let backdropPath: String?
    let popularity: Double
    let voteCount: Int
    let video: Bool
    let voteAverage: Double

    var releaseYear: String {
        return String(releaseDate.prefix(4))
    }

    enum CodingKeys: String, CodingKey {
        case posterPath = "poster_path"
        case adult
        case overview
        case releaseDate = "release_date"
        case genreIds = "genre_ids"
        case id
        case originalTitle = "original_title"
        case originalLanguage = "original_language"
        case title
        case backdropPath = "backdrop_path"
        case popularity
        case voteCount = "vote_count"
        case video
        case voteAverage = "vote_average"
    }
}

```

答:
Just create main model:</p>

```<code> public class MainClas{
      public ChildOne ChildOnes { get; set; }
      public ChildTwo ChildTwos { get; set; }
      public ChildThree ChildThress { get; set; }
 }
</code>```

Body:
There is a GET method from TMDB API, which could return 3 mix types of data in one array, movie, tv and actor. Currently, I had create those 3 models, but how could I create one data model with all those three types data?

Well my purpose is to list all types of search result in a table view, e.g. when I give "Billions", it should list TV series named Billions as well as Movie and Actor with same name.

/ / / as below result return from Web API, element with 14 or 15 Items could be Movie or TV item, and the left one is Actor with 9 items.

(root): {} 4 Items
  page: 1
  total_results: 16
  total_pages: 1
results [] 16 Items
  0: {} 14 Items
  1: {} 15 Items
  2: {} 15 Items
  3: {} 9 Items
  4: {} 15 Items
  5: {} 15 Items
  6: {} 9 Items
  7: {} 9 Items
  8: {} 15 Items
  ...

Multi search: GET /search/multi

Search multiple models in a single request. Multi search currently
  supports searching for movies, tv shows and people in a single
  request.

/ / / Update the json response from server for the multi-search.
The returned json data is like results[Movie, Movie, Movie, TV, Actor...], which contains 3 types of item and without sequence, also same type item could occurs many times in the array base on your search query name. Thus, how to create a model to adopt above results[] json data?

{
  "page": 1,
  "total_results": 16,
  "total_pages": 1,
  "results": [
    {
      "original_name": "Billions",
      "genre_ids": [
        18
      ],
      "media_type": "tv",
      "name": "Billions",
      "popularity": 32.444,
      "origin_country": [
        "US"
      ],
      "vote_count": 328,
      "first_air_date": "2016-01-17",
      "backdrop_path": "/6f3s7NbujF9NGBIdBQhRJcZAbFy.jpg",
      "original_language": "en",
      "id": 62852,
      "vote_average": 7.7,
      "overview": "A complex drama about power politics in the world of New York high finance. \n\nShrewd, savvy U.S. Attorney Chuck Rhoades and the brilliant, ambitious hedge fund king Bobby \"Axe\" Axelrod are on an explosive collision course, with each using all of his considerable smarts, power and influence to outmaneuver the other. The stakes are in the billions in this timely, provocative series.",
      "poster_path": "/3VlVadslWLbOJtp4VQ6VkdAwmpV.jpg"
    },
    {
      "vote_count": 5,
      "popularity": 3.034,
      "id": 173327,
      "video": false,
      "media_type": "movie",
      "vote_average": 7.1,
      "title": "From Bedrooms to Billions",
      "release_date": "2014-10-03",
      "original_language": "en",
      "original_title": "From Bedrooms to Billions",
      "genre_ids": [
        99
      ],
      "backdrop_path": "/iRVufH3NyLHIhyVpJHOdm3dRTgz.jpg",
      "adult": false,
      "overview": "From Bedrooms to Billions is a 2014 documentary film by British filmmakers Anthony Caulfield and Nicola Caulfield that tells the story of the British video games industry from 1979 to the present day. The film focuses on how the creativity and vision of a relatively small number of individuals allowed the UK to play a key, pioneering role in the shaping of the billion dollar video games industry which today dominates the modern world's entertainment landscape. The film features interviews with major British game designers, journalists and musicians from across the last 30 years.",
      "poster_path": "/fYImGFVmmYbksWJwA5DQE4A3jqS.jpg"
    },
    {
      "vote_count": 0,
      "popularity": 0.841,
      "id": 566190,
      "video": false,
      "media_type": "movie",
      "vote_average": 0,
      "title": "Billions",
      "release_date": "1920-12-06",
      "original_language": "en",
      "original_title": "Billions",
      "genre_ids": [
        35
      ],
      "backdrop_path": null,
      "adult": false,
      "overview": "Billions is a lost 1920 American silent comedy film produced by and starring Alla Nazimova and distributed by Metro Pictures. Ray Smallwood directed. It is based on a French play, L'Homme riche, by Jean Jose Frappa and Henry Dupuy-Mazuel.",
      "poster_path": "/tyg1N4tp4NU52xpxPr3CAO0o4QG.jpg"
    },
    {
      "known_for_department": "Acting",
      "id": 1547859,
      "name": "Jonathan Billions",
      "known_for": [
        {
          "original_name": "The Walking Dead",
          "genre_ids": [
            18,
            10759,
            10765
          ],
          "media_type": "tv",
          "name": "The Walking Dead",
          "origin_country": [
            "US"
          ],
          "vote_count": 4517,
          "first_air_date": "2010-10-31",
          "backdrop_path": "/wXXaPMgrv96NkH8KD1TMdS2d7iq.jpg",
          "original_language": "en",
          "id": 1402,
          "vote_average": 7.3,
          "overview": "Sheriff's deputy Rick Grimes awakens from a coma to find a post-apocalyptic world dominated by flesh-eating zombies. He sets out to find his family and encounters many other survivors along the way.",
          "poster_path": "/5l10EjdgPxu8Gbl5Ww6SWkVQH6T.jpg"
        },
        {
          "poster_path": "/y1VT2NoBOx3aC2exhkyN9AGUkMR.jpg",
          "vote_count": 834,
          "video": false,
          "media_type": "movie",
          "id": 333385,
          "adult": false,
          "backdrop_path": "/pEQVSTEuYOOBAzbD7VzBea2KlCs.jpg",
          "original_language": "en",
          "original_title": "Mr. Right",
          "genre_ids": [
            28,
            35,
            10749
          ],
          "title": "Mr. Right",
          "vote_average": 6.4,
          "overview": "A girl falls for the \"perfect\" guy, who happens to have a very fatal flaw: he's a hitman on the run from the crime cartels who employ him.",
          "release_date": "2016-02-29"
        },
        {
          "poster_path": "/cbpv3Ocs772JVRLT6xlRJsiPwFp.jpg",
          "vote_count": 102,
          "video": false,
          "media_type": "movie",
          "id": 367551,
          "adult": false,
          "backdrop_path": "/xVqO8aah6HgLfP0bsG9YBidpNQJ.jpg",
          "original_language": "en",
          "original_title": "American Hero",
          "genre_ids": [
            28,
            35,
            878
          ],
          "title": "American Hero",
          "vote_average": 5.2,
          "overview": "Melvin, a reluctant hero who is far from super, has been suppressing his telekinetic powers for years with booze, drugs, and women. In the process, he has failed at practically everything, most of all as a parent to his son. After a brush with death, Melvin decides to use his powers for good and clean up the streets of New Orleans with the help of his best friend/definitely-not-a-sidekick, Lucille. For a man who can do the impossible, it might be a fight even he can’t win.",
          "release_date": "2015-12-11"
        }
      ],
      "popularity": 1.4,
      "profile_path": "/51C28GwY9XYx9ELLiaHEaPsa2nu.jpg",
      "adult": false,
      "media_type": "person",
      "gender": 0
    },
    {
      "poster_path": "/xys6Ii7J0tYgaXVcStts7r5sAcn.jpg",
      "popularity": 4.262,
      "vote_count": 11,
      "video": false,
      "media_type": "movie",
      "id": 339586,
      "adult": false,
      "backdrop_path": "/2RdKldFMbdm2eXB1NJljf367tJ7.jpg",
      "original_language": "en",
      "original_title": "From Bedrooms to Billions: The Amiga Years",
      "genre_ids": [
        99
      ],
      "title": "From Bedrooms to Billions: The Amiga Years",
      "vote_average": 7.4,
      "overview": "A feature documentary that explores the influence of the Commodore Amiga and how it took video game development, music and publishing to a whole new level and changed the video games industry forever.",
      "release_date": "2016-05-10"
    },
    {
      "vote_count": 7,
      "popularity": 1.16,
      "id": 363551,
      "video": false,
      "media_type": "movie",
      "vote_average": 8.3,
      "title": "Billions in Change",
      "release_date": "2015-10-04",
      "original_language": "en",
      "original_title": "Billions in Change",
      "genre_ids": [
        99
      ],
      "backdrop_path": null,
      "adult": false,
      "overview": "The world is facing some huge problems. There’s a lot of talk about how to solve them. But talk doesn’t reduce pollution, or grow food, or heal the sick. That takes doing. This film is the story about a group of doers, the elegantly simple inventions they have made to change the lives of billions of people, and the unconventional billionaire spearheading the project.",
      "poster_path": "/ryiRPF1CDBY5pXIaumQRoVJtqno.jpg"
    },
    {
      "known_for_department": "Acting",
      "id": 1547858,
      "name": "Bill Billions",
      "known_for": [
        {
          "release_date": "2015-12-11",
          "id": 367551,
          "vote_count": 100,
          "video": false,
          "media_type": "movie",
          "vote_average": 5.2,
          "title": "American Hero",
          "genre_ids": [
            28,
            35,
            878
          ],
          "original_title": "American Hero",
          "original_language": "en",
          "adult": false,
          "backdrop_path": "/xVqO8aah6HgLfP0bsG9YBidpNQJ.jpg",
          "overview": "Melvin, a reluctant hero who is far from super, has been suppressing his telekinetic powers for years with booze, drugs, and women. In the process, he has failed at practically everything, most of all as a parent to his son. After a brush with death, Melvin decides to use his powers for good and clean up the streets of New Orleans with the help of his best friend/definitely-not-a-sidekick, Lucille. For a man who can do the impossible, it might be a fight even he can’t win.",
          "poster_path": "/cbpv3Ocs772JVRLT6xlRJsiPwFp.jpg"
        },
        {
          "release_date": "2018-03-24",
          "id": 513510,
          "vote_count": 14,
          "video": false,
          "media_type": "movie",
          "vote_average": 5.7,
          "title": "All Light Will End",
          "genre_ids": [
            27,
            53
          ],
          "original_title": "All Light Will End",
          "original_language": "en",
          "adult": false,
          "backdrop_path": "/2uvfioN7TjQCSlLmRFedRCya2Hd.jpg",
          "overview": "When a capricious young author with a dark secret returns home for her brother's graduation, she finds herself haunted by the past and tormented by night terrors.",
          "poster_path": "/OiReATeSgIyIPePtNeaUfQfDGX.jpg"
        },
        {
          "poster_path": "/tnxNqC3S9qgyx4PdwT1MybcpCYJ.jpg",
          "id": 554979,
          "vote_count": 8,
          "video": false,
          "media_type": "movie",
          "adult": false,
          "backdrop_path": "/mFCR7qscnhseuGXbE0v2afvr0wH.jpg",
          "genre_ids": [
            18,
            10751,
            878
          ],
          "original_title": "Mail Order Monster",
          "original_language": "en",
          "title": "Mail Order Monster",
          "vote_average": 5,
          "overview": "A girl seeks help and guidance from a robot monster to cope with the bullies at school and her father's new girlfriend.",
          "release_date": "2018-11-06"
        }
      ],
      "popularity": 0.6,
      "profile_path": null,
      "gender": 0,
      "media_type": "person",
      "adult": false
    },
    {
      "known_for_department": "Production",
      "id": 2285018,
      "name": "Ayoka Billions",
      "known_for": [
        {
          "release_date": "2019-09-27",
          "id": 565383,
          "vote_count": 15,
          "video": false,
          "media_type": "movie",
          "vote_average": 6.1,
          "title": "The Death of Dick Long",
          "genre_ids": [
            35,
            80,
            18
          ],
          "original_title": "The Death of Dick Long",
          "original_language": "en",
          "adult": false,
          "backdrop_path": "/gTNCO9iTeOq9m4pyUZwNoMCvdGf.jpg",
          "overview": "Dick died last night, and Zeke and Earl don’t want anybody finding out how. That’s too bad though, cause news travels fast in small-town Alabama.",
          "poster_path": "/vURitOcmtcH8Dr1bWryTvfkeyJX.jpg"
        }
      ],
      "popularity": 0.6,
      "profile_path": null,
      "gender": 0,
      "media_type": "person",
      "adult": false
    },
    {
      "vote_count": 0,
      "popularity": 0.6,
      "id": 238821,
      "video": false,
      "media_type": "movie",
      "vote_average": 0,
      "title": "Thousands... Not Billions",
      "release_date": "2005-01-01",
      "original_language": "en",
      "original_title": "Thousands... Not Billions",
      "genre_ids": [
        99
      ],
      "backdrop_path": null,
      "adult": false,
      "overview": "Radiometric dating is one of the linchpins of evolutionary education today. Dr. Don DeYoung shatters this and other dating methods employed by evolutionists to cast doubt on the reliability of the Bible and its chronology of earth history. Evolutionists seek to undermine faith in Genesis as the true documentary of the history of the universe. When people are told that a dinosaur bone has been determined to be tens of millions of years old, that obviously doesn’t square with the biblical record of man being created on Day 6 with the land animals. But DeYoung now demonstrates that Christians no longer have to puzzle over this glaring contradiction.",
      "poster_path": "/qn15fLI8x90BBag3Q4E0NJSDrsp.jpg"
    },
    {
      "poster_path": "/hM4rIzzRZ7CifI46JgaY6pL9lP2.jpg",
      "popularity": 1.001,
      "vote_count": 0,
      "video": false,
      "media_type": "movie",
      "id": 612537,
      "adult": false,
      "backdrop_path": null,
      "original_language": "en",
      "original_title": "From Bedrooms to Billions: The PlayStation Revolution",
      "genre_ids": [
        99
      ],
      "title": "From Bedrooms to Billions: The PlayStation Revolution",
      "vote_average": 0,
      "overview": "Feature film focusing on how the Sony PlayStation took Video Gaming to a whole new level for Gamers and Developers!",
      "release_date": "2019-09-01"
    },
    {
      "original_name": "The Foods that Make Billions",
      "id": 38601,
      "media_type": "tv",
      "name": "The Foods that Make Billions",
      "popularity": 0.6,
      "vote_count": 0,
      "vote_average": 0,
      "first_air_date": "2010-11-23",
      "poster_path": null,
      "genre_ids": [],
      "original_language": "en",
      "backdrop_path": null,
      "overview": "A documentary series which tells the story of how big business feeds us by transforming simple commodities into everyday necessities and highly profitable brands",
      "origin_country": [
        "GB"
      ]
    },
    {
      "vote_count": 0,
      "popularity": 0.6,
      "id": 395824,
      "video": false,
      "media_type": "movie",
      "vote_average": 0,
      "title": "From Billions to None: The Passenger Pigeon's Flight to Extinction",
      "release_date": "2014-09-01",
      "original_language": "en",
      "original_title": "From Billions to None: The Passenger Pigeon's Flight to Extinction",
      "genre_ids": [],
      "backdrop_path": null,
      "adult": false,
      "overview": "From Billions to None follows naturalist and author Joel Greenberg and his friends on a quest to reveal the incredible, mostly forgotten story of how the passenger pigeon, the most abundant bird species in North America for thousands of years, became extinct by human hands in a geologic heartbeat. From Billions to None retells the remarkable story of the passenger pigeon and explores its striking relevance to conservation challenges today, and plans for its possible revival. Interweaving rare archival material, CGI animation that brings the flocks of millions to life and aerial cinematography, the film recreates the awe-inspiring nature of these birds, and presents passionate scientists, teachers and young people who reveal why, 100 years later, it's important to remember the event - and act.",
      "poster_path": "/xGjOGXoLtBPhZdfzmoZEeKIAMiA.jpg"
    },
    {
      "poster_path": "/vH7s14m6trJhdteH4rbEJxzzGoR.jpg",
      "popularity": 0.6,
      "vote_count": 0,
      "video": false,
      "media_type": "movie",
      "id": 488790,
      "adult": false,
      "backdrop_path": "/3aV4z6c7zcla8sVepUIXFqa65i.jpg",
      "original_language": "en",
      "original_title": "Jay Billion's Anything But Love",
      "genre_ids": [
        35
      ],
      "title": "Jay Billion's Anything But Love",
      "vote_average": 0,
      "overview": "Two divorcees are jaded on love. They meet each other and have to figure how to let their guard down.",
      "release_date": "2013-12-04"
    },
    {
      "known_for_department": "Acting",
      "id": 1381030,
      "name": "Maki Billiones",
      "known_for": [
        {
          "vote_count": 2,
          "video": false,
          "media_type": "movie",
          "id": 63897,
          "adult": false,
          "genre_ids": [
            35,
            10749
          ],
          "original_title": "Who's That Girl?",
          "original_language": "tl",
          "title": "Who's That Girl?",
          "vote_average": 4.3,
          "overview": "Elizabeth Pedroza (Curtis) is a UST Architecture graduate infatuated with her long-time school crush, John Eduque (Luis Manzano). Her world comes crushing down when she learns about the death of Eduque. She immediately goes to the wake and gets the shock of her life. She sees an older man, instead of a young man, lying in the coffin. The wife of the deceased John Eduque Sr gets piqued with her visit. A family friend’s simple question ‘who’s that girl?’ soon escalates into a grand-scale inquisition complete with kidnapping and high-profile rescue.",
          "release_date": "2011-03-02"
        }
      ],
      "popularity": 0.6,
      "profile_path": null,
      "gender": 0,
      "media_type": "person",
      "adult": false
    },
    {
      "known_for_department": "Acting",
      "id": 1083881,
      "name": "Cheska Billiones",
      "known_for": [
        {
          "vote_count": 3,
          "video": false,
          "media_type": "movie",
          "adult": false,
          "vote_average": 6,
          "title": "The Adventures of Pureza - Queen Of The Riles",
          "original_language": "tl",
          "original_title": "The Adventures of Pureza - Queen Of The Riles",
          "genre_ids": [
            35
          ],
          "id": 73086,
          "backdrop_path": "/og7bD3t0yIeSQX1WpBZdV7UOR4N.jpg",
          "overview": "The story revolves with Pura, (Melai) who plays the comedic role of a bubbly, caring, kind-hearted, very hardworking “dakilang ate” who wants nothing but only the best for her one and only beloved brother, Ulam, and uplift their dismal life. In all her endeavors, Pura’s best friend, Ruben (Jason Francisco), has always been by her side. Pura and Ruben then stumbles into a one-time big time opportunity to usher a Brazilian model who manages to escape them. With this unfortunate turn of event, Pura steps into the role … literally. She is now the model Pureza Mayriles! Basking in the promise of a better fortune plus a serendipitous love, little did Pura know that she has dragged herself into a life-threatening mess? Now running for their lives, Pura and Ruben has to detangle themselves from the dangers that faces them and how! Read More: The Adventures of Pureza: Queen of The Riles Trailer | Pinoymovieblog.com Under Creative Commons License: Attribution Share Alike",
          "release_date": "2011-07-13"
        },
        {
          "release_date": "2008-05-28",
          "id": 50720,
          "vote_count": 3,
          "video": false,
          "media_type": "movie",
          "vote_average": 6.3,
          "title": "Caregiver",
          "genre_ids": [
            18
          ],
          "original_title": "Caregiver",
          "original_language": "en",
          "adult": false,
          "backdrop_path": "/bvwGldHNcsobXJyjaScBcSJePx3.jpg",
          "overview": "A grade school English teacher Sarah Gonzales joins the 150,000 Pinoy OFWs working in the United Kingdom to support her Husband, Teddy Gonzales in making a better living for their family. More than just a chronicle of the Filipinos experience working as nurses and caregivers in the UK, this story also charts Sarah's journey to self-discovery from a submissive wife who makes sacrifices for her Husband; Teddy's aspirations to an empowered woman who finds dignity and pride in a humbling job as a Caregiver in London.",
          "poster_path": "/vwBeNAlTXFl1Zedb33U5YBigm7k.jpg"
        },
        {
          "vote_count": 2,
          "video": false,
          "media_type": "movie",
          "id": 127074,
          "vote_average": 8.3,
          "original_language": "en",
          "original_title": "My Kuya's Wedding",
          "title": "My Kuya's Wedding",
          "genre_ids": [
            18,
            10749
          ],
          "adult": false,
          "overview": "Inseparable as siblings, Jeff  and Kat grew up very close to each other through thick and thin. Kat being overzealous and very wary of girls who likes her brother Jeff. Her Kuya simply means the world to her.  Years later, Kat is all grown-up and lovely, and soon awaits her Kuyas return after four years of hard work from abroad. But all this excitement of a sibling reunion is foiled at the airport upon sight of Heidi, Kats worst nightmare and her brothers fiancée.  Fueled with envy, Kat embarks on an all-out scheme to pull out all the stops to their impending wedding with the help of her gay bestfriend of all seasons. However, as Kat schemes to freeze the marital icing off her siblings cake, she finds herself falling for the charms of an evicted reality show superstar - Aris  who happens to be Heidis brother.  As she desperately clings to her last semblance of family, her Kuya Jeff, will Kat be able to stop this bridezilla from snatching away her only Kuya in her life?",
          "release_date": "2007-08-29"
        }
      ],
      "popularity": 0.6,
      "profile_path": null,
      "gender": 0,
      "media_type": "person",
      "adult": false
    },
    {
      "poster_path": "/pTFv3fksOhUHkSLeWiY7hzowSq6.jpg",
      "popularity": 3.235,
      "vote_count": 31,
      "video": false,
      "media_type": "movie",
      "id": 35201,
      "adult": false,
      "backdrop_path": "/6tPw2MyxnPYLxKXIK4UCQSw0fWx.jpg",
      "original_language": "en",
      "original_title": "The Holcroft Covenant",
      "genre_ids": [
        28,
        53
      ],
      "title": "The Holcroft Covenant",
      "vote_average": 5.2,
      "overview": "A man who was a confidant of Adolf Hitler dies and leaves a fortune to make amends for his Nazi past--but his son has to search the world to find it",
      "release_date": "1985-09-20"
    }
  ]
}

One of model, the MovieResults model.

struct MovieResults: Codable {

    let page: Int
    let results: [Movie]
    let totalPages: Int
    let totalResults: Int

    enum CodingKeys: String, CodingKey {
        case page
        case results
        case totalPages = "total_pages"
        case totalResults = "total_results"
    }
}

/// Movie model

struct Movie: Codable, Equatable {

    let posterPath: String?
    let adult: Bool
    let overview: String
    let releaseDate: String
    let genreIds: [Int]
    let id: Int
    let originalTitle: String
    let originalLanguage: String
    let title: String
    let backdropPath: String?
    let popularity: Double
    let voteCount: Int
    let video: Bool
    let voteAverage: Double

    var releaseYear: String {
        return String(releaseDate.prefix(4))
    }

    enum CodingKeys: String, CodingKey {
        case posterPath = "poster_path"
        case adult
        case overview
        case releaseDate = "release_date"
        case genreIds = "genre_ids"
        case id
        case originalTitle = "original_title"
        case originalLanguage = "original_language"
        case title
        case backdropPath = "backdrop_path"
        case popularity
        case voteCount = "vote_count"
        case video
        case voteAverage = "vote_average"
    }
}

Body:
Just create main model:

 public class MainClas{
      public ChildOne ChildOnes { get; set; }
      public ChildTwo ChildTwos { get; set; }
      public ChildThree ChildThress { get; set; }
 }


问:
How to infer datatypes of an existing Spark Dataframe?
I have pivoted a long dataframe to wide. This new dataframe has many more new variables coming out of the pivot. These are all stringType in the Spark Dataframe. How could I get pyspark to re-infer the datatypes of those new columns so that decimals will be recognised as float/double instead of strings?

Background: The number of these new columns per table and the number of pivoted tables are too large to hand-build the schemas.

It would be nice if there is something similar to infer_objects() from Pandas, but within PySpark. I cannot use Pandas because the job lives in AWS Glue Spark, which offers no Pandas library.

答:
Ok, here it is.
As of Feb. 2020, there is no solution to this problem within PySpark, other than using infer_objects() form Pandas. If you cannot use Pandas because you are in AWS Glue, then you are lucky and unlucky. Unlucky - because Pandas isn't available; lucky - because there is something even better, which is recomputeSchema() in Scala.

All you have to do is

Start with DynamicFrame dyf

Move the dyf to Java with dyf._jdf

Use the recomputeSchema() method in Scala dyf._jdf.recomputeSchema(), which returns a schema.

Catch the schema with toString() method and _deserialize_json_string( ) function

The code would be

```<code>    from awsglue.gluetypes import _deserialize_json_string
    newSchema=_deserialize_json_string( dyf._jdf.recomputeSchema().toString() ) )
</code>```

Then you can get to resolving choices as serkan mentioned.

Body:
Ok, here it is.
As of Feb. 2020, there is no solution to this problem within PySpark, other than using infer_objects() form Pandas. If you cannot use Pandas because you are in AWS Glue, then you are lucky and unlucky. Unlucky - because Pandas isn't available; lucky - because there is something even better, which is recomputeSchema() in Scala.

All you have to do is

Start with DynamicFrame dyf

Move the dyf to Java with dyf._jdf

Use the recomputeSchema() method in Scala dyf._jdf.recomputeSchema(), which returns a schema.

Catch the schema with toString() method and _deserialize_json_string( ) function

The code would be

    from awsglue.gluetypes import _deserialize_json_string
    newSchema=_deserialize_json_string( dyf._jdf.recomputeSchema().toString() ) )

Then you can get to resolving choices as serkan mentioned.


问:
wifi doesn't work in own apps, but works in blackberry's browser
we have just started to write Blackberry apps and got strange situation. Our apps work with mobile internet (GPRS, 3G, EDGE) but are not working using wifi connection.

I have tried to change all the settings. But still usually it is just "Tunnel failure" or "connection timed out" errors. The same is with HTTPDemo example.

Could someone help and explain what it is with Blackberry and WiFi?

StreamConnection s = null;
                   s = (StreamConnection)Connector.open(getUrl() +";interface=wifi");
                   HttpConnection httpConn = (HttpConnection)s;

```<code>               int status = httpConn.getResponseCode();

               if (status == HttpConnection.HTTP_OK)
               {
                   // Is this html?
                   String contentType = httpConn.getHeaderField(HEADER_CONTENTTYPE);
                   boolean htmlContent = (contentType != null && contentType.startsWith(CONTENTTYPE_TEXTHTML));

                   InputStream input = s.openInputStream();

                   byte[] data = new byte[256];
                   int len = 0;
                   int size = 0;
                   StringBuffer raw = new StringBuffer();

                   while ( -1 != (len = input.read(data)) )
                   {
                       // Exit condition for the thread. An IOException is
                       // thrown because of the call to  httpConn.close(),
                       // causing the thread to terminate.
                       if ( _stop )
                       {
                           httpConn.close();
                           s.close();
                           input.close();
                       }
                       raw.append(new String(data, 0, len));
                       size += len;
                   }

                   raw.insert(0, "bytes received]\n");
                   raw.insert(0, size);
                   raw.insert(0, '[');
                   content = raw.toString();

                   if ( htmlContent )
                   {
                       content = prepareData(raw.toString());
                   }
                   input.close();
               }
               else
               {
                   content = "response code = " + status;
               }
               s.close();
           }
           catch (IOCancelledException e)
           {
               System.out.println(e.toString());
               return;
           }
           catch (IOException e)
           {
               errorDialog(e.toString());
               return;
           }
</code>```

答:
Connecting the following way works for me

```<code>HttpConnection connection = null;
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
         connection = (HttpConnection) Connector.open(url+ ";interface=wifi",
         Connector.READ_WRITE,true);
} else {
         connection = (HttpConnection) Connector.open(url+";deviceside=true", Connector.READ_WRITE,true);
}
</code>```

Please refer the following resource for in-depth understanding and various methods.

Sample HTTP Connection code and BIS-B Access By peter_strange

ContentLicense: CC BY-SA 3.0

Body:
we have just started to write Blackberry apps and got strange situation. Our apps work with mobile internet (GPRS, 3G, EDGE) but are not working using wifi connection.

I have tried to change all the settings. But still usually it is just "Tunnel failure" or "connection timed out" errors. The same is with HTTPDemo example.

Could someone help and explain what it is with Blackberry and WiFi?

StreamConnection s = null;
                   s = (StreamConnection)Connector.open(getUrl() +";interface=wifi");
                   HttpConnection httpConn = (HttpConnection)s;

               int status = httpConn.getResponseCode();

               if (status == HttpConnection.HTTP_OK)
               {
                   // Is this html?
                   String contentType = httpConn.getHeaderField(HEADER_CONTENTTYPE);
                   boolean htmlContent = (contentType != null && contentType.startsWith(CONTENTTYPE_TEXTHTML));

                   InputStream input = s.openInputStream();

                   byte[] data = new byte[256];
                   int len = 0;
                   int size = 0;
                   StringBuffer raw = new StringBuffer();

                   while ( -1 != (len = input.read(data)) )
                   {
                       // Exit condition for the thread. An IOException is
                       // thrown because of the call to  httpConn.close(),
                       // causing the thread to terminate.
                       if ( _stop )
                       {
                           httpConn.close();
                           s.close();
                           input.close();
                       }
                       raw.append(new String(data, 0, len));
                       size += len;
                   }

                   raw.insert(0, "bytes received]\n");
                   raw.insert(0, size);
                   raw.insert(0, '[');
                   content = raw.toString();

                   if ( htmlContent )
                   {
                       content = prepareData(raw.toString());
                   }
                   input.close();
               }
               else
               {
                   content = "response code = " + status;
               }
               s.close();
           }
           catch (IOCancelledException e)
           {
               System.out.println(e.toString());
               return;
           }
           catch (IOException e)
           {
               errorDialog(e.toString());
               return;
           }

Body:
Connecting the following way works for me

HttpConnection connection = null;
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
         connection = (HttpConnection) Connector.open(url+ ";interface=wifi",
         Connector.READ_WRITE,true);
} else {
         connection = (HttpConnection) Connector.open(url+";deviceside=true", Connector.READ_WRITE,true);
}

Please refer the following resource for in-depth understanding and various methods.

Sample HTTP Connection code and BIS-B Access By peter_strange