问:
Issues with rendering in Android ListView in Visual Studio Xamarin
Hello to all programmers. I try to create simple chat. The first chatter's messages should be in white square with rounded corners, the second chatter's messages should be in blue square with rounded corners and with some icon. So I decided to use listview and adapter for this task. In adapter I use simple set of data {bool type, sting message, DateTime date}. So Adapter Code is

```<code>class ChatMessagesViewHolder : Java.Lang.Object
{
    internal TextView chatMessageView;
    public void initialize(View view){}
}
public class ChatMessagesAdapter : BaseAdapter
{
    Activity _context;
    List<MessageData> _dataList;

    public ChatMessagesAdapter(Activity context, List<MessageData> dataList)
    {
        _context = context;
        _dataList = dataList;
    }
    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        ChatMessagesViewHolder chatMessagesViewHolderClass;
        View view;
        view = convertView;
        int layout = _dataList[position]._type == 0 ? Resource.Layout.MessageLitsUserItem:Resource.Layout.MessageListWorkerItem;
        Typeface openSansRegular = Typeface.CreateFromAsset(_context.Assets, "fonts/OpenSans-Regular.ttf");
        if (view == null)
        {
            view = _context.LayoutInflater.Inflate(layout, parent, false);
            chatMessagesViewHolderClass = new ChatMessagesViewHolder();
            chatMessagesViewHolderClass.chatMessageView = view.FindViewById<TextView>(Resource.Id.messageText);
            chatMessagesViewHolderClass.initialize(view);
            view.Tag = chatMessagesViewHolderClass;
        }
        else
        {
            chatMessagesViewHolderClass = (ChatMessagesViewHolder)view.Tag;
        }
        chatMessagesViewHolderClass.chatMessageView.Typeface = openSansRegular;
        chatMessagesViewHolderClass.chatMessageView.Text = _dataList[position]._date.ToString()+"\n"+ _dataList[position]._message;
        return view;
    }
    public void Add(MessageData messageData)
    {
        _dataList.Add(messageData);
    }
}
</code>```

In Activity I fill Adapter with test information that way - message from 1-st chatter, message from 2-nd chatter. It repeats 10 times.

```<code>public class ChatActivity : Activity{
    ListView chatList;
    ChatMessagesAdapter chatAdapter;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.ChatLayout);
        List<MessageData> dataList = new List<MessageData>();
        for (int i = 0; i < 20; i++)
        {
            string message = "Test message from chatter "+(i%2).ToString();
            dataList.Add(new MessageData(i % 2, message, DateTime.Now));
        }
        chatAdapter = new ChatMessagesAdapter(this, dataList);
        chatList.Adapter = chatAdapter;
    }
}
</code>```

When I run app (in Visual studio emulator for android) first rendering of list is correct, but when I scroll list up/down, the layouts of ListView mixes - 1-st chatter's message sometimes get 2-nd chatter's template (with blue square and icon), 2-nd chatter's message sometimes get 1-st chatter's template (with white square and no icon).
For Example

Can anybody help me with this issue? Any help will be appreciated.

UPDATED

New code of Adapter, updated to work with two different ViewHolders for different type of messages.

```<code>class ChatUserMessagesViewHolder : Java.Lang.Object
{
    internal RelativeLayout messageBox;
    internal TextView messageText;
    public void initialize(View view) { }
}
class ChatWorkerMessagesViewHolder : Java.Lang.Object
{
    internal RelativeLayout messageBox;
    internal TextView messageText;
    internal ImageView workerIcon;
    public void initialize(View view) { }
}
public class ChatMessagesAdapter : BaseAdapter
{
    Activity _context;
    List<MessageData> _dataList;

    public ChatMessagesAdapter(Activity context, List<MessageData> dataList)
    {
        _context = context;
        _dataList = dataList;
    }
    public override Java.Lang.Object GetItem(int position)
    {
        return position;
    }
    public override long GetItemId(int position)
    {
        return position;
    }
    public override int Count
    {
        get
        {
            return _dataList.Count;
        }
    }
    public override int GetItemViewType(int position)
    {
        return _dataList[position]._type;
    }
    public override int ViewTypeCount
    {
        get
        {
            return 2;
        }
    }
    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        ChatMessagesViewHolder chatMessagesViewHolderClass;
        ChatWorkerMessagesViewHolder chatWorkerMessagesViewHolderClass;
        ChatUserMessagesViewHolder chatUserMessagesViewHolderClass;
        View view;
        view = convertView;
        int layout = _dataList[position]._type == 0 ? Resource.Layout.MessageLitsUserItem:Resource.Layout.MessageListWorkerItem;
        Typeface openSansRegular = Typeface.CreateFromAsset(_context.Assets, "fonts/OpenSans-Regular.ttf");
        if (view == null)
        {
            switch (GetItemViewType(position))
            {
                case 0:
                    view = _context.LayoutInflater.Inflate(Resource.Layout.MessageLitsUserItem, null);
                    chatUserMessagesViewHolderClass = new ChatUserMessagesViewHolder();
                    chatUserMessagesViewHolderClass.messageBox = view.FindViewById<RelativeLayout>(Resource.Id.messageBox);
                    chatUserMessagesViewHolderClass.messageText = view.FindViewById<TextView>(Resource.Id.messageText);
                    chatUserMessagesViewHolderClass.messageText.Typeface = openSansRegular;
                    chatUserMessagesViewHolderClass.messageText.Text = _dataList[position]._date.ToString() + "\n" + _dataList[position]._message;
                    view.Tag = chatUserMessagesViewHolderClass;
                    break;
                case 1:
                    view = _context.LayoutInflater.Inflate(Resource.Layout.MessageListWorkerItem, null);
                    chatWorkerMessagesViewHolderClass = new ChatWorkerMessagesViewHolder();
                    chatWorkerMessagesViewHolderClass.messageBox = view.FindViewById<RelativeLayout>(Resource.Id.messageBox);
                    chatWorkerMessagesViewHolderClass.messageText = view.FindViewById<TextView>(Resource.Id.messageText);
                    chatWorkerMessagesViewHolderClass.workerIcon = view.FindViewById<ImageView>(Resource.Id.workerIcon);
                    chatWorkerMessagesViewHolderClass.messageText.Typeface = openSansRegular;
                    chatWorkerMessagesViewHolderClass.messageText.Text = _dataList[position]._date.ToString() + "\n" + _dataList[position]._message;
                    break;
            }
        }
        else
        {
            switch (GetItemViewType(position))
            {
                case 0:
                    chatUserMessagesViewHolderClass = (ChatUserMessagesViewHolder)view.Tag;
                    chatUserMessagesViewHolderClass.messageText.Typeface = openSansRegular;
                    chatUserMessagesViewHolderClass.messageText.Text = _dataList[position]._date.ToString() + "\n" + _dataList[position]._message;
                    break;
                case 1:
                    chatWorkerMessagesViewHolderClass = (ChatWorkerMessagesViewHolder)view.Tag;
                    chatWorkerMessagesViewHolderClass.messageText.Typeface = openSansRegular;
                    chatWorkerMessagesViewHolderClass.messageText.Text = _dataList[position]._date.ToString() + "\n" + _dataList[position]._message;
                    break;
            }
        }
        return view;
    }

    public void Add(MessageData messageData)
    {
        _dataList.Add(messageData);
    }
}
</code>```

答:
As suggest Iulian Popescu according answer for this post solution for this issue is using two different ViewHolder and implementing GetItemViewType adapter's method . In my case that is ChatUserMessagesViewHolder for 1-st chatter's messages and ChatWorkerMessagesViewHolder for 2-nd chatter's messages.
The code of solution is

```<code>class ChatUserMessagesViewHolder : Java.Lang.Object
{
    internal RelativeLayout messageBox;
    internal TextView messageText;
    public void initialize(View view) { }
}
class ChatWorkerMessagesViewHolder : Java.Lang.Object
{
    internal RelativeLayout messageBox;
    internal TextView messageText;
    internal ImageView workerIcon;
    public void initialize(View view) { }
}
public class ChatMessagesAdapter : BaseAdapter
{
    Activity _context;
    List<MessageData> _dataList;

    public ChatMessagesAdapter(Activity context, List<MessageData> dataList)
    {
        _context = context;
        _dataList = dataList;
    }
    public override Java.Lang.Object GetItem(int position)
    {
        return position;
    }
    public override long GetItemId(int position)
    {
        return position;
    }
    public override int Count
    {
        get
        {
            return _dataList.Count;
        }
    }
    public override int GetItemViewType(int position)
    {
        return _dataList[position]._type;
    }
    public override int ViewTypeCount
    {
        get
        {
            return 2;
        }
    }
    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        ChatWorkerMessagesViewHolder chatWorkerMessagesViewHolderClass;
        ChatUserMessagesViewHolder chatUserMessagesViewHolderClass;
        View view;
        view = convertView;
        int layout = _dataList[position]._type == 0 ? Resource.Layout.MessageLitsUserItem : Resource.Layout.MessageListWorkerItem;
        Typeface openSansRegular = Typeface.CreateFromAsset(_context.Assets, "fonts/OpenSans-Regular.ttf");
        if (view == null)
        {
            switch (GetItemViewType(position))
            {
                case 0:
                    view = _context.LayoutInflater.Inflate(Resource.Layout.MessageLitsUserItem, null);
                    chatUserMessagesViewHolderClass = new ChatUserMessagesViewHolder();
                    chatUserMessagesViewHolderClass.messageBox = view.FindViewById<RelativeLayout>(Resource.Id.messageBox);
                    chatUserMessagesViewHolderClass.messageText = view.FindViewById<TextView>(Resource.Id.messageText);
                    chatUserMessagesViewHolderClass.messageText.Typeface = openSansRegular;
                    chatUserMessagesViewHolderClass.messageText.Text = _dataList[position]._date.ToString() + "\n" + _dataList[position]._message;
                    view.Tag = chatUserMessagesViewHolderClass;
                    break;
                case 1:
                    view = _context.LayoutInflater.Inflate(Resource.Layout.MessageListWorkerItem, null);
                    chatWorkerMessagesViewHolderClass = new ChatWorkerMessagesViewHolder();
                    chatWorkerMessagesViewHolderClass.messageBox = view.FindViewById<RelativeLayout>(Resource.Id.messageBox);
                    chatWorkerMessagesViewHolderClass.messageText = view.FindViewById<TextView>(Resource.Id.messageText);
                    chatWorkerMessagesViewHolderClass.workerIcon = view.FindViewById<ImageView>(Resource.Id.workerIcon);
                    chatWorkerMessagesViewHolderClass.messageText.Typeface = openSansRegular;
                    chatWorkerMessagesViewHolderClass.messageText.Text = _dataList[position]._date.ToString() + "\n" + _dataList[position]._message;
                    view.Tag = chatWorkerMessagesViewHolderClass;
                    break;
            }
        }
        else
        {
            switch (GetItemViewType(position))
            {
                case 0:
                    chatUserMessagesViewHolderClass = (ChatUserMessagesViewHolder)view.Tag;
                    chatUserMessagesViewHolderClass.messageText.Typeface = openSansRegular;
                    chatUserMessagesViewHolderClass.messageText.Text = _dataList[position]._date.ToString() + "\n" + _dataList[position]._message;
                    break;
                case 1:
                    chatWorkerMessagesViewHolderClass = (ChatWorkerMessagesViewHolder)view.Tag;
                    chatWorkerMessagesViewHolderClass.messageText.Typeface = openSansRegular;
                    chatWorkerMessagesViewHolderClass.messageText.Text = _dataList[position]._date.ToString() + "\n" + _dataList[position]._message;
                    break;
            }
        }
        return view;
    }

    public void Add(MessageData messageData)
    {
        _dataList.Add(messageData);
    }
}
</code>```

Body:
Hello to all programmers. I try to create simple chat. The first chatter's messages should be in white square with rounded corners, the second chatter's messages should be in blue square with rounded corners and with some icon. So I decided to use listview and adapter for this task. In adapter I use simple set of data {bool type, sting message, DateTime date}. So Adapter Code is

class ChatMessagesViewHolder : Java.Lang.Object
{
    internal TextView chatMessageView;
    public void initialize(View view){}
}
public class ChatMessagesAdapter : BaseAdapter
{
    Activity _context;
    List<MessageData> _dataList;

    public ChatMessagesAdapter(Activity context, List<MessageData> dataList)
    {
        _context = context;
        _dataList = dataList;
    }
    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        ChatMessagesViewHolder chatMessagesViewHolderClass;
        View view;
        view = convertView;
        int layout = _dataList[position]._type == 0 ? Resource.Layout.MessageLitsUserItem:Resource.Layout.MessageListWorkerItem;
        Typeface openSansRegular = Typeface.CreateFromAsset(_context.Assets, "fonts/OpenSans-Regular.ttf");
        if (view == null)
        {
            view = _context.LayoutInflater.Inflate(layout, parent, false);
            chatMessagesViewHolderClass = new ChatMessagesViewHolder();
            chatMessagesViewHolderClass.chatMessageView = view.FindViewById<TextView>(Resource.Id.messageText);
            chatMessagesViewHolderClass.initialize(view);
            view.Tag = chatMessagesViewHolderClass;
        }
        else
        {
            chatMessagesViewHolderClass = (ChatMessagesViewHolder)view.Tag;
        }
        chatMessagesViewHolderClass.chatMessageView.Typeface = openSansRegular;
        chatMessagesViewHolderClass.chatMessageView.Text = _dataList[position]._date.ToString()+"\n"+ _dataList[position]._message;
        return view;
    }
    public void Add(MessageData messageData)
    {
        _dataList.Add(messageData);
    }
}

In Activity I fill Adapter with test information that way - message from 1-st chatter, message from 2-nd chatter. It repeats 10 times.

public class ChatActivity : Activity{
    ListView chatList;
    ChatMessagesAdapter chatAdapter;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.ChatLayout);
        List<MessageData> dataList = new List<MessageData>();
        for (int i = 0; i < 20; i++)
        {
            string message = "Test message from chatter "+(i%2).ToString();
            dataList.Add(new MessageData(i % 2, message, DateTime.Now));
        }
        chatAdapter = new ChatMessagesAdapter(this, dataList);
        chatList.Adapter = chatAdapter;
    }
}

When I run app (in Visual studio emulator for android) first rendering of list is correct, but when I scroll list up/down, the layouts of ListView mixes - 1-st chatter's message sometimes get 2-nd chatter's template (with blue square and icon), 2-nd chatter's message sometimes get 1-st chatter's template (with white square and no icon).
For Example

Can anybody help me with this issue? Any help will be appreciated.

UPDATED

New code of Adapter, updated to work with two different ViewHolders for different type of messages.

class ChatUserMessagesViewHolder : Java.Lang.Object
{
    internal RelativeLayout messageBox;
    internal TextView messageText;
    public void initialize(View view) { }
}
class ChatWorkerMessagesViewHolder : Java.Lang.Object
{
    internal RelativeLayout messageBox;
    internal TextView messageText;
    internal ImageView workerIcon;
    public void initialize(View view) { }
}
public class ChatMessagesAdapter : BaseAdapter
{
    Activity _context;
    List<MessageData> _dataList;

    public ChatMessagesAdapter(Activity context, List<MessageData> dataList)
    {
        _context = context;
        _dataList = dataList;
    }
    public override Java.Lang.Object GetItem(int position)
    {
        return position;
    }
    public override long GetItemId(int position)
    {
        return position;
    }
    public override int Count
    {
        get
        {
            return _dataList.Count;
        }
    }
    public override int GetItemViewType(int position)
    {
        return _dataList[position]._type;
    }
    public override int ViewTypeCount
    {
        get
        {
            return 2;
        }
    }
    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        ChatMessagesViewHolder chatMessagesViewHolderClass;
        ChatWorkerMessagesViewHolder chatWorkerMessagesViewHolderClass;
        ChatUserMessagesViewHolder chatUserMessagesViewHolderClass;
        View view;
        view = convertView;
        int layout = _dataList[position]._type == 0 ? Resource.Layout.MessageLitsUserItem:Resource.Layout.MessageListWorkerItem;
        Typeface openSansRegular = Typeface.CreateFromAsset(_context.Assets, "fonts/OpenSans-Regular.ttf");
        if (view == null)
        {
            switch (GetItemViewType(position))
            {
                case 0:
                    view = _context.LayoutInflater.Inflate(Resource.Layout.MessageLitsUserItem, null);
                    chatUserMessagesViewHolderClass = new ChatUserMessagesViewHolder();
                    chatUserMessagesViewHolderClass.messageBox = view.FindViewById<RelativeLayout>(Resource.Id.messageBox);
                    chatUserMessagesViewHolderClass.messageText = view.FindViewById<TextView>(Resource.Id.messageText);
                    chatUserMessagesViewHolderClass.messageText.Typeface = openSansRegular;
                    chatUserMessagesViewHolderClass.messageText.Text = _dataList[position]._date.ToString() + "\n" + _dataList[position]._message;
                    view.Tag = chatUserMessagesViewHolderClass;
                    break;
                case 1:
                    view = _context.LayoutInflater.Inflate(Resource.Layout.MessageListWorkerItem, null);
                    chatWorkerMessagesViewHolderClass = new ChatWorkerMessagesViewHolder();
                    chatWorkerMessagesViewHolderClass.messageBox = view.FindViewById<RelativeLayout>(Resource.Id.messageBox);
                    chatWorkerMessagesViewHolderClass.messageText = view.FindViewById<TextView>(Resource.Id.messageText);
                    chatWorkerMessagesViewHolderClass.workerIcon = view.FindViewById<ImageView>(Resource.Id.workerIcon);
                    chatWorkerMessagesViewHolderClass.messageText.Typeface = openSansRegular;
                    chatWorkerMessagesViewHolderClass.messageText.Text = _dataList[position]._date.ToString() + "\n" + _dataList[position]._message;
                    break;
            }
        }
        else
        {
            switch (GetItemViewType(position))
            {
                case 0:
                    chatUserMessagesViewHolderClass = (ChatUserMessagesViewHolder)view.Tag;
                    chatUserMessagesViewHolderClass.messageText.Typeface = openSansRegular;
                    chatUserMessagesViewHolderClass.messageText.Text = _dataList[position]._date.ToString() + "\n" + _dataList[position]._message;
                    break;
                case 1:
                    chatWorkerMessagesViewHolderClass = (ChatWorkerMessagesViewHolder)view.Tag;
                    chatWorkerMessagesViewHolderClass.messageText.Typeface = openSansRegular;
                    chatWorkerMessagesViewHolderClass.messageText.Text = _dataList[position]._date.ToString() + "\n" + _dataList[position]._message;
                    break;
            }
        }
        return view;
    }

    public void Add(MessageData messageData)
    {
        _dataList.Add(messageData);
    }
}

Body:
As suggest Iulian Popescu according answer for this post solution for this issue is using two different ViewHolder and implementing GetItemViewType adapter's method . In my case that is ChatUserMessagesViewHolder for 1-st chatter's messages and ChatWorkerMessagesViewHolder for 2-nd chatter's messages.
The code of solution is

class ChatUserMessagesViewHolder : Java.Lang.Object
{
    internal RelativeLayout messageBox;
    internal TextView messageText;
    public void initialize(View view) { }
}
class ChatWorkerMessagesViewHolder : Java.Lang.Object
{
    internal RelativeLayout messageBox;
    internal TextView messageText;
    internal ImageView workerIcon;
    public void initialize(View view) { }
}
public class ChatMessagesAdapter : BaseAdapter
{
    Activity _context;
    List<MessageData> _dataList;

    public ChatMessagesAdapter(Activity context, List<MessageData> dataList)
    {
        _context = context;
        _dataList = dataList;
    }
    public override Java.Lang.Object GetItem(int position)
    {
        return position;
    }
    public override long GetItemId(int position)
    {
        return position;
    }
    public override int Count
    {
        get
        {
            return _dataList.Count;
        }
    }
    public override int GetItemViewType(int position)
    {
        return _dataList[position]._type;
    }
    public override int ViewTypeCount
    {
        get
        {
            return 2;
        }
    }
    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        ChatWorkerMessagesViewHolder chatWorkerMessagesViewHolderClass;
        ChatUserMessagesViewHolder chatUserMessagesViewHolderClass;
        View view;
        view = convertView;
        int layout = _dataList[position]._type == 0 ? Resource.Layout.MessageLitsUserItem : Resource.Layout.MessageListWorkerItem;
        Typeface openSansRegular = Typeface.CreateFromAsset(_context.Assets, "fonts/OpenSans-Regular.ttf");
        if (view == null)
        {
            switch (GetItemViewType(position))
            {
                case 0:
                    view = _context.LayoutInflater.Inflate(Resource.Layout.MessageLitsUserItem, null);
                    chatUserMessagesViewHolderClass = new ChatUserMessagesViewHolder();
                    chatUserMessagesViewHolderClass.messageBox = view.FindViewById<RelativeLayout>(Resource.Id.messageBox);
                    chatUserMessagesViewHolderClass.messageText = view.FindViewById<TextView>(Resource.Id.messageText);
                    chatUserMessagesViewHolderClass.messageText.Typeface = openSansRegular;
                    chatUserMessagesViewHolderClass.messageText.Text = _dataList[position]._date.ToString() + "\n" + _dataList[position]._message;
                    view.Tag = chatUserMessagesViewHolderClass;
                    break;
                case 1:
                    view = _context.LayoutInflater.Inflate(Resource.Layout.MessageListWorkerItem, null);
                    chatWorkerMessagesViewHolderClass = new ChatWorkerMessagesViewHolder();
                    chatWorkerMessagesViewHolderClass.messageBox = view.FindViewById<RelativeLayout>(Resource.Id.messageBox);
                    chatWorkerMessagesViewHolderClass.messageText = view.FindViewById<TextView>(Resource.Id.messageText);
                    chatWorkerMessagesViewHolderClass.workerIcon = view.FindViewById<ImageView>(Resource.Id.workerIcon);
                    chatWorkerMessagesViewHolderClass.messageText.Typeface = openSansRegular;
                    chatWorkerMessagesViewHolderClass.messageText.Text = _dataList[position]._date.ToString() + "\n" + _dataList[position]._message;
                    view.Tag = chatWorkerMessagesViewHolderClass;
                    break;
            }
        }
        else
        {
            switch (GetItemViewType(position))
            {
                case 0:
                    chatUserMessagesViewHolderClass = (ChatUserMessagesViewHolder)view.Tag;
                    chatUserMessagesViewHolderClass.messageText.Typeface = openSansRegular;
                    chatUserMessagesViewHolderClass.messageText.Text = _dataList[position]._date.ToString() + "\n" + _dataList[position]._message;
                    break;
                case 1:
                    chatWorkerMessagesViewHolderClass = (ChatWorkerMessagesViewHolder)view.Tag;
                    chatWorkerMessagesViewHolderClass.messageText.Typeface = openSansRegular;
                    chatWorkerMessagesViewHolderClass.messageText.Text = _dataList[position]._date.ToString() + "\n" + _dataList[position]._message;
                    break;
            }
        }
        return view;
    }

    public void Add(MessageData messageData)
    {
        _dataList.Add(messageData);
    }
}


来源: stackexchange

问:
How to read Plist file from server and directly use it without creating local file?
I'm working on a project and I have some setting on the server which I got through the Plist file and I want to read this Plist file without creating any local copy.

Need to store this setting in the dictionary, not in the local Plist file.

any idea how can we do this?

Sample Plist like below:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>New item</key>
    <array>
        <dict>
            <key>value</key>
            <string>Data1</string>
            <key>key</key>
            <string>Tab1</string>
        </dict>
        <dict>
            <key>value</key>
            <string>Data2</string>
            <key>key</key>
            <string>Tab2</string>
        </dict>
    </array>
</dict>
</plist>
</code>```

Let me know if required more detail on this.

Thanks in advance!

答:
It's almost the same like loading and parsing JSON. Instead of JSONSerialization use PropertyListSerialization.

```<code>let urlString = "http://server.com/api"

let url = URL(string: urlString)
URLSession.shared.dataTask(with:url!) { data, _, error in
  if let error = error { print(error); return }
  do {
      let plistDictionary = try PropertyListSerialization.propertyList(from: data!, format: nil) as! [String:Any]
      print(plistDictionary)
  } catch {
      print(error)
  }
}.resume()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm working on a project and I have some setting on the server which I got through the Plist file and I want to read this Plist file without creating any local copy.

Need to store this setting in the dictionary, not in the local Plist file.

any idea how can we do this?

Sample Plist like below:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>New item</key>
    <array>
        <dict>
            <key>value</key>
            <string>Data1</string>
            <key>key</key>
            <string>Tab1</string>
        </dict>
        <dict>
            <key>value</key>
            <string>Data2</string>
            <key>key</key>
            <string>Tab2</string>
        </dict>
    </array>
</dict>
</plist>

Let me know if required more detail on this.

Thanks in advance!

Body:
It's almost the same like loading and parsing JSON. Instead of JSONSerialization use PropertyListSerialization.

let urlString = "http://server.com/api"

let url = URL(string: urlString)
URLSession.shared.dataTask(with:url!) { data, _, error in
  if let error = error { print(error); return }
  do {
      let plistDictionary = try PropertyListSerialization.propertyList(from: data!, format: nil) as! [String:Any]
      print(plistDictionary)
  } catch {
      print(error)
  }
}.resume()


问:
Is it possible to compress video on Android?
I want to do video compression.

Actually in my application I want to have two options, one is low and another is high. If I choose the low option then the application will compress the video and then upload it. If I choose high then it will upload the original video which I have recorded itself.

I want to do this thing in my application and I'm confused. I have searched google a lot but I'm not able to find the useful way to solve this question please if anyone can help me out.

答:
Yes in android you can us ffmpeg4android for compress video it's native library

Please check this link

ffmpeg4android Code

Install the Android NDK First to Use it

ContentLicense: CC BY-SA 3.0


问:
Why does this code return a list index error?
Basically it's supposed to take a set of coordinates and return a list of coordinates of it's neighbors. However, when it hits here:

```<code>if result[i][0] < 0 or result[i][0] >= board.dimensions:
    result.pop(i)
</code>```

when i is 2, it gives me an out of index error. I can manage to have it print result[2][0] but at the if statement it throws the errors. Why is this happening?

```<code>def neighborGen(row,col,board):
    """
    returns lists of coords of neighbors, in order of up, down, left, right
    """

    result = []
    result.append([row-1 , col])
    result.append([row+1 , col])
    result.append([row , col-1])
    result.append([row , col+1])

     #prune off invalid neighbors (such as (0,-1), etc etc)
     for i in range(len(result)):
        if result[i][0] < 0 or result[i][0] >= board.dimensions:
            result.pop(i)
        if result[i][1] < 0 or result[i][1] >= board.dimensions:
            result.pop(i)

    return result
</code>```

答: During the for loop, you are popping elements which decreases the size of result. Yet, i will still go from 0 to 4.

Body:
Basically it's supposed to take a set of coordinates and return a list of coordinates of it's neighbors. However, when it hits here:

if result[i][0] < 0 or result[i][0] >= board.dimensions:
    result.pop(i)

when i is 2, it gives me an out of index error. I can manage to have it print result[2][0] but at the if statement it throws the errors. Why is this happening?

def neighborGen(row,col,board):
    """
    returns lists of coords of neighbors, in order of up, down, left, right
    """

    result = []
    result.append([row-1 , col])
    result.append([row+1 , col])
    result.append([row , col-1])
    result.append([row , col+1])

     #prune off invalid neighbors (such as (0,-1), etc etc)
     for i in range(len(result)):
        if result[i][0] < 0 or result[i][0] >= board.dimensions:
            result.pop(i)
        if result[i][1] < 0 or result[i][1] >= board.dimensions:
            result.pop(i)

    return result

ContentLicense: CC BY-SA 2.5


问:
Make and reflect changes to popup.html in chrome extension
I am new to chrome extensions. I am trying to make a basic extension which updates the value to an input field in the popup page every few seconds. Here is my current code.

manifest.json

```<code>{
 "manifest_version": 2,
 "name": "Test extension",
 "version": "1",
 "browser_action": {
    "default_icon": "tl.png",
    "default_popup": "layout.html"
 },
 "background": {
    "scripts": ["jquery-3.2.1.min.js","addvalues.js"],
    "persistent": false
 },

 "permissions": [
        "alarms",
        "tabs",
        "webNavigation"
   ]

}
</code>```

layout.html

```<code><html>
<head>
    <script src="jquery-3.2.1.min.js"></script>
    <script src="addvalues.js"></script>
</head>

<body>
    <label for="pfvalue"> Portfolio value </label>
    <input id="pfvalue" readonly style="border:0; color:#f6931f; font-weight:bold; padding-bottom: 10px;">

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

addvalues.js

```<code>$(function()
{
    var i=0;
    var portvalue;
    function getData()
    {
        portvalue = i;
        $("#pfvalue").val(portvalue);
        i++;
        console.log(portvalue);
    }

    getData();
    chrome.alarms.create("fetch data",{periodInMinutes: 0.1});
    chrome.alarms.onAlarm.addListener(getData);
});
</code>```

When I keep the popup page open for long enough, the input value does change like it is supposed to. But when I close it and then open it again, the popup page resets to the initial state of showing 0. I am not able to figure out why this happens.

The console shows the right value of portvalue (i.e. the one that gets updated every 6 seconds).

Thanks in advance.

答:
Make sure to read the extension architecture overview: the popup is a separate page that exists only while shown. To view its devtools and console rightclick the popup and click Inspect.

A background/event page is a separate, hidden page with its own DOM so no need to load jQuery there.

Your background page can increment the value and store it via chrome.storage.local.set

Your popup.js (a different script) can use chrome.storage.local.get on startup and chrome.storage.onChanged to detect the changes

It's meaningless to use an event page ("persistent" : false in your manifest.json) if you wake it up every 6 seconds because an event page is unloaded automatically after 5 seconds since its last activation, meaning your event page currently gets unloaded every 6 seconds for just 1 second. That's a waste of the computer resources: every time it loads the browser needs to parse it, compile it, optimize it and so on.

Body:
I am new to chrome extensions. I am trying to make a basic extension which updates the value to an input field in the popup page every few seconds. Here is my current code.

manifest.json

{
 "manifest_version": 2,
 "name": "Test extension",
 "version": "1",
 "browser_action": {
    "default_icon": "tl.png",
    "default_popup": "layout.html"
 },
 "background": {
    "scripts": ["jquery-3.2.1.min.js","addvalues.js"],
    "persistent": false
 },

 "permissions": [
        "alarms",
        "tabs",
        "webNavigation"
   ]

}

layout.html

     Portfolio value
    <input id="pfvalue" readonly style="border:0; color:#f6931f; font-weight:bold; padding-bottom: 10px;">

addvalues.js

$(function()
{
    var i=0;
    var portvalue;
    function getData()
    {
        portvalue = i;
        $("#pfvalue").val(portvalue);
        i++;
        console.log(portvalue);
    }

    getData();
    chrome.alarms.create("fetch data",{periodInMinutes: 0.1});
    chrome.alarms.onAlarm.addListener(getData);
});

When I keep the popup page open for long enough, the input value does change like it is supposed to. But when I close it and then open it again, the popup page resets to the initial state of showing 0. I am not able to figure out why this happens.

The console shows the right value of portvalue (i.e. the one that gets updated every 6 seconds).

Thanks in advance.


问:
How to create a table with 3 columns in iOS App?(Objective C)

Want to create a table as shown in the image in iOS Xcode

Unable to remove space between cells Using Collection view as in the image below:

enter image description here

答:
If you need to achieve this using UITableView, you have to customise UITableViewCell.

Otherwise its better to do with UICollectionView


问:
Generate jenkins jobs for all github repos
I would like to set up some automation inside Jenkins that periodically polls the list of repos in our github organization and automatically sets up a jenkins job for each of that Git repos based on a job template.

What would be a possible solution to achieve this? Thanks!

答:
Jenkins Pipeline is nowadays the way to go.

It defines pipelines using a Jenkinsfile, which you can check into your repos.

Which the best practice is a file like this

```<code>pipeline {
    agent any

    stages {
        stage('Build') {
            steps {
                echo 'Building..'
            }
        }
        stage('Test') {
            steps {
                echo 'Testing..'
            }
        }
        stage('Deploy') {
            steps {
                echo 'Deploying....'
            }
        }
    }
}
</code>```

As described in the documentation.

Body:
Jenkins Pipeline is nowadays the way to go.

It defines pipelines using a Jenkinsfile, which you can check into your repos.

Which the best practice is a file like this

pipeline {
    agent any

    stages {
        stage('Build') {
            steps {
                echo 'Building..'
            }
        }
        stage('Test') {
            steps {
                echo 'Testing..'
            }
        }
        stage('Deploy') {
            steps {
                echo 'Deploying....'
            }
        }
    }
}

As described in the documentation.


问:
After uploaded a image, resized with JS and saved in PHP, how do I send the resized file via email using PHPMAILER?
I am from Brazil. SO, I am sorry for my bad english.
 I will give my best to explain what I need
 I am new to javascript and php...

I use a javascript where its resize the image before the upload. OK.
 After that, I use php to save the resized image to my server. OK.

What I need now is... how do I get this resized image and send via email using PHPMAILER ??

Here is the codes :

index.html

```<code><!DOCTYPE html>
<html>

<head>

    <meta charset="utf-8">
    <title>Cadastro de Foto</title>

    <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
    <script src="js/canvas-to-blob.min.js"></script>
    <script src="js/resize.js"></script>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

    <script type="text/javascript">

        // Iniciando biblioteca
        var resize = new window.resize();
        resize.init();

        // Declarando variáveis
        var imagens;
        var imagem_atual;

        // Quando carregado a página
        $(function ($) {

            // Quando selecionado as imagens
            $('#imagem').on('change', function () {
                enviar();
            });

        });

        /*
         Envia os arquivos selecionados
         */
        function enviar()
        {
            // Verificando se o navegador tem suporte aos recursos para redimensionamento
            if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
                alert('O navegador não suporta os recursos utilizados pelo aplicativo');
                return;
            }

            // Alocando imagens selecionadas
            imagens = $('#imagem')[0].files;

            // Se selecionado pelo menos uma imagem
            if (imagens.length > 0)
            {
                // Definindo progresso de carregamento
                $('#progresso').attr('aria-valuenow', 0).css('width', '0%');

                // Escondendo campo de imagem
                $('#imagem').hide();

                // Iniciando redimensionamento
                imagem_atual = 0;
                redimensionar();
            }
        }

        /*
         Redimensiona uma imagem e passa para a próxima recursivamente
         */
        function redimensionar()
        {
            // Se redimensionado todas as imagens
            if (imagem_atual > imagens.length)
            {
                // Definindo progresso de finalizado
                $('#progresso').html('Imagen(s) enviada(s) com sucesso');

                // Limpando imagens
                limpar();

                // Exibindo campo de imagem
                $('#imagem').show();

                // Finalizando
                return;
            }

            // Se não for um arquivo válido
            if ((typeof imagens[imagem_atual] !== 'object') || (imagens[imagem_atual] == null))
            {
                // Passa para a próxima imagem
                imagem_atual++;
                redimensionar();
                return;
            }

            // Redimensionando
            resize.photo(imagens[imagem_atual], 800, 'dataURL', function (imagem) {

                // Salvando imagem no servidor
                $.post('ajax/salvar.php', {imagem: imagem}, function() {

                    // Definindo porcentagem
                    var porcentagem = (imagem_atual + 1) / imagens.length * 100;

                    // Atualizando barra de progresso
                    $('#progresso').text(Math.round(porcentagem) + '%').attr('aria-valuenow', porcentagem).css('width', porcentagem + '%');

                    // Aplica delay de 1 segundo
                    // Apenas para evitar sobrecarga de requisições
                    // e ficar visualmente melhor o progresso
                    setTimeout(function () {
                        // Passa para a próxima imagem
                        imagem_atual++;
                        redimensionar();
                    }, 1000);

                });

            });
        }

        /*
         Limpa os arquivos selecionados
         */
        function limpar()
        {
            var input = $("#imagem");
            input.replaceWith(input.val('').clone(true));
        }
    </script>
</head>

<body>

<div class="container">

    <h1>Cadastro de Foto</h1>

    <form method="post" action="#" role="form">

        <div class="progress">
            <div id="progresso" class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="0"
                 aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>
        </div>

        <div class="form-group row">

            <div class="col-xs-12">
                <input id="imagem" type="file" accept="image/*" multiple/>
            </div>

        </div>

    </form>

</div>

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

Below is the php where save the resized file

salvar.php

```<code><?php
   $imagem = $_POST['imagem'];
   list($tipo, $dados) = explode(';', $imagem);
   list(, $tipo) = explode(':', $tipo);
   list(, $dados) = explode(',', $dados);
   $dados = base64_decode($dados);
   $nome = md5(uniqid(time()));
   file_put_contents("../img/{$nome}.jpg", $dados);
 ?>
</code>```

Ok.. After saved the resized file, I need to send this file via email using phpmailer.. to my own email address.. Once I am collecting data.

How do I do that ??
 please, help me

答:
Please try the below Code to send email using PHPMAILER:

```<code><?php
require_once 'class.phpmailer.php';
$mail = new PHPMailer();
// Now you only need to add the necessary stuff

// HTML body

$body = "```

";
$body .= " Hello Dimitrios
";
$body .= "Your personal photograph to this message.
";
$body .= "Sincerely,
";
$body .= "phpmailer test message ";
$body .= "
" ;

// And the absolute required configurations for sending HTML with attachement
$fileName = 'path_of_image/image.jpg';
$mail->AddAddress("sendemailto@mail.zz", "My-webpage Website");
$mail->Subject = "test for phpmailer-3";
$mail->MsgHTML($body);
$mail->AddAttachment($fileName);
if(!$mail->Send()) {
echo "There was an error sending the message";
exit;
}
echo "Message was sent successfully";

?>
```

<p><strong>Updated Code</strong></p>

```<?php
    require_once 'class.phpmailer.php';
    $mail = new PHPMailer();
    // Now you only need to add the necessary stuff

    // HTML body

    $imagem = $_POST['imagem'];
    list($tipo, $dados) = explode(';', $imagem);
    list(, $tipo) = explode(':', $tipo);
    list(, $dados) = explode(',', $dados);
    $dados = base64_decode($dados);
    $nome = md5(uniqid(time()));
    file_put_contents("img/{$nome}.jpg", $dados);

    $body = "```
    <div>";
    $body .= " Hello Dimitrios
    ";
    $body .= "<i>Your</i> personal photograph to this message.
    ";
    $body .= "Sincerely,
    ";
    $body .= "phpmailer test message ";
    $body .= "</div>" ;

    // And the absolute required configurations for sending HTML with attachement
    $fileName = 'img/'.$nome.'.jpg';
    $mail->AddAddress("sendemailto@mail.zz", "My-webpage Website");
    $mail->Subject = "test for phpmailer-3";
    $mail->MsgHTML($body);
    $mail->AddAttachment($fileName);
    if(!$mail->Send()) {
    echo "There was an error sending the message";
    exit;
    }
    echo "Message was sent successfully";

    ?>
</code>```

Body:
I am from Brazil. SO, I am sorry for my bad english.
 I will give my best to explain what I need
 I am new to javascript and php...

I use a javascript where its resize the image before the upload. OK.
 After that, I use php to save the resized image to my server. OK.

What I need now is... how do I get this resized image and send via email using PHPMAILER ??

Here is the codes :

index.html

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Cadastro de Foto</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

Cadastro de Foto

    <form method="post" action="#" role="form">

                <input id="imagem" type="file" accept="image/*" multiple/>

    </form>

Below is the php where save the resized file

salvar.php

<?php
   $imagem = $_POST['imagem'];
   list($tipo, $dados) = explode(';', $imagem);
   list(, $tipo) = explode(':', $tipo);
   list(, $dados) = explode(',', $dados);
   $dados = base64_decode($dados);
   $nome = md5(uniqid(time()));
   file_put_contents("../img/{$nome}.jpg", $dados);
 ?>

Ok.. After saved the resized file, I need to send this file via email using phpmailer.. to my own email address.. Once I am collecting data.

How do I do that ??
 please, help me

Body:
Please try the below Code to send email using PHPMAILER:

<?php
require_once 'class.phpmailer.php';
$mail = new PHPMailer();
// Now you only need to add the necessary stuff

// HTML body

$body = "</pre>
<div>";
$body .= " Hello Dimitrios
";
$body .= "<i>Your</i> personal photograph to this message.
";
$body .= "Sincerely,
";
$body .= "phpmailer test message ";
$body .= "</div>" ;

// And the absolute required configurations for sending HTML with attachement
$fileName = 'path_of_image/image.jpg';
$mail->AddAddress("sendemailto@mail.zz", "My-webpage Website");
$mail->Subject = "test for phpmailer-3";
$mail->MsgHTML($body);
$mail->AddAttachment($fileName);
if(!$mail->Send()) {
echo "There was an error sending the message";
exit;
}
echo "Message was sent successfully";

?>

Updated Code

<?php
    require_once 'class.phpmailer.php';
    $mail = new PHPMailer();
    // Now you only need to add the necessary stuff

    // HTML body

    $imagem = $_POST['imagem'];
    list($tipo, $dados) = explode(';', $imagem);
    list(, $tipo) = explode(':', $tipo);
    list(, $dados) = explode(',', $dados);
    $dados = base64_decode($dados);
    $nome = md5(uniqid(time()));
    file_put_contents("img/{$nome}.jpg", $dados);

    $body = "</pre>
    <div>";
    $body .= " Hello Dimitrios
    ";
    $body .= "<i>Your</i> personal photograph to this message.
    ";
    $body .= "Sincerely,
    ";
    $body .= "phpmailer test message ";
    $body .= "</div>" ;

    // And the absolute required configurations for sending HTML with attachement
    $fileName = 'img/'.$nome.'.jpg';
    $mail->AddAddress("sendemailto@mail.zz", "My-webpage Website");
    $mail->Subject = "test for phpmailer-3";
    $mail->MsgHTML($body);
    $mail->AddAttachment($fileName);
    if(!$mail->Send()) {
    echo "There was an error sending the message";
    exit;
    }
    echo "Message was sent successfully";

    ?>


问:
Only createdAt column in join table
By default, sequelize will create createdAt and updatedAt columns in join table for many to many relationships but I only want to use createdAt column and set it automatically when row created.

custom UserJob model:

```<code>const UserJob = sequelize.define('UserJob', {
    createdAt: DataTypes.DATE
}, {
    timestamps: false
});
UserJob.beforeCreate((userJob, options) => {
    console.log('before create');
    userJob.createdAt = new Date();
});
return UserJob;
</code>```

Associations:

```<code>User.belongsToMany(models.Job, {through: UserJob, foreignKey: 'user_id'});
Job.belongsToMany(models.User, {through: UserJob, foreignKey: 'job_id'});
</code>```

it doesn't set createdAt, what should I do?

答:
As sequelize suggests, if you don't want a particular timestamp
You should define your model as

```<code>const Foo = sequelize.define('foo', { /* bla */
  { // don't forget to enable timestamps!
  timestamps: true,
  // I don't want createdAt
  createdAt: false,
  // I want updatedAt to actually be called updateTimestamp
  updatedAt: 'updateTimestamp'
})
</code>```

So for your case, you could set updatedAt to false, that way the column won't exist.
And would be more cleaner than using a hook.

Title: Only createdAt column in join table

Body:
By default, sequelize will create createdAt and updatedAt columns in join table for many to many relationships but I only want to use createdAt column and set it automatically when row created.

custom UserJob model:

const UserJob = sequelize.define('UserJob', {
    createdAt: DataTypes.DATE
}, {
    timestamps: false
});
UserJob.beforeCreate((userJob, options) => {
    console.log('before create');
    userJob.createdAt = new Date();
});
return UserJob;

Associations:

User.belongsToMany(models.Job, {through: UserJob, foreignKey: 'user_id'});
Job.belongsToMany(models.User, {through: UserJob, foreignKey: 'job_id'});

it doesn't set createdAt, what should I do?

Body:
As sequelize suggests, if you don't want a particular timestamp
You should define your model as

const Foo = sequelize.define('foo', { /* bla */
  { // don't forget to enable timestamps!
  timestamps: true,
  // I don't want createdAt
  createdAt: false,
  // I want updatedAt to actually be called updateTimestamp
  updatedAt: 'updateTimestamp'
})

So for your case, you could set updatedAt to false, that way the column won't exist.
And would be more cleaner than using a hook.


问:
Importing .csv file into a Oracle Forms application
I've got a question how to import a .csv file into a Oracle Forms application.
We are using Oracle Forms 11g on a Oracle 12c Database.

Now we want to import a .csv file with the Forms applicationso our customers can import this file and write the data into the database.

My plan is to create an application where the user can import a .csv file with a filechooser. The data from the .csv will be read and an output shows the user the data in this application. Then the user should be able to save it into the database through a button.

I've tried several searches but haven't found the right solution for this kind of problem. The only solutions I've found were a direct import of a .csv file into a database but not through Oracle Forms

Is it even possible to load .csv files in Oracle Forms?

If anyone has a good solution or anything else that might be helpfull i would be thankfull for that.

答:
I've found a suitable solution for me now. Maybe I could do it better but this helps me so far.

I've found the following Blog: http://tfathy.blogspot.de/2009/03/reading-from-file.html

The Code works 100% by copy&paste and helps me from now on to complete the task.

Maybe it might help anyone else too.

Here is the solutioncode:

```<code>Reading From File
March 19, 2009
--------------------------------------------------
Declare
  vfilename varchar2(500);
  in_file   Client_Text_IO.File_Type;
  linebuf   VARCHAR2(1800);
BEGIN
    vfilename := client_get_file_name('c:/temp/', File_Filter=>'Comma Dialimeted Files (*.csv)|*.csv|');
    in_file := client_Text_IO.Fopen(vfilename, 'r');
    GO_BLOCK('Emp');
    FIRST_RECORD;
  LOOP
    Client_Text_IO.Get_Line(in_file, linebuf);
    p_output_line(linebuf);
    Client_Text_IO.New_Line;
    Next_record;
  END LOOP;
   FIRST_RECORD;
EXCEPTION
  WHEN no_data_found THEN
    Client_Text_IO.Put_Line('Closing the file...');
    Client_Text_IO.Fclose(in_file);
END;
-------------------------------------------------------
PROCEDURE p_output_line(p_line varchar2) IS
vLINE VARCHAR2(4000);
vVALUE VARCHAR2(1000);
vCOMMA_COUNT NUMBER;
vREPORT_DATE DATE;
BEGIN
 vLINE := p_line;
 vCOMMA_COUNT := LENGTH(vLINE)- LENGTH(REPLACE(vLINE,',','')); -- COUNT THE NUMBER OF COMMAS
  FOR I IN 1.. vCOMMA_COUNT+1 LOOP
   vVALUE := SUBSTR(vLINE,1,INSTR(vLINE,',')-1);                             -- IF vLINE = 123,ABC,9877 THEN VVALUE WILL BE  123
    IF vVALUE IS NULL THEN
        vVALUE := vLINE;
    END IF;
   vLINE := SUBSTR(vLINE,INSTR(vLINE,',')+1) ;                              -- CHANGE   123,ABC,9877 TO BE   ABC,9877
   IF I = 1 THEN
    :DATA.BMK_NAME := vVALUE;
   ELSIF I = 2 THEN
    vREPORT_DATE := last_day(to_date(vVALUE,'dd-mm-yyyy'));
    :DATA.REPORT_DATE := vREPORT_DATE;
   ELSIF I = 3 THEN
    :DATA.BMK_RETURN := to_number(vVALUE);
   END IF;
  END LOOP;
  EXCEPTION
    WHEN NO_DATA_FOUND THEN
    MESSAGE('Please Check the data type is appropriate on you excel file');
    MESSAGE('Please Check the data type is appropriate on you excel file');
END;
-----------------------------------------------------------------------
-- notes
1- you must install webutil version 106 or later
2- make sure that you attached and compiled the webutill.pll scucessfuly
</code>```

Body:
I've found a suitable solution for me now. Maybe I could do it better but this helps me so far.

I've found the following Blog: http://tfathy.blogspot.de/2009/03/reading-from-file.html

The Code works 100% by copy&paste and helps me from now on to complete the task.

Maybe it might help anyone else too.

Here is the solutioncode:

Reading From File
March 19, 2009
--------------------------------------------------
Declare
  vfilename varchar2(500);
  in_file   Client_Text_IO.File_Type;
  linebuf   VARCHAR2(1800);
BEGIN
    vfilename := client_get_file_name('c:/temp/', File_Filter=>'Comma Dialimeted Files (*.csv)|*.csv|');
    in_file := client_Text_IO.Fopen(vfilename, 'r');
    GO_BLOCK('Emp');
    FIRST_RECORD;
  LOOP
    Client_Text_IO.Get_Line(in_file, linebuf);
    p_output_line(linebuf);
    Client_Text_IO.New_Line;
    Next_record;
  END LOOP;
   FIRST_RECORD;
EXCEPTION
  WHEN no_data_found THEN
    Client_Text_IO.Put_Line('Closing the file...');
    Client_Text_IO.Fclose(in_file);
END;
-------------------------------------------------------
PROCEDURE p_output_line(p_line varchar2) IS
vLINE VARCHAR2(4000);
vVALUE VARCHAR2(1000);
vCOMMA_COUNT NUMBER;
vREPORT_DATE DATE;
BEGIN
 vLINE := p_line;
 vCOMMA_COUNT := LENGTH(vLINE)- LENGTH(REPLACE(vLINE,',','')); -- COUNT THE NUMBER OF COMMAS
  FOR I IN 1.. vCOMMA_COUNT+1 LOOP
   vVALUE := SUBSTR(vLINE,1,INSTR(vLINE,',')-1);                             -- IF vLINE = 123,ABC,9877 THEN VVALUE WILL BE  123
    IF vVALUE IS NULL THEN
        vVALUE := vLINE;
    END IF;
   vLINE := SUBSTR(vLINE,INSTR(vLINE,',')+1) ;                              -- CHANGE   123,ABC,9877 TO BE   ABC,9877
   IF I = 1 THEN
    :DATA.BMK_NAME := vVALUE;
   ELSIF I = 2 THEN
    vREPORT_DATE := last_day(to_date(vVALUE,'dd-mm-yyyy'));
    :DATA.REPORT_DATE := vREPORT_DATE;
   ELSIF I = 3 THEN
    :DATA.BMK_RETURN := to_number(vVALUE);
   END IF;
  END LOOP;
  EXCEPTION
    WHEN NO_DATA_FOUND THEN
    MESSAGE('Please Check the data type is appropriate on you excel file');
    MESSAGE('Please Check the data type is appropriate on you excel file');
END;
-----------------------------------------------------------------------
-- notes
1- you must install webutil version 106 or later
2- make sure that you attached and compiled the webutill.pll scucessfuly


问:
How to show 6 images in each slide of flexslider?
I have a question on flexslider
I am trying to build a slider using flexslider such that

For desktop (window screen size >= 1200 px), I have six horizonttal images in each slides

For mobile or tablet (window screen size < 1200px), I have four images in each slide such that the four images are in a 2 by 2 grid always

Here is a sample codepen
https://codepen.io/hellouniverse/pen/LLJzgM

I have it almost working. In mobile, I am seeing 4 images in 2 by 2 grid. However, in desktop, I see 6 images for the first slide. For the subsequent slides, I also expected 6 images like the first ones. However I am seeing all the remaining.

I am slicing it as below and wrapping ul

```<code>// Wrap uls
for (var i = 0; i < item.length; i += dataItem) {
  item.slice(i, i + dataItem).wrapAll('<ul class="items"></ul>');
}
</code>```

However, I think I must have made mistake in slicing probably. May someone please see if this can be made such that in desktop we have 6 images horizontally for each slides keeping everything else as it is now.

My html looks like

```<code><div id="flexslider" class="flexslider" data-item="4">
  <ul class="slides">
    <li class="item"> <img src="http://placehold.it/1200x600" alt="placeholder image"></li>
    <li class="item"> <img src="http://placehold.it/1200x600" alt="placeholder image"></li>
    <li class="item"> <img src="http://placehold.it/1200x600" alt="placeholder image"></li>
    <li class="item"> <img src="http://placehold.it/1200x600" alt="placeholder image"></li>
    <li class="item"> <img src="http://placehold.it/1200x600" alt="placeholder image"></li>
    <li class="item"> <img src="http://placehold.it/1200x600" alt="placeholder image"></li>
    <li class="item"> <img src="http://placehold.it/1200x600" alt="placeholder image"></li>
    <li class="item"> <img src="http://placehold.it/1200x600" alt="placeholder image"></li>
    <li class="item"> <img src="http://placehold.it/1200x600" alt="placeholder image"></li>
    <li class="item"> <img src="http://placehold.it/1200x600" alt="placeholder image"></li>
    <li class="item"> <img src="http://placehold.it/1200x600" alt="placeholder image"></li>
    <li class="item"> <img src="http://placehold.it/1200x600" alt="placeholder image"></li>
    <li class="item"> <img src="http://placehold.it/1200x600" alt="placeholder image"></li>
    <li class="item"> <img src="http://placehold.it/1200x600" alt="placeholder image"></li>
    <li class="item"> <img src="http://placehold.it/1200x600" alt="placeholder image"></li>
    <li class="item"> <img src="http://placehold.it/1200x600" alt="placeholder image"></li>
    <li class="item"> <img src="http://placehold.it/1200x600" alt="placeholder image"></li>
    <li class="item"> <img src="http://placehold.it/1200x600" alt="placeholder image"></li>
  </ul>
</div>
</code>```

and my scss code looks like below

```<code>ul,
li {
  margin: 0;
  padding: 0;
}

@media screen and (max-width: 1199px) {
  .flexslider {
      .slides {
          .items {
              display: flex !important;
              flex-wrap: wrap !important;

              item {
                  border: 1px solid red;
              }
          }

          .item {
              background: #ccc;
              margin: 10px;
              padding: 5px;
              text-align: center;
              flex-basis: calc(50% - 40px);
              /* Need to tweak!*/
              list-style-type: none;
          }
      }
  }
}

@media screen and (min-width: 1200px) {
  .flexslider {
      .slides {
          .items {
              display: flex !important;
              //flex-wrap: wrap !important;
              item {
                  border: 1px solid red;
              }
          }

          .item {
              background: #ccc;
              margin: 10px;
              padding: 5px;
              text-align: center;
              flex-basis: calc(100% / 6);
              /* Need to tweak!*/
              list-style-type: none;
          }
      }
  }
}
</code>```

And my js looks like below

```<code>var fs = $(".flexslider"),
  dataItem = fs.data("item"),
  item = fs.find(".item");

//console.log('item', item.length);

//var dataItem = $(".flexslider").attr("data-type");
if ($(window).width() >= 1200) {
  var el = document.getElementById("flexslider");
  el.setAttribute("data-item", "6");
  dataItem = el.getAttribute("data-item");
}

console.log('dataItem', dataItem);
console.log('length of item', item.length);

// Wrap uls
for (var i = 0; i < item.length; i += dataItem) {
  item.slice(i, i + dataItem).wrapAll('<ul class="items"></ul>');
}

// Initialize flexslider
$(window).load(function() {
  fs.flexslider({
    selector: ".slides > .items",
    animation: "slide",
    animationLoop: false,
    directionNav: true,
    slideshow: false,
    smoothHeight: true,
    itemMargin: 0,
    minItems: 1,
    maxItems: 1
  });
});
</code>```

答:
On desktop versions, I only want to see 6 images.. But I see 6 + 1/2 of 7 sometimes and sometimes 5 and 1/2 of left and right

Maxwidth is 1200px. So if you want to show 6 items, each item will have only 200px right? But in your css code, you have margin: 20px for each item.That means each item will take 240px.

For 2x2 grid view on Mobile, my solution is you will have a new html structure to show 2 images on each
 tag.

This is my demo code: https://codepen.io/anon/pen/qjMRdG

Body:
I have a question on flexslider
I am trying to build a slider using flexslider such that

For desktop (window screen size >= 1200 px), I have six horizonttal images in each slides

For mobile or tablet (window screen size < 1200px), I have four images in each slide such that the four images are in a 2 by 2 grid always

Here is a sample codepen
https://codepen.io/hellouniverse/pen/LLJzgM

I have it almost working. In mobile, I am seeing 4 images in 2 by 2 grid. However, in desktop, I see 6 images for the first slide. For the subsequent slides, I also expected 6 images like the first ones. However I am seeing all the remaining.

I am slicing it as below and wrapping ul

// Wrap uls
for (var i = 0; i < item.length; i += dataItem) {
  item.slice(i, i + dataItem).wrapAll('

');
}

However, I think I must have made mistake in slicing probably. May someone please see if this can be made such that in desktop we have 6 images horizontally for each slides keeping everything else as it is now.

My html looks like

and my scss code looks like below

ul,
li {
  margin: 0;
  padding: 0;
}

@media screen and (max-width: 1199px) {
  .flexslider {
      .slides {
          .items {
              display: flex !important;
              flex-wrap: wrap !important;

              item {
                  border: 1px solid red;
              }
          }

          .item {
              background: #ccc;
              margin: 10px;
              padding: 5px;
              text-align: center;
              flex-basis: calc(50% - 40px);
              /* Need to tweak!*/
              list-style-type: none;
          }
      }
  }
}

@media screen and (min-width: 1200px) {
  .flexslider {
      .slides {
          .items {
              display: flex !important;
              //flex-wrap: wrap !important;
              item {
                  border: 1px solid red;
              }
          }

          .item {
              background: #ccc;
              margin: 10px;
              padding: 5px;
              text-align: center;
              flex-basis: calc(100% / 6);
              /* Need to tweak!*/
              list-style-type: none;
          }
      }
  }
}

And my js looks like below

var fs = $(".flexslider"),
  dataItem = fs.data("item"),
  item = fs.find(".item");

//console.log('item', item.length);

//var dataItem = $(".flexslider").attr("data-type");
if ($(window).width() >= 1200) {
  var el = document.getElementById("flexslider");
  el.setAttribute("data-item", "6");
  dataItem = el.getAttribute("data-item");
}

console.log('dataItem', dataItem);
console.log('length of item', item.length);

// Wrap uls
for (var i = 0; i < item.length; i += dataItem) {
  item.slice(i, i + dataItem).wrapAll('

');
}

// Initialize flexslider
$(window).load(function() {
  fs.flexslider({
    selector: ".slides > .items",
    animation: "slide",
    animationLoop: false,
    directionNav: true,
    slideshow: false,
    smoothHeight: true,
    itemMargin: 0,
    minItems: 1,
    maxItems: 1
  });
});

Body:
On desktop versions, I only want to see 6 images.. But I see 6 + 1/2 of 7 sometimes and sometimes 5 and 1/2 of left and right

Maxwidth is 1200px. So if you want to show 6 items, each item will have only 200px right? But in your css code, you have margin: 20px for each item.That means each item will take 240px.

For 2x2 grid view on Mobile, my solution is you will have a new html structure to show 2 images on each <li> tag.

This is my demo code: https://codepen.io/anon/pen/qjMRdG


问:
How to add new record to table in Ms Access by form?
I made form by wizard, but when I run this, first I have in fields first record from table, and I can edit this record, but I don't want to have this. I want to have blank field and when I click add button i can add new record, not edit....</p>

答:
Create a macro for this.
1. In create tab select macro.
2. Under cation field in macro select open form.
3. Below in property box select the form you want to perform task with
4. Then in Data Mode select Add.

Then when ever you run this Macro your form will open to enter a new record and not editing existing record.

The only problem here would be when you open form then it will open in edit existing record mode but when you open corresponding macro form will open in add mode, so in order to counter this you can name your Macro as AutoExec so the macro will run itself when you open the database.;


问:
How to plot a legend according to its color on an image?
Now I got an image like fig1 and different color means different thing, and I want to add a legend(fig2) at the bottom of fig1, how to do this? I have the rgb value of each color.

Fig 1 :

Fig 2 :

and this is the code I got:

```<code># coding=utf-8
import matplotlib
matplotlib.use('Agg')
import h5py
import numpy
from PIL import Image
from PIL import ImageDraw
import matplotlib.pyplot as plt
import matplotlib.ticker as plticker
import sys
table={
    k:v for k,v,n in [

[
        127,
        [
            100,
            100,
            100
        ],
        "NO DATA"
    ],
    [
        126,
        [
            0,
            0,
            0
        ],
        "SPACE"
    ],
    [
        0,
        [
            200,
            255,
            255
        ],
        "CLEAR"
    ],
    [
        2,
        [
            0,
            0,
            244
        ],
        "WATER CLOUD"
    ],
    [
        3,
        [
            32,
            165,
            225
        ],
        "ICED CLOUD"
    ],
    [
        4,
        [
            33,
            255,
            170
        ],
        "MIXED CLOUD"
    ],
    [
        5,
        [
            255,
            0,
            0
        ],
        "CIRRUS CLOUD"
    ],
    [
        6,
        [
            180,
            20,
            255
        ],
        "Opaque cloud"
    ],
    [
        7,
        [
            105,
            255,
            0
        ],
        "OVERLAP CLOUD"
    ],
    [
        9,
        [
            224,
            180,
            0
        ],
        "UNKNOWN CLOUD"
    ]
]
}

def main(_,fn,out):
    with h5py.File(fn) as f:
        data = f['EVB1'].value
    w,h = data.shape
    ret = numpy.zeros((w,h,3),'u1')
    for i in (0,2,3,4,5,6,7,9,126,127):
        ret[data==i]=table[i]

    Image.fromarray(ret,mode="RGB").save(out)
    image = Image.open(out)
    my_dpi = 100.

    # Set up figure
    fig = plt.figure(figsize=(float(image.size[0]) / my_dpi,float(image.size[1]) / my_dpi), dpi=my_dpi)
    ax = fig.add_subplot(111)

# Set the gridding interval: here we use the major tick interval
    myInterval = 249.9
    loc = plticker.MultipleLocator(base=myInterval)
    # ax=plt.gca()
    ax.xaxis.set_major_locator(loc)
    ax.yaxis.set_major_locator(loc)

    ax.set_xticklabels(['60', '70', '80', '90', '100', '110', '120', '130', '140'])
# ax.set_xticklabels(np.arange(70,150,10))
    ax.set_yticklabels(('70', '60', '50', '40', '30', '20', '10', '0'))
#

    out1 = out.split('/')[-1].split('.')[0].split('V0001')[0]

    ax.set_title(out1,fontsize = 20)

# Add the grid
    ax.grid(which='major', axis='both', linestyle='-')

# Add the image
    ax.imshow(image)

# Save the figure
    fig.savefig(out)

if __name__ == '__main__':
    main(*sys.argv)
</code>```

答:
I couldn't get the Chinese characters to display correctly, but you should get the basic idea:

```<code># coding=utf-8
from matplotlib import pyplot as plt
from matplotlib.patches import Rectangle
import numpy as np

x = np.linspace(0,1,100)
y = np.linspace(0,1,100)

X,Y = np.meshgrid(x,y)

array = np.sin(X)*np.cos(Y)

plt.imshow(array)

legend_data = [
   [
    127,
    [
        100,
        100,
        100
    ],
    "无数据区"
],
[
    126,
    [
        0,
        0,
        0
    ],
    "外太空"
],
[
    0,
    [
        200,
        255,
        255
    ],
    "晴空"
],
[
    2,
    [
        0,
        0,
        244
    ],
    "水云"
],
[
    3,
    [
        32,
        165,
        225
    ],
    "过冷水云"
],
[
    4,
    [
        33,
        255,
        170
    ],
    "混合云"
],
[
    5,
    [
        255,
        0,
        0
    ],
    "厚冰云"
],
[
    6,
    [
        180,
        20,
        255
    ],
    "卷云"
],
[
    7,
    [
        105,
        255,
        0
    ],
    "多层云"
],
[
    9,
    [
        224,
        180,
        0
    ],
    "不确定"
]
]
handles = [
    Rectangle((0,0),1,1, color = (v/255 for v in c)) for k,c,n in legend_data
]
labels = [n for k,c,n in legend_data]

plt.legend(handles,labels)
plt.show()
</code>```

The result looks like this:

The plot is just a placeholder, as I don't have your input data. The crucial lines are the ones that produce the rectangular handles and the labels from your table and the label command in the end.

EDIT:

If you want the legend strictly below the plot, you can to so by defining a second axis for the legend:

```<code>from matplotlib import pyplot as plt
from matplotlib.patches import Rectangle
from matplotlib.gridspec import GridSpec
import numpy as np

from matplotlib.font_manager import FontProperties
ChineseFont = FontProperties('SimHei')

x = np.linspace(0,1,100)
y = np.linspace(0,1,100)

X,Y = np.meshgrid(x,y)

array = np.sin(X)*np.cos(Y)

gs = GridSpec(6,1)

fig = plt.figure(figsize = (4,6))
ax1 = fig.add_subplot(gs[:-1,:]) ##for the plot
ax2 = fig.add_subplot(gs[-1,:])   ##for the legend

ax1.imshow(array)

legend_data =[
[
        127,
        [
            100,
            100,
            100
        ],
        u"无数据区"
    ],
...
]
handles = [
    Rectangle((0,0),1,1, color = tuple((v/255 for v in c))) for k,c,n in legend_data
]
labels = [n for k,c,n in legend_data]

ax2.legend(handles,labels, mode='expand', ncol=3, prop=ChineseFont)
ax2.axis('off')
plt.show()
</code>```

This looks like this:

EDIT2:

I found a way to display the Chinese characters correctly with help of this answer. The example should now work in Python 2.7 and Python 3.5 -- just prepend a u to each label and divide by 255.0 instead of just 255.

Body:
Now I got an image like fig1 and different color means different thing, and I want to add a legend(fig2) at the bottom of fig1, how to do this? I have the rgb value of each color.

Fig 1 :

Fig 2 :

and this is the code I got:

# coding=utf-8
import matplotlib
matplotlib.use('Agg')
import h5py
import numpy
from PIL import Image
from PIL import ImageDraw
import matplotlib.pyplot as plt
import matplotlib.ticker as plticker
import sys
table={
    k:v for k,v,n in [

[
        127,
        [
            100,
            100,
            100
        ],
        "NO DATA"
    ],
    [
        126,
        [
            0,
            0,
            0
        ],
        "SPACE"
    ],
    [
        0,
        [
            200,
            255,
            255
        ],
        "CLEAR"
    ],
    [
        2,
        [
            0,
            0,
            244
        ],
        "WATER CLOUD"
    ],
    [
        3,
        [
            32,
            165,
            225
        ],
        "ICED CLOUD"
    ],
    [
        4,
        [
            33,
            255,
            170
        ],
        "MIXED CLOUD"
    ],
    [
        5,
        [
            255,
            0,
            0
        ],
        "CIRRUS CLOUD"
    ],
    [
        6,
        [
            180,
            20,
            255
        ],
        "Opaque cloud"
    ],
    [
        7,
        [
            105,
            255,
            0
        ],
        "OVERLAP CLOUD"
    ],
    [
        9,
        [
            224,
            180,
            0
        ],
        "UNKNOWN CLOUD"
    ]
]
}

def main(_,fn,out):
    with h5py.File(fn) as f:
        data = f['EVB1'].value
    w,h = data.shape
    ret = numpy.zeros((w,h,3),'u1')
    for i in (0,2,3,4,5,6,7,9,126,127):
        ret[data==i]=table[i]

    Image.fromarray(ret,mode="RGB").save(out)
    image = Image.open(out)
    my_dpi = 100.

    # Set up figure
    fig = plt.figure(figsize=(float(image.size[0]) / my_dpi,float(image.size[1]) / my_dpi), dpi=my_dpi)
    ax = fig.add_subplot(111)

# Set the gridding interval: here we use the major tick interval
    myInterval = 249.9
    loc = plticker.MultipleLocator(base=myInterval)
    # ax=plt.gca()
    ax.xaxis.set_major_locator(loc)
    ax.yaxis.set_major_locator(loc)

    ax.set_xticklabels(['60', '70', '80', '90', '100', '110', '120', '130', '140'])
# ax.set_xticklabels(np.arange(70,150,10))
    ax.set_yticklabels(('70', '60', '50', '40', '30', '20', '10', '0'))
#

    out1 = out.split('/')[-1].split('.')[0].split('V0001')[0]

    ax.set_title(out1,fontsize = 20)

# Add the grid
    ax.grid(which='major', axis='both', linestyle='-')

# Add the image
    ax.imshow(image)

# Save the figure
    fig.savefig(out)

if __name__ == '__main__':
    main(*sys.argv)

Body:
I couldn't get the Chinese characters to display correctly, but you should get the basic idea:

# coding=utf-8
from matplotlib import pyplot as plt
from matplotlib.patches import Rectangle
import numpy as np

x = np.linspace(0,1,100)
y = np.linspace(0,1,100)

X,Y = np.meshgrid(x,y)

array = np.sin(X)*np.cos(Y)

plt.imshow(array)

legend_data = [
   [
    127,
    [
        100,
        100,
        100
    ],
    "无数据区"
],
[
    126,
    [
        0,
        0,
        0
    ],
    "外太空"
],
[
    0,
    [
        200,
        255,
        255
    ],
    "晴空"
],
[
    2,
    [
        0,
        0,
        244
    ],
    "水云"
],
[
    3,
    [
        32,
        165,
        225
    ],
    "过冷水云"
],
[
    4,
    [
        33,
        255,
        170
    ],
    "混合云"
],
[
    5,
    [
        255,
        0,
        0
    ],
    "厚冰云"
],
[
    6,
    [
        180,
        20,
        255
    ],
    "卷云"
],
[
    7,
    [
        105,
        255,
        0
    ],
    "多层云"
],
[
    9,
    [
        224,
        180,
        0
    ],
    "不确定"
]
]
handles = [
    Rectangle((0,0),1,1, color = (v/255 for v in c)) for k,c,n in legend_data
]
labels = [n for k,c,n in legend_data]

plt.legend(handles,labels)
plt.show()

The result looks like this:

The plot is just a placeholder, as I don't have your input data. The crucial lines are the ones that produce the rectangular handles and the labels from your table and the label command in the end.

EDIT:

If you want the legend strictly below the plot, you can to so by defining a second axis for the legend:

from matplotlib import pyplot as plt
from matplotlib.patches import Rectangle
from matplotlib.gridspec import GridSpec
import numpy as np

from matplotlib.font_manager import FontProperties
ChineseFont = FontProperties('SimHei')

x = np.linspace(0,1,100)
y = np.linspace(0,1,100)

X,Y = np.meshgrid(x,y)

array = np.sin(X)*np.cos(Y)

gs = GridSpec(6,1)

fig = plt.figure(figsize = (4,6))
ax1 = fig.add_subplot(gs[:-1,:]) ##for the plot
ax2 = fig.add_subplot(gs[-1,:])   ##for the legend

ax1.imshow(array)

legend_data =[
[
        127,
        [
            100,
            100,
            100
        ],
        u"无数据区"
    ],
...
]
handles = [
    Rectangle((0,0),1,1, color = tuple((v/255 for v in c))) for k,c,n in legend_data
]
labels = [n for k,c,n in legend_data]

ax2.legend(handles,labels, mode='expand', ncol=3, prop=ChineseFont)
ax2.axis('off')
plt.show()

This looks like this:

EDIT2:

I found a way to display the Chinese characters correctly with help of this answer. The example should now work in Python 2.7 and Python 3.5 -- just prepend a u to each label and divide by 255.0 instead of just 255.


答: If you pop off an element, then it's no longer in the list - but your index doesn't move, so it's now pointing to the next element. Say you pop off two elements... your list size after that would be 2, but the for loop is still going to try to go to 4.

Title: Why does this code return a list index error?


问:
Avoid deleting databases by other users in Hive
I'm working on a Kerberos-enabled Hortonworks Data Platform 2.5 with Hive 1.2.1.

I just saw, that one user can create a database and another user can delete it!

```<code>[root@host ~]# su -l user1

[user1@host ~]# hive
 hive> create database user1db
 OK
 Time taken: 0.077 seconds
</code>```

After creating this database, another user can login and delete it:

```<code>[root@host ~]# su -l user2

[user2@host ~]# hive
 hive> drop database user1db
 OK
 Time taken: 1.352 seconds
</code>```

Why is this possible? Another user can also do other things like showing all databases etc.

How can this be avoided? Shouldn't there be a restriction like "only the creator is allowed to delete by default" or similar?

A user shouldn't be able to view / delete databases of other users!

答:
As per my understanding:

Give the permission to hive Database as 755 so that only owner can play with it, provided its a EXTERNAL hive table and data will be in HDFS.

Enable the empty snapshots on warehouse of each user in HDFS (assuming /user/user1/warehouse, /user/user2/warehouse), details are https://hadoop.apache.org/docs/r2.7.2/hadoop-project-dist/hadoop-hdfs/HdfsSnapshots.html

Body:
I'm working on a Kerberos-enabled Hortonworks Data Platform 2.5 with Hive 1.2.1.

I just saw, that one user can create a database and another user can delete it!

[root@host ~]# su -l user1

[user1@host ~]# hive
 hive> create database user1db
 OK
 Time taken: 0.077 seconds

After creating this database, another user can login and delete it:

[root@host ~]# su -l user2

[user2@host ~]# hive
 hive> drop database user1db
 OK
 Time taken: 1.352 seconds

Why is this possible? Another user can also do other things like showing all databases etc.

How can this be avoided? Shouldn't there be a restriction like "only the creator is allowed to delete by default" or similar?

A user shouldn't be able to view / delete databases of other users!


问:
how to set equal margin between recyclerview items

See this Image

I achieved the current margin from xml layout but its not same through all four sides.

How to get equal margin

My current xml layout

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="300dp">

<ImageView
    android:id="@+id/iv_photo"
    android:layout_width="match_parent"
    android:layout_height="300dp"
    android:layout_marginEnd="6dp"
    android:layout_marginTop="6dp"
    android:adjustViewBounds="true"
    android:background="@color/colorPrimary"
    android:foreground="?android:attr/selectableItemBackground"
    android:scaleType="fitXY" />

</RelativeLayout>
</code>```

答:
use     DividerItemDecoration class.

for reference follow this link How to add dividers and spaces between items in RecyclerView?

Body:
See this Image

I achieved the current margin from xml layout but its not same through all four sides.

How to get equal margin

My current xml layout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="300dp">

<ImageView
    android:id="@+id/iv_photo"
    android:layout_width="match_parent"
    android:layout_height="300dp"
    android:layout_marginEnd="6dp"
    android:layout_marginTop="6dp"
    android:adjustViewBounds="true"
    android:background="@color/colorPrimary"
    android:foreground="?android:attr/selectableItemBackground"
    android:scaleType="fitXY" />

</RelativeLayout>


问:
ASP.NET MVC Populate DropDown thru ViewBag
I am a beginner to ASP.NET MVC technology.
   In my View page, I have a WebGrid that is bind to data that is passed from Controller. I also want to populate a dropdown list with the list of Tables in the database. I retrieve the tables List from a helper method. I am trying to send the List to the ViewBag and want to populate the dropdown; but can't get it. Some syntax error is only coming or the List is not accessible.

My Controller class :

```<code>        [Authorize]
    public ActionResult Index(int page = 1, string sort = "FirstName", string sortdir = "asc", string search = "")
    {
        int pageSize = 10;
        int totalRecord = 0;
        if (page < 1)
            page = 1;
        int skip = (page * pageSize) - pageSize;
        var data = GetUsers(search, sort, sortdir, skip, pageSize, out totalRecord);

        // Get Tables List
        ViewBag.TableList = DataFiller.GetTableNames();
        ViewBag.TotalRows = totalRecord;

        return View(data);
    }
</code>```

View file :

```<code>@model List<DataStudio.Models.User>

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_MemberLayout.cshtml";

<!-- data is used for grid -->
var grid = new WebGrid(canPage: true, rowsPerPage: 10);
grid.Bind(source: Model, rowCount: ViewBag.TotalRows, autoSortAndPage: false);
}

<!-- ERROR LINE   -->
@Html.DropDownList("tableName", @ViewBag.TableList, "Select Table")
</code>```

ERROR

```<code>Error   CS1973  'HtmlHelper<List<User>>' has no applicable method named 'DropDownList' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.    1_Views_Member_Index.cshtml Index.cshtml    82  Active
</code>```

The User model doesn't contain any List nor any DropDownList. The drop down is a totally separate combo box, that I want to fill with a List items; it just contains the list of table names from the database.

I am not able to get how do I bind or populate the drop down list with the SelectLiteItem items. I googled a lot, but could not get any example with this scenario. I don't wish to add my List with my model. And, I want to populate the Tables list drop down only once.

Can anyone please help me and guide me how do I achieve the goal. Any help is highly appreciated.

Thanks

Tom

UPDATE:
The DataFilter.GetTableNames() method

```<code>       public static List<SelectListItem> GetTableNames()
    {
        List<SelectListItem> tablesList = new List<SelectListItem>();

        string sql = "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'";
        string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["DMSDbConnectionString"].ToString();

        using (SqlConnection con = new SqlConnection(conStr))
        {
            using (SqlCommand com = new SqlCommand(sql, con)) {
                con.Open();
                using(SqlDataReader sdr = com.ExecuteReader() )
                {
                    while (sdr.Read())
                    {
                        tablesList.Add(new SelectListItem
                        {
                            Text = sdr["TABLE_NAME"].ToString(),
                            Value = sdr["TABLE_NAME"].ToString()
                        });
                    }
                }

                /*
                SqlDataAdapter da = new SqlDataAdapter(com);
                DataSet ds = new DataSet();
                da.Fill(ds);

                DataTable dt = ds.Tables[0];

                tablesList = (from DataRow dr in dt.Rows
                              select new TablesInfo()
                              {
                                  TableCatalog = dr["TABLE_CATALOG"].ToString(),
                                  TableName = dr["TABLE_NAME"].ToString(),
                                  TableSchema = dr["TABLE_SCHEMA"].ToString(),
                                  TableType = dr["TABLE_TYPE"].ToString(),
                              }).ToList();

                    */
                con.Close();
            }
        }
        return tablesList;
    }
</code>```

I had created a class also TablesInfo to populate data in it and use strong typed object. But, as couldn't find a way to populate it, so used SelectListItem.
And as it contains only list of tables, so I don't wish it to be populated on every refresh of the page.

答:
You can actually do it like below too:</p>

```<code>@Html.DropDownListFor(m => m.tableName, (IEnumerable<SelectListItem>)ViewBag.TableList ,"select table")
</code>```

Body:
I am a beginner to ASP.NET MVC technology.
   In my View page, I have a WebGrid that is bind to data that is passed from Controller. I also want to populate a dropdown list with the list of Tables in the database. I retrieve the tables List from a helper method. I am trying to send the List to the ViewBag and want to populate the dropdown; but can't get it. Some syntax error is only coming or the List is not accessible.

My Controller class :

        [Authorize]
    public ActionResult Index(int page = 1, string sort = "FirstName", string sortdir = "asc", string search = "")
    {
        int pageSize = 10;
        int totalRecord = 0;
        if (page < 1)
            page = 1;
        int skip = (page * pageSize) - pageSize;
        var data = GetUsers(search, sort, sortdir, skip, pageSize, out totalRecord);

        // Get Tables List
        ViewBag.TableList = DataFiller.GetTableNames();
        ViewBag.TotalRows = totalRecord;

        return View(data);
    }

View file :

@model List<DataStudio.Models.User>

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_MemberLayout.cshtml";

var grid = new WebGrid(canPage: true, rowsPerPage: 10);
grid.Bind(source: Model, rowCount: ViewBag.TotalRows, autoSortAndPage: false);
}

@Html.DropDownList("tableName", @ViewBag.TableList, "Select Table")

ERROR

Error   CS1973  'HtmlHelper<List<User>>' has no applicable method named 'DropDownList' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.    1_Views_Member_Index.cshtml Index.cshtml    82  Active

The User model doesn't contain any List nor any DropDownList. The drop down is a totally separate combo box, that I want to fill with a List items; it just contains the list of table names from the database.

I am not able to get how do I bind or populate the drop down list with the SelectLiteItem items. I googled a lot, but could not get any example with this scenario. I don't wish to add my List with my model. And, I want to populate the Tables list drop down only once.

Can anyone please help me and guide me how do I achieve the goal. Any help is highly appreciated.

Thanks

Tom

UPDATE:
The DataFilter.GetTableNames() method

       public static List<SelectListItem> GetTableNames()
    {
        List<SelectListItem> tablesList = new List<SelectListItem>();

        string sql = "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'";
        string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["DMSDbConnectionString"].ToString();

        using (SqlConnection con = new SqlConnection(conStr))
        {
            using (SqlCommand com = new SqlCommand(sql, con)) {
                con.Open();
                using(SqlDataReader sdr = com.ExecuteReader() )
                {
                    while (sdr.Read())
                    {
                        tablesList.Add(new SelectListItem
                        {
                            Text = sdr["TABLE_NAME"].ToString(),
                            Value = sdr["TABLE_NAME"].ToString()
                        });
                    }
                }

                /*
                SqlDataAdapter da = new SqlDataAdapter(com);
                DataSet ds = new DataSet();
                da.Fill(ds);

                DataTable dt = ds.Tables[0];

                tablesList = (from DataRow dr in dt.Rows
                              select new TablesInfo()
                              {
                                  TableCatalog = dr["TABLE_CATALOG"].ToString(),
                                  TableName = dr["TABLE_NAME"].ToString(),
                                  TableSchema = dr["TABLE_SCHEMA"].ToString(),
                                  TableType = dr["TABLE_TYPE"].ToString(),
                              }).ToList();

                    */
                con.Close();
            }
        }
        return tablesList;
    }

I had created a class also TablesInfo to populate data in it and use strong typed object. But, as couldn't find a way to populate it, so used SelectListItem.
And as it contains only list of tables, so I don't wish it to be populated on every refresh of the page.

Body:
You can actually do it like below too:

@Html.DropDownListFor(m => m.tableName, (IEnumerable<SelectListItem>)ViewBag.TableList ,"select table")


问:
Can a signal observer get access to the last emitted value of a ReactiveCocoa signal?
I'm starting using ReactiveCocoa and I'm still struggling with some basic concepts:

My app starts listening for geolocation data (init in my view model)

My app emits a signal with my current location (didFindCurrentPosition is called)

My view controller showing a map loads (viewDidLoad in my view controller)

My view controller starts observing the current location signal (still viewDidLoad)

My problem is: after step 2 is achieved, if no other event is sent on the signal, my view controller doesn't get notified.

How can my view controller get access to the last value from the signal? (ie how to get access at step 3 to a value emitted at step 2?)

Thanks for your help.

PS: ReactiveCocoa looks like a great library but I'm puzzled by the state of the documentation. IMHO, it is not very clear and lacks some clear guides on how to use it.

The Code

The view model:

```<code>class MyViewModel: LocationManagerDelegate {
    let locationManager: LocationManager
    let geolocationDataProperty = MutableProperty<Geolocation?>(nil)
    let geolocationData: Signal<Geolocation?, NoError>

    init() {
        geolocationData = geolocationDataProperty.signal

        // Location Management
        locationManager = LocationManager()
        locationManager.delegate = self
        locationManager.requestLocation()
    }

    // MARK: - LocationManagerDelegate

    func didFindCurrentPosition(location: CLLocation) {
        geolocationDataProperty.value = Geolocation(location: location)
    }
}
</code>```

The view controller:

```<code>class MyViewController: UIViewController {
    let viewModel = MyViewModel()

    init() {
        super.init(nibName: nil, bundle: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        viewModel.geolocationData
            .observe(on: UIScheduler())
            .observeValues { geolocation in
                debugPrint("GOT GEOLOCATION")
        }
    }
}
</code>```

答:
If your problem is to have old value when it gets modified .You can try with Key-Value Observing . Add your property for value observation like

```<code> geolocationDataProperty.addObserver(self, forKeyPath: "value", options: [.new, .old], context: &observerContext)
</code>```

Whenever your geolocationDataProperty gets modified ,you will receive that value in delegate method

```<code> override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        let newValue = change?[.newKey] as? NSObject
         let oldValue = change?[.oldKey] as? NSObject
//Add your code
    }
</code>```

Body:
I'm starting using ReactiveCocoa and I'm still struggling with some basic concepts:

My app starts listening for geolocation data (init in my view model)

My app emits a signal with my current location (didFindCurrentPosition is called)

My view controller showing a map loads (viewDidLoad in my view controller)

My view controller starts observing the current location signal (still viewDidLoad)

My problem is: after step 2 is achieved, if no other event is sent on the signal, my view controller doesn't get notified.

How can my view controller get access to the last value from the signal? (ie how to get access at step 3 to a value emitted at step 2?)

Thanks for your help.

PS: ReactiveCocoa looks like a great library but I'm puzzled by the state of the documentation. IMHO, it is not very clear and lacks some clear guides on how to use it.

The Code

The view model:

class MyViewModel: LocationManagerDelegate {
    let locationManager: LocationManager
    let geolocationDataProperty = MutableProperty<Geolocation?>(nil)
    let geolocationData: Signal<Geolocation?, NoError>

    init() {
        geolocationData = geolocationDataProperty.signal

        // Location Management
        locationManager = LocationManager()
        locationManager.delegate = self
        locationManager.requestLocation()
    }

    // MARK: - LocationManagerDelegate

    func didFindCurrentPosition(location: CLLocation) {
        geolocationDataProperty.value = Geolocation(location: location)
    }
}

The view controller:

class MyViewController: UIViewController {
    let viewModel = MyViewModel()

    init() {
        super.init(nibName: nil, bundle: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        viewModel.geolocationData
            .observe(on: UIScheduler())
            .observeValues { geolocation in
                debugPrint("GOT GEOLOCATION")
        }
    }
}

Body:
If your problem is to have old value when it gets modified .You can try with Key-Value Observing . Add your property for value observation like

 geolocationDataProperty.addObserver(self, forKeyPath: "value", options: [.new, .old], context: &observerContext)

Whenever your geolocationDataProperty gets modified ,you will receive that value in delegate method

 override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        let newValue = change?[.newKey] as? NSObject
         let oldValue = change?[.oldKey] as? NSObject
//Add your code
    }


问:
Finding smallest value in an array most efficiently
There are N values in the array, and one of them is the smallest value. How can I find the smallest value most efficiently?</p>

答:
If the array is sorted in ascending or descending order then you can find it with complexity O(1).
For an array of ascending order the first element is the smallest element, you can get it by arr[0] (0 based indexing).
If the array is sorted in descending order then the last element is the smallest element,you can get it by arr[sizeOfArray-1].

If the array is not sorted then you have to iterate over the array to get the smallest element.In this case time complexity is O(n), here n is the size of array.

```<code>int arr[] = {5,7,9,0,-3,2,3,4,56,-7};
int smallest_element=arr[0] //let, first element is the smallest one

for(int i =1;i<sizeOfArray;i++)
{
    if(arr[i]<smallest_element)
    {
     smallest_element=arr[i];
    }
}
</code>```

You can calculate it in input section (when you have to find smallest element from a given array)

```<code>int smallest_element;
int arr[100],n;
cin>>n;
for(int i = 0;i<n;i++)
{
cin>>arr[i];
if(i==0)
{
    smallest_element=arr[i]; //smallest_element=arr[0];
}
else if(arr[i]<smallest_element)
{
smallest_element = arr[i];
}
}
</code>```

Also you can get smallest element by built in function

```<code>#inclue<algorithm>
int smallest_element = *min_element(arr,arr+n); //here n is the size of array
</code>```

You can get smallest element of any range by using this function
such as,

```<code>int arr[] = {3,2,1,-1,-2,-3};
cout<<*min_element(arr,arr+3); //this will print 1,smallest element of first three element
cout<<*min_element(arr+2,arr+5); // -2, smallest element between third and fifth element (inclusive)
</code>```

I have used asterisk (*), before min_element() function. Because it returns pointer of smallest element.
All codes are in c++.
You can find the maximum element in opposite way.

Body:
If the array is sorted in ascending or descending order then you can find it with complexity O(1).
For an array of ascending order the first element is the smallest element, you can get it by arr[0] (0 based indexing).
If the array is sorted in descending order then the last element is the smallest element,you can get it by arr[sizeOfArray-1].

If the array is not sorted then you have to iterate over the array to get the smallest element.In this case time complexity is O(n), here n is the size of array.

int arr[] = {5,7,9,0,-3,2,3,4,56,-7};
int smallest_element=arr[0] //let, first element is the smallest one

for(int i =1;i<sizeOfArray;i++)
{
    if(arr[i]<smallest_element)
    {
     smallest_element=arr[i];
    }
}

You can calculate it in input section (when you have to find smallest element from a given array)

int smallest_element;
int arr[100],n;
cin>>n;
for(int i = 0;i<n;i++)
{
cin>>arr[i];
if(i==0)
{
    smallest_element=arr[i]; //smallest_element=arr[0];
}
else if(arr[i]<smallest_element)
{
smallest_element = arr[i];
}
}

Also you can get smallest element by built in function

#inclue<algorithm>
int smallest_element = *min_element(arr,arr+n); //here n is the size of array

You can get smallest element of any range by using this function
such as,

int arr[] = {3,2,1,-1,-2,-3};
cout<<*min_element(arr,arr+3); //this will print 1,smallest element of first three element
cout<<*min_element(arr+2,arr+5); // -2, smallest element between third and fifth element (inclusive)

I have used asterisk (*), before min_element() function. Because it returns pointer of smallest element.
All codes are in c++.
You can find the maximum element in opposite way.