问:
How can I implement a click to select using a ViewModel
I have this XAML that displays 6 TextCells which can show a check mark or not. They also so as enabled or not enabled:

```<code><TableSection Title="Front Side" x:Name="cfsSection">
   <local:CustomTextCell Text="{Binding [0].Name}" IsChecked="{Binding [0].IsSelected}" IsEnabled="{Binding [0].IsSelected, Converter={StaticResource InverseBoolConverter} } "Tapped="cfsSelectValue"/>
   <local:CustomTextCell Text="{Binding [1].Name}" IsChecked="{Binding [1].IsSelected}" IsEnabled="{Binding [1].IsSelected, Converter={StaticResource InverseBoolConverter} } "Tapped="cfsSelectValue"/>
   <local:CustomTextCell Text="{Binding [2].Name}" IsChecked="{Binding [2].IsSelected}" IsEnabled="{Binding [2].IsSelected, Converter={StaticResource InverseBoolConverter} } "Tapped="cfsSelectValue"/>
   <local:CustomTextCell Text="{Binding [3].Name}" IsChecked="{Binding [3].IsSelected}" IsEnabled="{Binding [3].IsSelected, Converter={StaticResource InverseBoolConverter} } "Tapped="cfsSelectValue"/>
   <local:CustomTextCell Text="{Binding [4].Name}" IsChecked="{Binding [4].IsSelected}" IsEnabled="{Binding [4].IsSelected, Converter={StaticResource InverseBoolConverter} } "Tapped="cfsSelectValue"/>
   <local:CustomTextCell Text="{Binding [5].Name}" IsChecked="{Binding [5].IsSelected}" IsEnabled="{Binding [5].IsSelected, Converter={StaticResource InverseBoolConverter} } "Tapped="cfsSelectValue"/>
</TableSection>
</code>```

The code behind is I think fairly simple. It declares an array of SSVViewModel and the binding causes the text to display:

```<code>    SSVViewModel[] CFS = new[] {
        new SSVViewModel {Id = 0, Name=LANG.English.Text(), IsSelected = false},
        new SSVViewModel {Id = 1, Name=LANG.Romaji.Text(), IsSelected = false},
        new SSVViewModel {Id = 2, Name=LANG.Kana.Text(), IsSelected = false},
        new SSVViewModel {Id = 3, Name=LANG.Kanji.Text(), IsSelected = false},
        new SSVViewModel {Id = 4, Name=LANG.KanjiKana.Text(), IsSelected = false},
        new SSVViewModel {Id = 5, Name=LANG.KanaKanji.Text(), IsSelected = false},
    };
</code>```

When a cell is clicked this function is called:

```<code>void cfsSelectValue(object sender, EventArgs e)
{
        var cell = sender as TextCell;
        if (cell == null)
            return;

        var selected = cell.Text;

        foreach (var setting in CFS)
            setting.IsSelected = false;

        foreach (var setting in CFS)
            if (setting.Name == selected)
                setting.IsSelected = true;

 }
</code>```

However when clicking on either of the first two cells both show as checked.  All other cell clicks work fine. In another part of my code I use a similar construct and it's the last two cells that do not work.

Note that the IsEnabled works but not the IsChecked

Can anyone see why a click on the first two cells could possibly give any problem. I have been through this with the debugger many time but I still cannot see what might be wrong. Surely the code that sets the IsSelected to false should cause all except the one cell to show as checked.

Note that when debugging this line: setting.IsSelected = false; and this line:  setting.IsSelected = true; then everything appears as it should as the correct cell has it's IsSelected set to true and the others to false.  It's just when I look at the display it seems like the binding didn't work for those first two cells.

Here's the viewModel code I am using:

```<code>public class SSVViewModel: ObservableProperty
{
    private int id;
    private string name;
    private bool isSelected;

    public int Id
    {
        get
        {
            return id;
        }
        set
        {
            if (value != id)
            {
                id = value;
                NotifyPropertyChanged("Id");
            }
        }
    }

    public string Name
    {
        get
        {
            return name;
        }
        set
        {
            if (value != name)
            {
                name = value;
                NotifyPropertyChanged("Name");
            }
        }
    }

    public bool IsSelected
    {
        get
        {
            return isSelected;
        }
        set
        {
            if (value != isSelected)
            {
                isSelected = value;
                NotifyPropertyChanged("IsSelected");
            }
        }
    }
}
</code>```

Here is the code for the CustomTextCellRenderer

```<code>public class CustomTextCellRenderer : TextCellRenderer
{
    UITableViewCell _nativeCell;

    public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
    {
        _nativeCell = base.GetCell(item, reusableCell, tv);
        var formsCell = item as CustomTextCell;

        if (formsCell != null)
        {
            formsCell.PropertyChanged -= OnPropertyChanged;
            formsCell.PropertyChanged += OnPropertyChanged;
        }

        SetCheckmark(formsCell);
        SetTap(formsCell);

        return _nativeCell;
    }

    void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        var formsCell = sender as CustomTextCell;
        if (formsCell == null)
            return;

        if (e.PropertyName == CustomTextCell.IsCheckedProperty.PropertyName)
        {
            SetCheckmark(formsCell);
        }

        if (e.PropertyName == CustomTextCell.NoTapProperty.PropertyName)
        {
            SetTap(formsCell);
        }
    }

    private void SetCheckmark(CustomTextCell formsCell)
    {
        if (formsCell.IsChecked)
            _nativeCell.Accessory = UITableViewCellAccessory.Checkmark;
        else
            _nativeCell.Accessory = UITableViewCellAccessory.None;
    }

    private void SetTap(CustomTextCell formsCell)
    {
        if (formsCell.NoTap)
            _nativeCell.SelectionStyle = UITableViewCellSelectionStyle.None;
        else
            _nativeCell.SelectionStyle = UITableViewCellSelectionStyle.Default;
    }

}
</code>```

Update 1

```<code><local:CustomTextCell           Text="{Binding [0].Name}" IsChecked="{Binding [0].IsSelected}" Tapped="cfsSelectValue" CommandParameter="0" />
<local:CustomTextCell           Text="{Binding [1].Name}" IsChecked="{Binding [1].IsSelected}" Tapped="cfsSelectValue" CommandParameter="1" />
<local:CustomTextCell           Text="{Binding [2].Name}" IsChecked="{Binding [2].IsSelected}" Tapped="cfsSelectValue" CommandParameter="2" />
<local:CustomTextCell           Text="{Binding [3].Name}" IsChecked="{Binding [3].IsSelected}" Tapped="cfsSelectValue" CommandParameter="3" />
<local:CustomTextCell           Text="{Binding [4].Name}" IsChecked="{Binding [4].IsSelected}" Tapped="cfsSelectValue" CommandParameter="4" />
</code>```

Since the question was written I have stopped using this for the Lang selection however it's still used in another part of the code and I tried to put in some debug points. Here's what I did:

I added this to the iOS custom renderer:

```<code>    private void SetCheckmark(CustomTextCell formsCell)
    {
        if (formsCell.IsChecked)
        {
            _nativeCell.Accessory = UITableViewCellAccessory.Checkmark;
            Debug.WriteLine(_nativeCell.TextLabel.Text + " checked");
        }
        else
        {
            _nativeCell.Accessory = UITableViewCellAccessory.None;
            Debug.WriteLine(_nativeCell.TextLabel.Text + " unchecked");
        }
    }
</code>```

Here's the result when I clicked JLPT N2:

```<code>Category Group unchecked
Category unchecked
All Available Words unchecked
Japanese for Busy People 1 unchecked
Japanese for Busy People 2 unchecked
Japanese for Busy People 3 unchecked
JLPT Level N5 unchecked
JLPT Level N4 unchecked
JLPT Level N3 unchecked
JLPT Level N2 unchecked
JLPT Level N1 checked
JLPT Level N2 checked
JLPT Level N3 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
</code>```

This was not at all what I expected.

On the screen I see that as expected N2 is disabled but there is a check mark next to N3 and N2.

Not sure if this helps but I notice the iOS renderer code used is different from similar code I have used in other places.  For example here's a different iOS renderer. Code looks very different. I realize function is different but this one has things like cell = tv.DequeueReusableCell(fullName) as CellTableViewCell;

```<code>public class TextCellCustomRenderer : TextCellRenderer
{
    CellTableViewCell cell;
    public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
    {
        var textCell = (TextCell)item;
        var fullName = item.GetType().FullName;
        cell = tv.DequeueReusableCell(fullName) as CellTableViewCell;

        if (cell == null)
        {
            cell = new CellTableViewCell(UITableViewCellStyle.Value1, fullName);
        }
        else
        {
            cell.Cell.PropertyChanged -= cell.HandlePropertyChanged;
            //cell.Cell.PropertyChanged -= Current_PropertyChanged;
        }

        cell.Cell = textCell;
        textCell.PropertyChanged += cell.HandlePropertyChanged;
        cell.PropertyChanged = this.HandlePropertyChanged;
        cell.SelectionStyle = UITableViewCellSelectionStyle.None;
        cell.TextLabel.Text = textCell.Text;
        cell.DetailTextLabel.Text = textCell.Detail;
        cell.ContentView.BackgroundColor = UIColor.White;

        switch (item.StyleId)
        {
            case "checkmark":
                cell.Accessory = UIKit.UITableViewCellAccessory.Checkmark;
                break;
            case "detail-button":
                cell.Accessory = UIKit.UITableViewCellAccessory.DetailButton;
                break;
            case "detail-disclosure-button":
                cell.Accessory = UIKit.UITableViewCellAccessory.DetailDisclosureButton;
                break;
            case "disclosure":
                cell.Accessory = UIKit.UITableViewCellAccessory.DisclosureIndicator;
                break;
            case "none":
            default:
                cell.Accessory = UIKit.UITableViewCellAccessory.None;
                break;
        }

        //UpdateBackground(cell, item);

        return cell;
    }

    void checkAccessoryVisibility() {

    }

}
</code>```

答:
As per the log statements, it looks like the unsubscribe logic for property-changed-handler is not working as expected.

With TextCellRenderer, we don't need to explicitly subscribe to property-changed-event as there is a base overridable method HandlePropertyChanged that can be re-used in this context.

Changing the renderer code to use this method (similar to this answer) should hopefully resolve this problem:

```<code>public class CustomTextCellRenderer : TextCellRenderer
{
    public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
    {
        var nativeCell = base.GetCell(item, reusableCell, tv);

        if (item is CustomTextCell formsCell)
        {
            SetCheckmark(nativeCell, formsCell);
            SetTap(nativeCell, formsCell);
        }

        return nativeCell;
    }

    protected override void HandlePropertyChanged(object sender, PropertyChangedEventArgs args)
    {
        base.HandlePropertyChanged(sender, args);

        System.Diagnostics.Debug.WriteLine($"HandlePropertyChanged {args.PropertyName}");

        var nativeCell = sender as CellTableViewCell;
        if (nativeCell?.Element is CustomTextCell formsCell)
        {
            if (args.PropertyName == CustomTextCell.IsCheckedProperty.PropertyName)
                SetCheckmark(nativeCell, formsCell);
            else if (args.PropertyName == CustomTextCell.NoTapProperty.PropertyName)
                SetTap(nativeCell, formsCell);
        }
    }

    void SetCheckmark(UITableViewCell nativeCell, CustomTextCell formsCell)
    {
        if (formsCell.IsChecked)
            nativeCell.Accessory = UITableViewCellAccessory.Checkmark;
        else
            nativeCell.Accessory = UITableViewCellAccessory.None;
    }

    void SetTap(UITableViewCell nativeCell, CustomTextCell formsCell)
    {
        if (formsCell.NoTap)
            _nativeCell.SelectionStyle = UITableViewCellSelectionStyle.None;
        else
            _nativeCell.SelectionStyle = UITableViewCellSelectionStyle.Default;
    }
}
</code>```

Body:
I have this XAML that displays 6 TextCells which can show a check mark or not. They also so as enabled or not enabled:

<TableSection Title="Front Side" x:Name="cfsSection">
   <local:CustomTextCell Text="{Binding [0].Name}" IsChecked="{Binding [0].IsSelected}" IsEnabled="{Binding [0].IsSelected, Converter={StaticResource InverseBoolConverter} } "Tapped="cfsSelectValue"/>
   <local:CustomTextCell Text="{Binding [1].Name}" IsChecked="{Binding [1].IsSelected}" IsEnabled="{Binding [1].IsSelected, Converter={StaticResource InverseBoolConverter} } "Tapped="cfsSelectValue"/>
   <local:CustomTextCell Text="{Binding [2].Name}" IsChecked="{Binding [2].IsSelected}" IsEnabled="{Binding [2].IsSelected, Converter={StaticResource InverseBoolConverter} } "Tapped="cfsSelectValue"/>
   <local:CustomTextCell Text="{Binding [3].Name}" IsChecked="{Binding [3].IsSelected}" IsEnabled="{Binding [3].IsSelected, Converter={StaticResource InverseBoolConverter} } "Tapped="cfsSelectValue"/>
   <local:CustomTextCell Text="{Binding [4].Name}" IsChecked="{Binding [4].IsSelected}" IsEnabled="{Binding [4].IsSelected, Converter={StaticResource InverseBoolConverter} } "Tapped="cfsSelectValue"/>
   <local:CustomTextCell Text="{Binding [5].Name}" IsChecked="{Binding [5].IsSelected}" IsEnabled="{Binding [5].IsSelected, Converter={StaticResource InverseBoolConverter} } "Tapped="cfsSelectValue"/>
</TableSection>

The code behind is I think fairly simple. It declares an array of SSVViewModel and the binding causes the text to display:

    SSVViewModel[] CFS = new[] {
        new SSVViewModel {Id = 0, Name=LANG.English.Text(), IsSelected = false},
        new SSVViewModel {Id = 1, Name=LANG.Romaji.Text(), IsSelected = false},
        new SSVViewModel {Id = 2, Name=LANG.Kana.Text(), IsSelected = false},
        new SSVViewModel {Id = 3, Name=LANG.Kanji.Text(), IsSelected = false},
        new SSVViewModel {Id = 4, Name=LANG.KanjiKana.Text(), IsSelected = false},
        new SSVViewModel {Id = 5, Name=LANG.KanaKanji.Text(), IsSelected = false},
    };

When a cell is clicked this function is called:

void cfsSelectValue(object sender, EventArgs e)
{
        var cell = sender as TextCell;
        if (cell == null)
            return;

        var selected = cell.Text;

        foreach (var setting in CFS)
            setting.IsSelected = false;

        foreach (var setting in CFS)
            if (setting.Name == selected)
                setting.IsSelected = true;

 }

However when clicking on either of the first two cells both show as checked.  All other cell clicks work fine. In another part of my code I use a similar construct and it's the last two cells that do not work.

Note that the IsEnabled works but not the IsChecked

Can anyone see why a click on the first two cells could possibly give any problem. I have been through this with the debugger many time but I still cannot see what might be wrong. Surely the code that sets the IsSelected to false should cause all except the one cell to show as checked.

Note that when debugging this line: setting.IsSelected = false; and this line:  setting.IsSelected = true; then everything appears as it should as the correct cell has it's IsSelected set to true and the others to false.  It's just when I look at the display it seems like the binding didn't work for those first two cells.

Here's the viewModel code I am using:

public class SSVViewModel: ObservableProperty
{
    private int id;
    private string name;
    private bool isSelected;

    public int Id
    {
        get
        {
            return id;
        }
        set
        {
            if (value != id)
            {
                id = value;
                NotifyPropertyChanged("Id");
            }
        }
    }

    public string Name
    {
        get
        {
            return name;
        }
        set
        {
            if (value != name)
            {
                name = value;
                NotifyPropertyChanged("Name");
            }
        }
    }

    public bool IsSelected
    {
        get
        {
            return isSelected;
        }
        set
        {
            if (value != isSelected)
            {
                isSelected = value;
                NotifyPropertyChanged("IsSelected");
            }
        }
    }
}

Here is the code for the CustomTextCellRenderer

public class CustomTextCellRenderer : TextCellRenderer
{
    UITableViewCell _nativeCell;

    public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
    {
        _nativeCell = base.GetCell(item, reusableCell, tv);
        var formsCell = item as CustomTextCell;

        if (formsCell != null)
        {
            formsCell.PropertyChanged -= OnPropertyChanged;
            formsCell.PropertyChanged += OnPropertyChanged;
        }

        SetCheckmark(formsCell);
        SetTap(formsCell);

        return _nativeCell;
    }

    void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        var formsCell = sender as CustomTextCell;
        if (formsCell == null)
            return;

        if (e.PropertyName == CustomTextCell.IsCheckedProperty.PropertyName)
        {
            SetCheckmark(formsCell);
        }

        if (e.PropertyName == CustomTextCell.NoTapProperty.PropertyName)
        {
            SetTap(formsCell);
        }
    }

    private void SetCheckmark(CustomTextCell formsCell)
    {
        if (formsCell.IsChecked)
            _nativeCell.Accessory = UITableViewCellAccessory.Checkmark;
        else
            _nativeCell.Accessory = UITableViewCellAccessory.None;
    }

    private void SetTap(CustomTextCell formsCell)
    {
        if (formsCell.NoTap)
            _nativeCell.SelectionStyle = UITableViewCellSelectionStyle.None;
        else
            _nativeCell.SelectionStyle = UITableViewCellSelectionStyle.Default;
    }

}

Update 1

<local:CustomTextCell           Text="{Binding [0].Name}" IsChecked="{Binding [0].IsSelected}" Tapped="cfsSelectValue" CommandParameter="0" />
<local:CustomTextCell           Text="{Binding [1].Name}" IsChecked="{Binding [1].IsSelected}" Tapped="cfsSelectValue" CommandParameter="1" />
<local:CustomTextCell           Text="{Binding [2].Name}" IsChecked="{Binding [2].IsSelected}" Tapped="cfsSelectValue" CommandParameter="2" />
<local:CustomTextCell           Text="{Binding [3].Name}" IsChecked="{Binding [3].IsSelected}" Tapped="cfsSelectValue" CommandParameter="3" />
<local:CustomTextCell           Text="{Binding [4].Name}" IsChecked="{Binding [4].IsSelected}" Tapped="cfsSelectValue" CommandParameter="4" />

Since the question was written I have stopped using this for the Lang selection however it's still used in another part of the code and I tried to put in some debug points. Here's what I did:

I added this to the iOS custom renderer:

    private void SetCheckmark(CustomTextCell formsCell)
    {
        if (formsCell.IsChecked)
        {
            _nativeCell.Accessory = UITableViewCellAccessory.Checkmark;
            Debug.WriteLine(_nativeCell.TextLabel.Text + " checked");
        }
        else
        {
            _nativeCell.Accessory = UITableViewCellAccessory.None;
            Debug.WriteLine(_nativeCell.TextLabel.Text + " unchecked");
        }
    }

Here's the result when I clicked JLPT N2:

Category Group unchecked
Category unchecked
All Available Words unchecked
Japanese for Busy People 1 unchecked
Japanese for Busy People 2 unchecked
Japanese for Busy People 3 unchecked
JLPT Level N5 unchecked
JLPT Level N4 unchecked
JLPT Level N3 unchecked
JLPT Level N2 unchecked
JLPT Level N1 checked
JLPT Level N2 checked
JLPT Level N3 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N2 checked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked
JLPT Level N1 unchecked

This was not at all what I expected.

On the screen I see that as expected N2 is disabled but there is a check mark next to N3 and N2.

Not sure if this helps but I notice the iOS renderer code used is different from similar code I have used in other places.  For example here's a different iOS renderer. Code looks very different. I realize function is different but this one has things like cell = tv.DequeueReusableCell(fullName) as CellTableViewCell;

public class TextCellCustomRenderer : TextCellRenderer
{
    CellTableViewCell cell;
    public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
    {
        var textCell = (TextCell)item;
        var fullName = item.GetType().FullName;
        cell = tv.DequeueReusableCell(fullName) as CellTableViewCell;

        if (cell == null)
        {
            cell = new CellTableViewCell(UITableViewCellStyle.Value1, fullName);
        }
        else
        {
            cell.Cell.PropertyChanged -= cell.HandlePropertyChanged;
            //cell.Cell.PropertyChanged -= Current_PropertyChanged;
        }

        cell.Cell = textCell;
        textCell.PropertyChanged += cell.HandlePropertyChanged;
        cell.PropertyChanged = this.HandlePropertyChanged;
        cell.SelectionStyle = UITableViewCellSelectionStyle.None;
        cell.TextLabel.Text = textCell.Text;
        cell.DetailTextLabel.Text = textCell.Detail;
        cell.ContentView.BackgroundColor = UIColor.White;

        switch (item.StyleId)
        {
            case "checkmark":
                cell.Accessory = UIKit.UITableViewCellAccessory.Checkmark;
                break;
            case "detail-button":
                cell.Accessory = UIKit.UITableViewCellAccessory.DetailButton;
                break;
            case "detail-disclosure-button":
                cell.Accessory = UIKit.UITableViewCellAccessory.DetailDisclosureButton;
                break;
            case "disclosure":
                cell.Accessory = UIKit.UITableViewCellAccessory.DisclosureIndicator;
                break;
            case "none":
            default:
                cell.Accessory = UIKit.UITableViewCellAccessory.None;
                break;
        }

        //UpdateBackground(cell, item);

        return cell;
    }

    void checkAccessoryVisibility() {

    }

}

Body:
As per the log statements, it looks like the unsubscribe logic for property-changed-handler is not working as expected.

With TextCellRenderer, we don't need to explicitly subscribe to property-changed-event as there is a base overridable method HandlePropertyChanged that can be re-used in this context.

Changing the renderer code to use this method (similar to this answer) should hopefully resolve this problem:

public class CustomTextCellRenderer : TextCellRenderer
{
    public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
    {
        var nativeCell = base.GetCell(item, reusableCell, tv);

        if (item is CustomTextCell formsCell)
        {
            SetCheckmark(nativeCell, formsCell);
            SetTap(nativeCell, formsCell);
        }

        return nativeCell;
    }

    protected override void HandlePropertyChanged(object sender, PropertyChangedEventArgs args)
    {
        base.HandlePropertyChanged(sender, args);

        System.Diagnostics.Debug.WriteLine($"HandlePropertyChanged {args.PropertyName}");

        var nativeCell = sender as CellTableViewCell;
        if (nativeCell?.Element is CustomTextCell formsCell)
        {
            if (args.PropertyName == CustomTextCell.IsCheckedProperty.PropertyName)
                SetCheckmark(nativeCell, formsCell);
            else if (args.PropertyName == CustomTextCell.NoTapProperty.PropertyName)
                SetTap(nativeCell, formsCell);
        }
    }

    void SetCheckmark(UITableViewCell nativeCell, CustomTextCell formsCell)
    {
        if (formsCell.IsChecked)
            nativeCell.Accessory = UITableViewCellAccessory.Checkmark;
        else
            nativeCell.Accessory = UITableViewCellAccessory.None;
    }

    void SetTap(UITableViewCell nativeCell, CustomTextCell formsCell)
    {
        if (formsCell.NoTap)
            _nativeCell.SelectionStyle = UITableViewCellSelectionStyle.None;
        else
            _nativeCell.SelectionStyle = UITableViewCellSelectionStyle.Default;
    }
}


来源: stackexchange

问:
How to properly print a list of unicode characters in python?
I am trying to search for emoticons in python strings.
So I have, for example,

```<code>em_test = ['\U0001f680']
print(em_test)
['']
test = 'This is a test string '
if any(x in test for x in em_test):
    print ("yes, the emoticon is there")
else:
    print ("no, the emoticon is not there")

yes, the emoticon is there
</code>```

and if a search em_test in

'This is a test string '

I can actually find it.

So I have made a csv file with all the emoticons I want defined by their unicode.
The CSV looks like this:

\U0001F600

\U0001F601

\U0001F602

\U0001F923

and when I import it and print it I actullay do not get the emoticons but rather just the text representation:

```<code>['\\U0001F600',
 '\\U0001F601',
 '\\U0001F602',
 '\\U0001F923',
...
]
</code>```

and hence I cannot use this to search for these emoticons in another string...
I somehow know that the double backslash \ is only representation of a single slash but somehow the unicode reader does not get it... I do not know what I'm missing.

Any suggestions?

答:
You can decode those Unicode escape sequences with .decode('unicode-escape'). However, .decode is a bytes method, so if those sequences are text rather than bytes you first need to encode them into bytes. Alternatively, you can (probably) open your CSV file in binary mode in order to read those sequences as bytes rather than as text strings.

Just for fun, I'll also use unicodedata to get the names of those emojis.

```<code>import unicodedata as ud

emojis = [
    '\\U0001F600',
    '\\U0001F601',
    '\\U0001F602',
    '\\U0001F923',
]

for u in emojis:
    s = u.encode('ASCII').decode('unicode-escape')
    print(u, ud.name(s), s)
</code>```

output

```<code>\U0001F600 GRINNING FACE
\U0001F601 GRINNING FACE WITH SMILING EYES
\U0001F602 FACE WITH TEARS OF JOY
\U0001F923 ROLLING ON THE FLOOR LAUGHING
</code>```

This should be much faster than using ast.literal_eval. And if you read the data in binary mode it will be even faster since it avoids the initial decoding step while reading the file, as well as allowing you to eliminate the .encode('ASCII') call.

You can make the decoding a little more robust by using

```<code>u.encode('Latin1').decode('unicode-escape')
</code>```

but that shouldn't be necessary for your emoji data. And as I said earlier, it would be even better if you open the file in binary mode to avoid the need to encode it.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to search for emoticons in python strings.
So I have, for example,

em_test = ['\U0001f680']
print(em_test)
['']
test = 'This is a test string '
if any(x in test for x in em_test):
    print ("yes, the emoticon is there")
else:
    print ("no, the emoticon is not there")

yes, the emoticon is there

and if a search em_test in

'This is a test string '

I can actually find it.

So I have made a csv file with all the emoticons I want defined by their unicode.
The CSV looks like this:

\U0001F600

\U0001F601

\U0001F602

\U0001F923

and when I import it and print it I actullay do not get the emoticons but rather just the text representation:

['\\U0001F600',
 '\\U0001F601',
 '\\U0001F602',
 '\\U0001F923',
...
]

and hence I cannot use this to search for these emoticons in another string...
I somehow know that the double backslash \ is only representation of a single slash but somehow the unicode reader does not get it... I do not know what I'm missing.

Any suggestions?

Body:
You can decode those Unicode escape sequences with .decode('unicode-escape'). However, .decode is a bytes method, so if those sequences are text rather than bytes you first need to encode them into bytes. Alternatively, you can (probably) open your CSV file in binary mode in order to read those sequences as bytes rather than as text strings.

Just for fun, I'll also use unicodedata to get the names of those emojis.

import unicodedata as ud

emojis = [
    '\\U0001F600',
    '\\U0001F601',
    '\\U0001F602',
    '\\U0001F923',
]

for u in emojis:
    s = u.encode('ASCII').decode('unicode-escape')
    print(u, ud.name(s), s)

output

\U0001F600 GRINNING FACE
\U0001F601 GRINNING FACE WITH SMILING EYES
\U0001F602 FACE WITH TEARS OF JOY
\U0001F923 ROLLING ON THE FLOOR LAUGHING

This should be much faster than using ast.literal_eval. And if you read the data in binary mode it will be even faster since it avoids the initial decoding step while reading the file, as well as allowing you to eliminate the .encode('ASCII') call.

You can make the decoding a little more robust by using

u.encode('Latin1').decode('unicode-escape')

but that shouldn't be necessary for your emoji data. And as I said earlier, it would be even better if you open the file in binary mode to avoid the need to encode it.

ContentLicense: CC BY-SA 3.0


问:
How to set headers for json web token in expressjs?
Hello I am working on mock authentication in nodeJs using express framework.I am using passport-jwt and jasonwebtoken for authentication. I created api and working well on postman.But I stuck on front end side I am not able to use protected api's on front end side.In postman i send token using headers and it works well.But it does not work on front end side.How to send token and verify from front end side??
My code is:

```<code>app.post("/login", function(req, res) {
  if(req.body.name && req.body.password){
    var name = req.body.name;
    var password = req.body.password;
  }

  var user = users[_.findIndex(users, {name: name})];
  if( ! user ){
    res.status(401).json({message:"no such user found"});
  }

  if(user.password === req.body.password) {

    var payload = {id: user.id};
    var token = jwt.sign(payload, jwtOptions.secretOrKey);
    res.json({message: "ok", token: token});
  } else {
    res.status(401).json({message:"passwords did not match"});
  }
});
</code>```

and if token is valid this post method should redirect to this page

```<code>app.get("/secret", passport.authenticate('jwt', { session: false }), function(req, res){
        res.json("Success! You can not see this without a token");

  });
</code>```

答:
```<code>npm install cookie-parser

var cookieParser = require('cookie-parser')
app.use(cookieParser())
app.use(function (req, res, next) {
var cookie = req.cookies.jwtToken;
if (!cookie) {
    res.cookie('jwtToken', theJwtTokenValue,
             { maxAge: 900000, httpOnly: true });
} else {
    console.log('let's check that this is a valid cookie');
    // send cookie along to the validation functions...
}
next();
});
</code>```

Body:
Hello I am working on mock authentication in nodeJs using express framework.I am using passport-jwt and jasonwebtoken for authentication. I created api and working well on postman.But I stuck on front end side I am not able to use protected api's on front end side.In postman i send token using headers and it works well.But it does not work on front end side.How to send token and verify from front end side??
My code is:

app.post("/login", function(req, res) {
  if(req.body.name && req.body.password){
    var name = req.body.name;
    var password = req.body.password;
  }

  var user = users[_.findIndex(users, {name: name})];
  if( ! user ){
    res.status(401).json({message:"no such user found"});
  }

  if(user.password === req.body.password) {

    var payload = {id: user.id};
    var token = jwt.sign(payload, jwtOptions.secretOrKey);
    res.json({message: "ok", token: token});
  } else {
    res.status(401).json({message:"passwords did not match"});
  }
});

and if token is valid this post method should redirect to this page

app.get("/secret", passport.authenticate('jwt', { session: false }), function(req, res){
        res.json("Success! You can not see this without a token");

  });


问:
Chinese and Japanese character encoding issues when exporting HTML to PDF
I run a web-based timeline maker that lets users create timelines in HTML/JavaScript and then export them to PDF files for printing when they're done.

I have had several users report issues with exporting their timelines to PDFs when the timelines contain certain Unicode characters. Here, for example, is a screenshot showing the web page and the PDF file that is generated:

I've been trying to wrap my head around why some Unicode character blocks like Block Elements and Georgian will export but Chinese and Japanese will not. Also, the export works correctly when I perform it on my local computer, but results in the above output when exporting on Heroku.

Does anyone know what might be causing this?

For completeness, the backend is in Ruby on Rails and it uses the PDFKit gem to convert the HTML page to a PDF and the site is hosted on Heroku.

答:
If you do use Docker and is having the same issue above then try installing Japanese fonts at Docker: apt-get install fonts-takao-mincho

If it works then add it to your Dockerfile:

```<code>apt update && apt install -y \
# japanese fonts
fonts-takao-mincho
</code>```

Body:
If you do use Docker and is having the same issue above then try installing Japanese fonts at Docker: apt-get install fonts-takao-mincho

If it works then add it to your Dockerfile:

apt update && apt install -y \
# japanese fonts
fonts-takao-mincho


问:
Python: While loop inside a for loop only running for the first instance of for variable
So here's my problem: I have a for loop with a variable k running from 1 to 31. Inside the for loop there is a while loop that seemingly only runs for the very first k and no others.

```<code>from numpy import exp

a = 0.0
N = 1
x = 0.1

def f(t):
    return exp(-t**2)

def int_trap(x,N):
    h = (x-a)/N
    s = 0.5*f(a) + 0.5*f(x)
    for i in range(1,N):
        s += f(a + i*h)
    return h*s

new_value = 1.0
old_value = 0.0

for k in range(1,11):
    x = k/10
    while abs(new_value - old_value) > 10**-6:
        old_value = new_value
        N = N*2
        new_value = int_trap(x,N)
        print(N,'\t',x,'\t',abs(new_value - old_value))
    print(x)
</code>```

The print(x) at the end is there to confirm that that the code is running through the k's.

And here's the output:

```<code>2        0.1     0.900373598036
4        0.1     3.09486672713e-05
8        0.1     7.73536466929e-06
16       0.1     1.93372859864e-06
32       0.1     4.83425115119e-07
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0
</code>```

答:
The for loop runs fine through all k values. It doesn't run through the while loop, perhaps because you don't reset the new_value and old_value variables inside the for loop. If we add some things to print to the original loop:

```<code>for k in range(1,11):
    x = k/10
    while abs(new_value - old_value) > 10**-6:
        old_value = new_value
        N = N*2
        new_value = int_trap(x,N)
        print(N,'\t',x,'\t',abs(new_value - old_value), 'In while for x={} and k={}'.format(x, k))
    print(x, '\tThis is me completing the loop for k=', k)
</code>```

We see that it is correctly running for all k values:

```<code>2    0.1     0.900373598036 In while for x=0.1 and k=1
4    0.1     3.09486672713e-05 In while for x=0.1 and k=1
8    0.1     7.73536466929e-06 In while for x=0.1 and k=1
16   0.1     1.93372859864e-06 In while for x=0.1 and k=1
32   0.1     4.83425115119e-07 In while for x=0.1 and k=1
0.1     This is me completing the loop for k= 1
0.2     This is me completing the loop for k= 2
0.3     This is me completing the loop for k= 3
0.4     This is me completing the loop for k= 4
0.5     This is me completing the loop for k= 5
0.6     This is me completing the loop for k= 6
0.7     This is me completing the loop for k= 7
0.8     This is me completing the loop for k= 8
0.9     This is me completing the loop for k= 9
1.0     This is me completing the loop for k= 10
</code>```

So try the following:

```<code>for k in range(1,11):
    x = k/10
    new_value = 1.0
    old_value = 0.0
    while abs(new_value - old_value) > 10**-6:
        old_value = new_value
        N = N*2
        new_value = int_trap(x,N)
        print(N,'\t',x,'\t',abs(new_value - old_value), 'In while for x={} and k={}'.format(x, k))
    print(x, '\tThis is me completing the loop for k=', k)
</code>```

Body:
So here's my problem: I have a for loop with a variable k running from 1 to 31. Inside the for loop there is a while loop that seemingly only runs for the very first k and no others.

from numpy import exp

a = 0.0
N = 1
x = 0.1

def f(t):
    return exp(-t**2)

def int_trap(x,N):
    h = (x-a)/N
    s = 0.5*f(a) + 0.5*f(x)
    for i in range(1,N):
        s += f(a + i*h)
    return h*s

new_value = 1.0
old_value = 0.0

for k in range(1,11):
    x = k/10
    while abs(new_value - old_value) > 10**-6:
        old_value = new_value
        N = N*2
        new_value = int_trap(x,N)
        print(N,'\t',x,'\t',abs(new_value - old_value))
    print(x)

The print(x) at the end is there to confirm that that the code is running through the k's.

And here's the output:

2        0.1     0.900373598036
4        0.1     3.09486672713e-05
8        0.1     7.73536466929e-06
16       0.1     1.93372859864e-06
32       0.1     4.83425115119e-07
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0

Body:
The for loop runs fine through all k values. It doesn't run through the while loop, perhaps because you don't reset the new_value and old_value variables inside the for loop. If we add some things to print to the original loop:

for k in range(1,11):
    x = k/10
    while abs(new_value - old_value) > 10**-6:
        old_value = new_value
        N = N*2
        new_value = int_trap(x,N)
        print(N,'\t',x,'\t',abs(new_value - old_value), 'In while for x={} and k={}'.format(x, k))
    print(x, '\tThis is me completing the loop for k=', k)

We see that it is correctly running for all k values:

2    0.1     0.900373598036 In while for x=0.1 and k=1
4    0.1     3.09486672713e-05 In while for x=0.1 and k=1
8    0.1     7.73536466929e-06 In while for x=0.1 and k=1
16   0.1     1.93372859864e-06 In while for x=0.1 and k=1
32   0.1     4.83425115119e-07 In while for x=0.1 and k=1
0.1     This is me completing the loop for k= 1
0.2     This is me completing the loop for k= 2
0.3     This is me completing the loop for k= 3
0.4     This is me completing the loop for k= 4
0.5     This is me completing the loop for k= 5
0.6     This is me completing the loop for k= 6
0.7     This is me completing the loop for k= 7
0.8     This is me completing the loop for k= 8
0.9     This is me completing the loop for k= 9
1.0     This is me completing the loop for k= 10

So try the following:

for k in range(1,11):
    x = k/10
    new_value = 1.0
    old_value = 0.0
    while abs(new_value - old_value) > 10**-6:
        old_value = new_value
        N = N*2
        new_value = int_trap(x,N)
        print(N,'\t',x,'\t',abs(new_value - old_value), 'In while for x={} and k={}'.format(x, k))
    print(x, '\tThis is me completing the loop for k=', k)


问:
The condition `WHERE Id = 14317961` in my query is invalid
```<code>var report = AdWordsApp.report(
           'SELECT Id, Criteria, CpcBid, FirstPageCpc, FirstPositionCpc, TopOfPageCpc, Criteria ' +
           'FROM   KEYWORDS_PERFORMANCE_REPORT ' +
           'WHERE' +
           'Id = 14317961 ' +
           'DURING LAST_7_DAYS ');
var rows = report.rows();

while(rows.hasNext()) {
    var row = rows.next();
    var keywordIdReport = row['Id'];
    var keywordNameReport = row['Criteria'];
    var cpcBid = row['CpcBid'];
    var firstPageCpc = row['FirstPageCpc'];
    var firstPositionCpc = row['FirstPositionCpc'];
    var topOfPageCpc = row['TopOfPageCpc'];

    Logger.log('KeywordIdReport :' + keywordIdReport)
    Logger.log('CPCbid :' + cpcBid)
    Logger.log('firstPositionCpc : ' + firstPositionCpc)
    Logger.log('topOfPageCpc : ' + topOfPageCpc)
    Logger.log('firstPageCpc : ' + firstPageCpc)
}
</code>```

I don't understand why, but the Adwords IDE tell me that the condition WHERE Id = 14317961 in my query is invalid, but I can't explain it is wrong. Assume here that the current Id exists. The purpose of that query is to access the three fields firstPositionCpc, topOfPageCpc and firstPageCpc for the specific keyword id. How could I fix my problem?

答:
There is no space after the 'WHERE' +

Add a space after it 'WHERE ' +.

Body:
var report = AdWordsApp.report(
           'SELECT Id, Criteria, CpcBid, FirstPageCpc, FirstPositionCpc, TopOfPageCpc, Criteria ' +
           'FROM   KEYWORDS_PERFORMANCE_REPORT ' +
           'WHERE' +
           'Id = 14317961 ' +
           'DURING LAST_7_DAYS ');
var rows = report.rows();

while(rows.hasNext()) {
    var row = rows.next();
    var keywordIdReport = row['Id'];
    var keywordNameReport = row['Criteria'];
    var cpcBid = row['CpcBid'];
    var firstPageCpc = row['FirstPageCpc'];
    var firstPositionCpc = row['FirstPositionCpc'];
    var topOfPageCpc = row['TopOfPageCpc'];

    Logger.log('KeywordIdReport :' + keywordIdReport)
    Logger.log('CPCbid :' + cpcBid)
    Logger.log('firstPositionCpc : ' + firstPositionCpc)
    Logger.log('topOfPageCpc : ' + topOfPageCpc)
    Logger.log('firstPageCpc : ' + firstPageCpc)
}

I don't understand why, but the Adwords IDE tell me that the condition WHERE Id = 14317961 in my query is invalid, but I can't explain it is wrong. Assume here that the current Id exists. The purpose of that query is to access the three fields firstPositionCpc, topOfPageCpc and firstPageCpc for the specific keyword id. How could I fix my problem?


问:
Open Chrome with selenium
```<code>public static void main(String[] args) {
    System.setProperty("webdriver.chrome.driver", "C:/Users/myPC/Desktop/chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.get("http://www.google.com");
}
</code>```

So I downloaded chromedriver.exe and tried opening Chrome using the following code, but every time I run this code I get the following error:

```<code>Error:java: package com.google.common.collect does not exist
</code>```

And also whenever I try and run chromedriver.exe from desktop, chrome does not want to open.

Thanks in advance

答:
```<code>public static void main(String[] args) {
    System.setProperty("webdriver.chrome.driver", "C:/Users/myPC/Desktop/chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.navigate().to("http://www.google.com");
}
</code>```

Title: Open Chrome with selenium

Body:
public static void main(String[] args) {
    System.setProperty("webdriver.chrome.driver", "C:/Users/myPC/Desktop/chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.get("http://www.google.com");
}

So I downloaded chromedriver.exe and tried opening Chrome using the following code, but every time I run this code I get the following error:

Error:java: package com.google.common.collect does not exist

And also whenever I try and run chromedriver.exe from desktop, chrome does not want to open.

Thanks in advance


问:
How to extract only specific parts from an image?

Hello, I have a task to build an android app that extracts only specific parts of an image.Like, for example, extract only the part of the image that contains the phone number above and then use an OCR to extract the text in that part.

I have already implemented Google's Text Recognition API to extract text from an image and it works good, but I don't want to extract everything, just a specific part.

Is that possible? and if it is, what techniques should I use to solve this problem?

Thank you

答:
Without any context, I am not sure whether you can actually pinpoint where the phone number (in this example) is or not. So simple question would be no, in my humble opinion.

However, if you can change the problem domain a little bit, I think you can do what you are trying to do.

What I mean by that is simple. Before the image of that RX is taken, can you ask the person who is taking picture or who is scanning that document to highlight the phone number field? Or can you ask them to put the phone number in a box? (Or simply, make the phone number look different from the rest of the info). If they can do so, you can then spot the highlighted portion, (or look for the box, or whatever else they did to differentiate the phone number field) separate it from the rest of the image and send it over to google API.

I know this solution may require human intervention and prone to error, or require messing with the problem domain. However, it may solve the problem. :)


问:
DataTables menu for select items to show per page doesn't work
On my DataTable the box where you can select how many items per page you want to show doesn't work. It is showing me this:
[[5,10],[5,10]] instead to show me only the numbers.
I tried to understand what caused this issue but without any success.

If I click on the menu one of the options I have this error also: Showing NaN to NaN of 2 entries

I'm using this in my Rails 4 app.

this is my js:

```<code>var dtMainDataTable;            // Reference to main table
var dtSecondaryDataTable;   // Reference to secondary table
var dtTertiaryDataTable;    // Reference to tertiary table
var dtMainOrder;          // Main table ordering

/*
* Create tables on document ready
*/
$(document).ready( function() {

  // Set the order of the main table and update if overridden by page.
  dtMainOrder = [0, 'asc'];
  if (typeof dtMainOrderUpdate !== 'undefined') {
    dtMainOrder = dtMainOrderUpdate;
  }

  dtMainDataTable = $('#main').DataTable({
    columnDefs: [],
    "pageLength": pageLength,
    "lengthMenu": pageSettings,
    "order": dtMainOrder,
    responsive: true
  });

  dtSecondaryDataTable = $('#secondary').DataTable({
    columnDefs: [],
    "pageLength": pageLength,
    "lengthMenu": pageSettings,
    responsive: true
  });

  dtTertiaryDataTable = $('#tertiary').DataTable({
    columnDefs: [],
    "pageLength": pageLength,
    "lengthMenu": pageSettings,
    responsive: true
    });

});

/**
 * Show all items in the main table.
 * Really only for testing purposes.
 *
 * @return [Null]
 */
function dtMainTableAll() {
  dtMainDataTable.page.len(-1).draw();
}
</code>```

答:
I resolved my own question and hope will be useful for others.
I had this in my code: var pageLength = '#{current_user.table_rows}';
I dleeted the '' and started working again
So the result working for me is:
var pageLength = #{current_user.table_rows};

Body:
On my DataTable the box where you can select how many items per page you want to show doesn't work. It is showing me this:
[[5,10],[5,10]] instead to show me only the numbers.
I tried to understand what caused this issue but without any success.

If I click on the menu one of the options I have this error also: Showing NaN to NaN of 2 entries

I'm using this in my Rails 4 app.

this is my js:

var dtMainDataTable;            // Reference to main table
var dtSecondaryDataTable;   // Reference to secondary table
var dtTertiaryDataTable;    // Reference to tertiary table
var dtMainOrder;          // Main table ordering

/*
* Create tables on document ready
*/
$(document).ready( function() {

  // Set the order of the main table and update if overridden by page.
  dtMainOrder = [0, 'asc'];
  if (typeof dtMainOrderUpdate !== 'undefined') {
    dtMainOrder = dtMainOrderUpdate;
  }

  dtMainDataTable = $('#main').DataTable({
    columnDefs: [],
    "pageLength": pageLength,
    "lengthMenu": pageSettings,
    "order": dtMainOrder,
    responsive: true
  });

  dtSecondaryDataTable = $('#secondary').DataTable({
    columnDefs: [],
    "pageLength": pageLength,
    "lengthMenu": pageSettings,
    responsive: true
  });

  dtTertiaryDataTable = $('#tertiary').DataTable({
    columnDefs: [],
    "pageLength": pageLength,
    "lengthMenu": pageSettings,
    responsive: true
    });

});

/**
 * Show all items in the main table.
 * Really only for testing purposes.
 *
 * @return [Null]
 */
function dtMainTableAll() {
  dtMainDataTable.page.len(-1).draw();
}


问:
Add another field for legend in amcharts to show percentage
I am using amcharts to create a piechart for some details in codeigniter and I use pie chart with legend(http://www.amcharts.com/demos/pie-chart-with-legend/) and I made view the legend with title and value just like in the demo. Now I want to add another field for the legend that display relevant percentage in line for each. Are there any keyword or method to do that? I am new to programming.
Here's my code..</p>

```<code>$data['chartOne'] = $this->prepareJson($totalQuotations, "q");
$data['chartTwo'] = $this->prepareJson($totalContribution, "c");

<script type = "text/javascript">
                    var chart1 = AmCharts.makeChart( "salesReportPerformanceChartdiv",' . $data["chartOne"] . ');
                    var chart2 = AmCharts.makeChart( "salesReportContributionChartdiv",' . $data["chartTwo"] . ');
                </script>';

public function prepareJson($data, $type) {
    $chatData = [];
    foreach ($data as $status) {
        $stustotal = new \stdClass();
        $stustotal->y = $status->count;
        if ($type == "q") {
            $stustotal->x = $status->status_name;
        } else if ($type == "c") {
            $stustotal->x = $status->user_name;
        }
        array_push($chatData, $stustotal);
    }

    $listeners = new \stdClass();
    $listeners->method = addLegendLabel;
    $listeners->event = "drawn";

    $export = new \stdClass();
    $export->enabled = true;

    $legend = new \stdClass();
    $legend->position = "right";
    $legend->markerType = "circle";
    $legend->autoMargins = true;

    $feOffset = new \stdClass();
    $feOffset->result = "offOut";
    $feOffset->in = "SourceAlpha";
    $feOffset->dx = 0;
    $feOffset->dy = 0;

    $feGaussianBlur = new \stdClass();
    $feGaussianBlur->result = "blurOut";
    $feGaussianBlur->in = "offOut";
    $feGaussianBlur->stdDeviation = 5;

    $feBlend = new \stdClass();
    $feBlend->in = "SourceGraphic";
    $feBlend->in2 = "blurOut";
    $feBlend->mode = "normal";

    $filter = new \stdClass();
    $filter->id = "shadow";
    $filter->width = "200%";
    $filter->height = "200%";
    $filter->feOffset = $feOffset;
    $filter->feGaussianBlur = $feGaussianBlur;
    $filter->feBlend = $feBlend;

    $defs = new \stdClass();
    $defs->filter = $filter;

    $chart = new \stdClass();
    $chart->type = "pie";
    $chart->startDuration = 0;
    $chart->theme = "light";
    $chart->addClassNames = true;
    $chart->legend = $legend;
    $chart->innerRadius = "85%";
    $chart->defs = $defs;
    $chart->dataProvider = (array)$chatData;
    $chart->valueField = "y";
    $chart->titleField = "x";
    $chart->labelRadius = 5;
    $chart->radius = "42%";
    $chart->labelText = "";
    $chart->listeners = $listeners;
    $chart->export = $export;

    $chartJSON = json_encode($chart);

    return $chartJSON;
}
</code>```

答:
You can customize the legend's valueText to include the percents by adding the [[percents]] shortcode to the string. By default, it is set to "[[value]]". In your case, it looks like you have to set it through your $legend variable. You might also want to set the valueWidth to accommodate for the longer value string like so:

```<code>$legend->valueText = "[[value]] [[percents]]%"; //customize as needed
$legend->valueWidth = 100; //adjust as needed so it doesn't overlap
</code>```

Fiddle

Body:
I am using amcharts to create a piechart for some details in codeigniter and I use pie chart with legend(http://www.amcharts.com/demos/pie-chart-with-legend/) and I made view the legend with title and value just like in the demo. Now I want to add another field for the legend that display relevant percentage in line for each. Are there any keyword or method to do that? I am new to programming.
Here's my code..

$data['chartOne'] = $this->prepareJson($totalQuotations, "q");
$data['chartTwo'] = $this->prepareJson($totalContribution, "c");

';

public function prepareJson($data, $type) {
    $chatData = [];
    foreach ($data as $status) {
        $stustotal = new \stdClass();
        $stustotal->y = $status->count;
        if ($type == "q") {
            $stustotal->x = $status->status_name;
        } else if ($type == "c") {
            $stustotal->x = $status->user_name;
        }
        array_push($chatData, $stustotal);
    }

    $listeners = new \stdClass();
    $listeners->method = addLegendLabel;
    $listeners->event = "drawn";

    $export = new \stdClass();
    $export->enabled = true;

    $legend = new \stdClass();
    $legend->position = "right";
    $legend->markerType = "circle";
    $legend->autoMargins = true;

    $feOffset = new \stdClass();
    $feOffset->result = "offOut";
    $feOffset->in = "SourceAlpha";
    $feOffset->dx = 0;
    $feOffset->dy = 0;

    $feGaussianBlur = new \stdClass();
    $feGaussianBlur->result = "blurOut";
    $feGaussianBlur->in = "offOut";
    $feGaussianBlur->stdDeviation = 5;

    $feBlend = new \stdClass();
    $feBlend->in = "SourceGraphic";
    $feBlend->in2 = "blurOut";
    $feBlend->mode = "normal";

    $filter = new \stdClass();
    $filter->id = "shadow";
    $filter->width = "200%";
    $filter->height = "200%";
    $filter->feOffset = $feOffset;
    $filter->feGaussianBlur = $feGaussianBlur;
    $filter->feBlend = $feBlend;

    $defs = new \stdClass();
    $defs->filter = $filter;

    $chart = new \stdClass();
    $chart->type = "pie";
    $chart->startDuration = 0;
    $chart->theme = "light";
    $chart->addClassNames = true;
    $chart->legend = $legend;
    $chart->innerRadius = "85%";
    $chart->defs = $defs;
    $chart->dataProvider = (array)$chatData;
    $chart->valueField = "y";
    $chart->titleField = "x";
    $chart->labelRadius = 5;
    $chart->radius = "42%";
    $chart->labelText = "";
    $chart->listeners = $listeners;
    $chart->export = $export;

    $chartJSON = json_encode($chart);

    return $chartJSON;
}

Body:
You can customize the legend's valueText to include the percents by adding the [[percents]] shortcode to the string. By default, it is set to "[[value]]". In your case, it looks like you have to set it through your $legend variable. You might also want to set the valueWidth to accommodate for the longer value string like so:

$legend->valueText = "[[value]] [[percents]]%"; //customize as needed
$legend->valueWidth = 100; //adjust as needed so it doesn't overlap

Fiddle


问:
xstl apply-template (call tempalate) with variable and use in xsl:evaluate
I have the following xml:

```<code><pi:Payroll_Extract_Employees xmlns:pi="urn:com.workday/picof">
   <pi:company>
      <pi:Employee>
         <pi:name>John Andrews</pi:name>
         <pi:age>23</pi:age>
         <pi:salary>4000</pi:salary>
         <pi:division>Accounting</pi:division>
      </pi:Employee>
   </pi:company>
</pi:Payroll_Extract_Employees>
</code>```

I am using this transformation:

```<code><xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:pi="urn:com.workday/picof">
    <xsl:output method="text"/>
    <xsl:template match="pi:Payroll_Extract_Employees/pi:company">
        <xsl:variable name="tabsNames">
            <entry>
                <spreadSheetName>Payroll Data for Taiwan</spreadSheetName>
                <values>
                    <value>
                        <header>Chinese Name</header>
                        <data>/pi:Name</data>
                    </value>
                </values>
            </entry>
        </xsl:variable>
        <xsl:variable name="currentNode" select="."/>
        <xsl:for-each select="$tabsNames/entry">
            <xsl:variable name="dataValues" select="values/value/data"/>

            <xsl:call-template name="employeeRows">
                <xsl:with-param name="rows" select="$dataValues" as="element()*"/>
                <xsl:with-param name="currentNode" select="$currentNode" as="element()"/>
            </xsl:call-template>

        </xsl:for-each>
    </xsl:template>
    <xsl:template name="employeeRows">
        <xsl:param name="rows" select="."/>
        <xsl:param name="currentNode" select="."/>

        <xsl:for-each select="$currentNode/pi:Employee">
            <xsl:variable name="employee" select="." as="element()"/>
            <xsl:for-each select="$rows">
                <xsl:variable name="path" select="."/>
                <xsl:value-of>
                    <xsl:evaluate xpath="$employee || $path" context-item="."/>
                    <!--<xsl:value-of select="$employee/pi:name"/>-->
                </xsl:value-of>
            </xsl:for-each>
        </xsl:for-each>

    </xsl:template>
</xsl:stylesheet>
</code>```

Here I am creating a map $tabNames and the would like to pass map together with current node to employeeRows template. Instead of data values for "rows" parameter I get entire map and instead of current node (pi:Payroll_Extract_Employees/pi:company) for currentNode parameter I receive the same map as for the "rows" parameter.
The second problem is that xsl:evaluates changes $employee to a value I would like following to give me the same output

```<code><xsl:evaluate xpath="$employee || $path" context-item="."/>
</code>```

as this

```<code><xsl:value-of select="$employee/pi:Name"/>
</code>```

What I have so far throws an error here:

```<code><xsl:evaluate xpath="$employee || $path" context-item="."/>
</code>```

Error message:

System ID: C:\Users\przemekb\AppData\Local\Temp\Untitled4.xsl
Severity: fatal
Description: Static error in XPath expression supplied to xsl:evaluate: Unexpected token name "Andrews" beyond end of expression. Expression: { John Andrews 23 4000 Accounting pi:Name}
Start location: 36:42
Length: 1

答:
I suspect that in this element

<data>pi:Summary/pi:Name</data>

the content is intended to be an XPath expression, and that you expect this XPath expression to be evaluated. That's not a correct expectation; use an xsl:value-of instruction.

I suspect that

<xsl:variable name="dataValues" select="values/value/data"/>

should be

```<code><xsl:variable name="dataValues" select="$tabsName/entry/values/value/data"/>
</code>```

though I can't account for the output you said you got.

In this:

<xsl:with-param name="currentNode" select="." as="node()*"/>

there's something amiss because "." will always be a singleton, so why does the "as" attribute suggest it might be a sequence?

Body:
I have the following xml:

<pi:Payroll_Extract_Employees xmlns:pi="urn:com.workday/picof">
   <pi:company>
      <pi:Employee>
         <pi:name>John Andrews</pi:name>
         <pi:age>23</pi:age>
         <pi:salary>4000</pi:salary>
         <pi:division>Accounting</pi:division>
      </pi:Employee>
   </pi:company>
</pi:Payroll_Extract_Employees>

I am using this transformation:

<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:pi="urn:com.workday/picof">
    <xsl:output method="text"/>
    <xsl:template match="pi:Payroll_Extract_Employees/pi:company">
        <xsl:variable name="tabsNames">
            <entry>
                <spreadSheetName>Payroll Data for Taiwan</spreadSheetName>
                <values>
                    <value>
                        Chinese Name
                        <data>/pi:Name</data>
                    </value>
                </values>
            </entry>
        </xsl:variable>
        <xsl:variable name="currentNode" select="."/>
        <xsl:for-each select="$tabsNames/entry">
            <xsl:variable name="dataValues" select="values/value/data"/>

            <xsl:call-template name="employeeRows">
                <xsl:with-param name="rows" select="$dataValues" as="element()*"/>
                <xsl:with-param name="currentNode" select="$currentNode" as="element()"/>
            </xsl:call-template>

        </xsl:for-each>
    </xsl:template>
    <xsl:template name="employeeRows">
        <xsl:param name="rows" select="."/>
        <xsl:param name="currentNode" select="."/>

        <xsl:for-each select="$currentNode/pi:Employee">
            <xsl:variable name="employee" select="." as="element()"/>
            <xsl:for-each select="$rows">
                <xsl:variable name="path" select="."/>
                <xsl:value-of>
                    <xsl:evaluate xpath="$employee || $path" context-item="."/>

                </xsl:value-of>
            </xsl:for-each>
        </xsl:for-each>

    </xsl:template>
</xsl:stylesheet>

Here I am creating a map $tabNames and the would like to pass map together with current node to employeeRows template. Instead of data values for "rows" parameter I get entire map and instead of current node (pi:Payroll_Extract_Employees/pi:company) for currentNode parameter I receive the same map as for the "rows" parameter.
The second problem is that xsl:evaluates changes $employee to a value I would like following to give me the same output

<xsl:evaluate xpath="$employee || $path" context-item="."/>

as this

<xsl:value-of select="$employee/pi:Name"/>

What I have so far throws an error here:

<xsl:evaluate xpath="$employee || $path" context-item="."/>

Error message:

System ID: C:\Users\przemekb\AppData\Local\Temp\Untitled4.xsl
Severity: fatal
Description: Static error in XPath expression supplied to xsl:evaluate: Unexpected token name "Andrews" beyond end of expression. Expression: { John Andrews 23 4000 Accounting pi:Name}
Start location: 36:42
Length: 1

Body:
I suspect that in this element

<data>pi:Summary/pi:Name</data>

the content is intended to be an XPath expression, and that you expect this XPath expression to be evaluated. That's not a correct expectation; use an xsl:value-of instruction.

I suspect that

<xsl:variable name="dataValues" select="values/value/data"/>

should be

<xsl:variable name="dataValues" select="$tabsName/entry/values/value/data"/>

though I can't account for the output you said you got.

In this:

<xsl:with-param name="currentNode" select="." as="node()*"/>

there's something amiss because "." will always be a singleton, so why does the "as" attribute suggest it might be a sequence?


问:
Crosswalk for iOS not working with iOS SDK 10.1.1
I am making an iOS app using crosswalk iOS web application runtime version 1.2.0. It works well till iOS SDK 9.2 but with latest iOS SDK 10.1.1 it gives compile time errors about Swift syntax as crosswalk for iOS is written in both Swift (maybe 1.0 or 1.2 Swift version) & Objective-C. As it is written in old Swift version (older than 2.3) I am getting compile time errors about Swift syntax in the library with latest iOS SDK 10.1.1 while compiling in Xcode 8.

When I set "use legacy swift language version" setting to yes from unspecified the above happens i.e. I get compile time errors about Swift syntax in library. & when I convert crosswalk iOS library to Swift 3 or 2.3 using Xcode 8 using crosswalk iOS SDK 10.1.1 it still throws compile time errors about the syntax in .swift files. When I set "use legacy swift language version" setting to no still get compile time errors about syntax. When I set "use legacy swift language version" to unspecified it gives "Use Legacy Swift Language Version" (SWIFT_VERSION) is required to be configured correctly for targets which use Swift. Use the [Edit > Convert > To Current Swift Syntax…] menu to choose a Swift version or use the Build Settings editor to configure the build setting directly.

Building the app with library with iOS SDK version 9.2 & installing the .ipa file in iPhone 5s using version 10.1.1 the app installs but is not running. It simply starts & then shuts down instantly.

I integrated the crosswalk library using cocoapods.

I need help in using crosswalk iOS library 1.2.0 (which is latest as till Nov. 2016) with latest iOS SDK 10.1.1.

Please let me know if any clarification is needed.

答: Modifying the complete (Swift part) library to latest Swift version solved the problem. Just had to solve syntax errors from old Swift version to latest Swift version.</p>


问:
Asp.NET DropDownList Resets SelectedIndex after PostBack
After doing a lot of research online I'm still stumped by this problem.  I have a page that loads the names and count of categories into a drop down list.  I only do this if !(Page.IsPostBack).  When AutoPostBack fires the SelectedIndex = 0.  I've tried several different things.  Here is my code:

PAGE

```<code><form id="AddAssignmentForm" runat="server">
<asp:ScriptManager ID="ScriptManager1" EnablePartialRendering="true" runat="server" />

<asp:UpdatePanel ID="CommentUpdate" runat="server">
<ContentTemplate>

Add Comment
<asp:DropDownList ID="ddlCategory" runat="server" Width="206" OnSelectedIndexChanged="ddlCategory_SelectedIndexChanged" AutoPostBack="true" />
<asp:TextBox ID="txtName" runat="server" Width="200" />
<asp:TextBox ID="txtAbbrv" runat="server" Width="200" />
<asp:TextBox ID="txtDescription" runat="server" Width="200" Height="90" TextMode="MultiLine" />

</ContentTemplate>
</asp:UpdatePanel>
</form>
</code>```

Here is the back end code.

```<code>private void Page_Load(object sender, System.EventArgs e)
{
    if (!Page.IsPostBack)
    {
        GetCategories();
    }
}

public void GetCategories()
{
    String strSql = @"SELECT Name, Total
                        FROM MyTable";

    if (con.State == ConnectionState.Closed)
        con.Open();

    OleDbCommand cmdsql = new OleDbCommand(strSql, con);
    OleDbDataReader cmdReader = cmdsql.ExecuteReader();

    if (cmdReader.HasRows)
    {
        while (cmdReader.Read())
        {
            ddlCategory.Items.Add(new ListItem(cmdReader["Category_Name"].ToString(), cmdReader["Total"].ToString()));

        }
        ddlCategory.SelectedIndex = -1;
    }

    cmdReader.Close();
    con.Close();
}

public void FillForm(int index)
{
    ListItem item = ddlCategory.Items[index];
    txtName.Text = item.Text + " " + (Convert.ToInt32(item.Value) + 1).ToString();
    txtAbbrv.Text = item.Text.Substring(0, 1) + (Convert.ToInt32(item.Value) + 1).ToString();
}

public void ddlCategory_SelectedIndexChanged(Object sender, EventArgs e)
{
    //When I break here SelectedIndex always = 1.
    FillForm(ddlCategory.SelectedIndex);
}
</code>```

I just want to be able to populate the form based on the selected index, but I can't seem to get the correct answer.  Any help is appreciated.

答:
You have to load list to DropDownList if not IsPostBack

Example code:

```<code>if (!IsPostBack)
{
   //fill here
}
</code>```

Body:
After doing a lot of research online I'm still stumped by this problem.  I have a page that loads the names and count of categories into a drop down list.  I only do this if !(Page.IsPostBack).  When AutoPostBack fires the SelectedIndex = 0.  I've tried several different things.  Here is my code:

PAGE

<form id="AddAssignmentForm" runat="server">
<asp:ScriptManager ID="ScriptManager1" EnablePartialRendering="true" runat="server" />

<asp:UpdatePanel ID="CommentUpdate" runat="server">
<ContentTemplate>

Add Comment
<asp:DropDownList ID="ddlCategory" runat="server" Width="206" OnSelectedIndexChanged="ddlCategory_SelectedIndexChanged" AutoPostBack="true" />
<asp:TextBox ID="txtName" runat="server" Width="200" />
<asp:TextBox ID="txtAbbrv" runat="server" Width="200" />
<asp:TextBox ID="txtDescription" runat="server" Width="200" Height="90" TextMode="MultiLine" />

</ContentTemplate>
</asp:UpdatePanel>
</form>

Here is the back end code.

private void Page_Load(object sender, System.EventArgs e)
{
    if (!Page.IsPostBack)
    {
        GetCategories();
    }
}

public void GetCategories()
{
    String strSql = @"SELECT Name, Total
                        FROM MyTable";

    if (con.State == ConnectionState.Closed)
        con.Open();

    OleDbCommand cmdsql = new OleDbCommand(strSql, con);
    OleDbDataReader cmdReader = cmdsql.ExecuteReader();

    if (cmdReader.HasRows)
    {
        while (cmdReader.Read())
        {
            ddlCategory.Items.Add(new ListItem(cmdReader["Category_Name"].ToString(), cmdReader["Total"].ToString()));

        }
        ddlCategory.SelectedIndex = -1;
    }

    cmdReader.Close();
    con.Close();
}

public void FillForm(int index)
{
    ListItem item = ddlCategory.Items[index];
    txtName.Text = item.Text + " " + (Convert.ToInt32(item.Value) + 1).ToString();
    txtAbbrv.Text = item.Text.Substring(0, 1) + (Convert.ToInt32(item.Value) + 1).ToString();
}

public void ddlCategory_SelectedIndexChanged(Object sender, EventArgs e)
{
    //When I break here SelectedIndex always = 1.
    FillForm(ddlCategory.SelectedIndex);
}

I just want to be able to populate the form based on the selected index, but I can't seem to get the correct answer.  Any help is appreciated.

Body:
You have to load list to DropDownList if not IsPostBack

Example code:

if (!IsPostBack)
{
   //fill here
}


问:
Cannot connect to MySQL db, PHP
Hello I am trying to connect MySQL database using mircloud host service but it does not connect. I tried to connect locally using phpMyAdmin but still give me this error.  This is my connect code.</p>

```<code><!-- connot connect to database -->
<?php
define (DB_USER, "root");
define (DB_PASSWORD, "gOJTkc7QSL");
define (DB_DATABASE, "rbkLastTask");
define (DB_HOST, "https://node42861-env-2276018.mircloud.host");
?>

<?php
$server = DB_HOST;
$user = DB_USER;
$pw = DB_PASSWORD;
$db = DB_DATABASE;
// $con = mysqli_connect($server,$user,$pw,$db);
$con=mysqli_connect($server,$user,$pw,$db);
Echo mysqli_connect_error();
if($con)
{
    echo "success";
}
else
{
    echo "failed";
}
?>
</code>```

答:
try this code

write this way  your code

```<code><?php
define ("DB_USER", "root"); //use "" for DB_USER
define ("DB_PASSWORD", "");//use "" for DB_PASSWORD
define("DB_DATABASE", "test");//use "" for DB_DATABASE
define ("DB_HOST", "localhost");  //use "" for DB_HOST

$server = DB_HOST; $user = DB_USER; $pw = DB_PASSWORD; $db = DB_DATABASE; // $con = mysqli_connect($server,$user,$pw,$db);
$con=mysqli_connect($server,$user,$pw,$db) or die (mysqli_connect_error()); //remove ; and echo and add or for die()
if($con) { echo "success"; } else { echo "failed"; } ?>
</code>```

Title: Cannot connect to MySQL db, PHP

Body:
Hello I am trying to connect MySQL database using mircloud host service but it does not connect. I tried to connect locally using phpMyAdmin but still give me this error.  This is my connect code.

<?php
define (DB_USER, "root");
define (DB_PASSWORD, "gOJTkc7QSL");
define (DB_DATABASE, "rbkLastTask");
define (DB_HOST, "https://node42861-env-2276018.mircloud.host");
?>

<?php
$server = DB_HOST;
$user = DB_USER;
$pw = DB_PASSWORD;
$db = DB_DATABASE;
// $con = mysqli_connect($server,$user,$pw,$db);
$con=mysqli_connect($server,$user,$pw,$db);
Echo mysqli_connect_error();
if($con)
{
    echo "success";
}
else
{
    echo "failed";
}
?>

Body:
try this code

write this way  your code

<?php
define ("DB_USER", "root"); //use "" for DB_USER
define ("DB_PASSWORD", "");//use "" for DB_PASSWORD
define("DB_DATABASE", "test");//use "" for DB_DATABASE
define ("DB_HOST", "localhost");  //use "" for DB_HOST

$server = DB_HOST; $user = DB_USER; $pw = DB_PASSWORD; $db = DB_DATABASE; // $con = mysqli_connect($server,$user,$pw,$db);
$con=mysqli_connect($server,$user,$pw,$db) or die (mysqli_connect_error()); //remove ; and echo and add or for die()
if($con) { echo "success"; } else { echo "failed"; } ?>


问:
Correct way to populate 45k elements into attribute in React
I have 45k objects of cordinates in JSON format and I want to put them as markers in my map component.

I have the following code:

```<code>const MapWithMarkers = withGoogleMap(props =>GoogleMap
    defaultZoom={8}
    defaultCenter={{ lat: -34.397, lng: 150.644 }}
  >
    <Marker
      position={{ lat: -34.397, lng: 150.644 }}
    />
  </GoogleMap>
);

<MapWithAMarker
  containerElement={<div style={{ height: '400px' }} />}
  mapElement={<div style={{ height: '100%' }} />}
/>
</code>```

How can that be achieved in the most correct way?

Thanks for your time.

答:
Pass down the data as a prop into the map component, then in the map component, pick up the data from the props and .map over it and generate a marker for every entry.</p>

```<code><GoogleMap>

        {
            (props.markerData).map((marker, i) => {return <Marker key={i} position={{ lat: parseFloat(marker.lat), lng: parseFloat(marker.lng) }} />})
        }

</GoogleMap>
</code>```

Body:
I have 45k objects of cordinates in JSON format and I want to put them as markers in my map component.

I have the following code:

const MapWithMarkers = withGoogleMap(props =>GoogleMap
    defaultZoom={8}
    defaultCenter={{ lat: -34.397, lng: 150.644 }}
  >
    <Marker
      position={{ lat: -34.397, lng: 150.644 }}
    />
  </GoogleMap>
);

<MapWithAMarker
  containerElement={
}
  mapElement={
}
/>

How can that be achieved in the most correct way?

Thanks for your time.

Body:
Pass down the data as a prop into the map component, then in the map component, pick up the data from the props and .map over it and generate a marker for every entry.

<GoogleMap>

        {
            (props.markerData).map((marker, i) => {return <Marker key={i} position={{ lat: parseFloat(marker.lat), lng: parseFloat(marker.lng) }} />})
        }

</GoogleMap>


问:
How do I import an excel spreadsheet into SQL Server?
I need to import an excel spreadsheet into SQL Server 2005.  What steps would I need to take to accomplish that?</p>

答:
The "Data Transformation Services" wizards are your friend.

The instructions here assume SQL Server 2000

Open SQL Server Enterprise Manager

Right-click on the appropriate server

Select Import Data

Run through the wizard.

Click Next on the first screen

Choose "Microsoft Excel " as your datasource

Enter the path to the XLS file and click next.

Enter the connection details for your database and click next.

Depending on what you want to do with the data, you have a few options new. For one-off jobs I generally find it easiest to import all the excel data, then edit it in SQL Server, but if you're going to repeat this action on multiple files, you might want to craft a really sexy import script.

If you are going to run it again, you can save the DTS package using the wizard, then edit it in the "Data Transformation Services" section of Enterprise Manager. It's a good way to learn how DTS works.

OwnerDisplayName: Fiona

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Onorio Catenacci

OwnerDisplayName: RB

LastEditorDisplayName: RB


问:
Looking for a drop-in replacement for a java.util.Map

Problem

Following up on this question, it seems that a file- or disk-based Map implementation may be the right solution to the problems I mentioned there. Short version:

Right now, I have a Map implemented as a ConcurrentHashMap.

Entries are added to it continually, at a fairly fixed rate. Details on this later.

Eventually, no matter what, this means the JVM runs out of heap space.

At work, it was (strongly) suggested that I solve this problem using SQLite, but after asking that previous question, I don't think that a database is the right tool for this job. So - let me know if this sounds crazy - I think a better solution would be a Map stored on disk.

Bad idea: implement this myself. Better idea: use someone else's library! Which one?

Requirements

Must-haves:

Free.

Persistent. The data needs to stick around between JVM restarts.

Some sort of searchability. Yes, I need the ability to retrieve this darn data as well as put it away. Basic result set filtering is a plus.

Platform-independent. Needs to be production-deployable on Windows or Linux machines.

Purgeable. Disk space is finite, just like heap space. I need to get rid of entries that are n days old. It's not a big deal if I have to do this manually.

Nice-to-haves:

Easy to use. It would be great if I could get this working by the end of the week.

Better still: the end of the day. It would be really, really great if I could add one JAR to my classpath, change new ConcurrentHashMap<Foo, Bar>(); to new SomeDiskStoredMap<Foo, Bar>();

and be done.

Decent scalability and performance. Worst case: new entries are added (on average) 3 times per second, every second, all day long, every day. However, inserts won't always happen that smoothly. It might be (no inserts for an hour) then (insert 10,000 objects at once).

Possible Solutions

Ehcache? I've never used it before. It was a suggested solution to my previous question.

Berkeley DB? Again, I've never used it, and I really don't know anything about it.

Hadoop (and which subproject)? Haven't used it. Based on these docs, its cross-platform-readiness is ambiguous to me. I don't need distributed operation in the foreseeable future.

A SQLite JDBC driver after all?

???

Ehcache and Berkeley DB both look reasonable right now. Any particular recommendations in either direction?

答: We have a similar solution implemented using Xapian. It's fast, it's scalable, it provedes almost all search functionality you requested, it's free, multiplatform, and of course purgeable.</p>


问:
Pointers to NSMutableDictionary objects
I have a following sample code:

```<code>NSNumber * number1 = @231;
NSNumber * number2 = @322;
NSLog(@"number1: %@", number1);
NSLog(@"number2: %@", number2);
NSMutableDictionary* dict = [NSMutableDictionary new];
[dict setObject:number1 forKey:@"number"];
NSNumber * outNumber = [dict objectForKey:@"number"];
NSLog(@"outNumber: %@",outNumber);
[dict setObject:number2 forKey:@"number"];
NSLog(@"outNumber: %@",outNumber);
</code>```

After updating the value under "number" key in the dictionary the outNumber object still points to the previous value (231).

Is there a way in Objective-C to make it so that the outNumber object always points to the current value under "number" key in dictionary ?

答:
You have didn't print updated dictionary so, add below 2 line in your end of code:

```<code>NSNumber * outNumber2 = [dict objectForKey:@"number"];
NSLog(@"outNumber: %@",outNumber2);
</code>```

Hope will helpful to you!!

Title: Pointers to NSMutableDictionary objects

Body:
I have a following sample code:

NSNumber * number1 = @231;
NSNumber * number2 = @322;
NSLog(@"number1: %@", number1);
NSLog(@"number2: %@", number2);
NSMutableDictionary* dict = [NSMutableDictionary new];
[dict setObject:number1 forKey:@"number"];
NSNumber * outNumber = [dict objectForKey:@"number"];
NSLog(@"outNumber: %@",outNumber);
[dict setObject:number2 forKey:@"number"];
NSLog(@"outNumber: %@",outNumber);

After updating the value under "number" key in the dictionary the outNumber object still points to the previous value (231).

Is there a way in Objective-C to make it so that the outNumber object always points to the current value under "number" key in dictionary ?

Body:
You have didn't print updated dictionary so, add below 2 line in your end of code:

NSNumber * outNumber2 = [dict objectForKey:@"number"];
NSLog(@"outNumber: %@",outNumber2);

Hope will helpful to you!!


问:
Should I rely on transitive dependencies in Maven if they come from other sub-module of my parent?
Suppose we are working on mortgage sub-module, and we are directly using the Google Guava classes in module code, but the dependcy for the guava is defined in other sub-module under the same parent and we have access to Guava classes only by transitive dependency on "investment" module:

```<code>banking-system (parent pom.xml)
|
|-- investment (pom.xml defines <dependency>guava</dependency>)
|
|-- mortgage (pom.xml defiens <dependency>investment</dependency>)
</code>```

Should we still put a <dependency> to Guava in the mortgage pom.xml?

The cons looks like duplication in our pom.xml, the pros are: if someone developing "investment" will drop guava, then it will not stop our mortgage sub-module from being successfuly build.

If yes, then what <version> shoudle we specify? (none + <dependencyManagement> in parent pom?)

If yes, should we use a <provided> scope in some module then?

Note: Keep in mind, that I am asking in specific situation, when modules have common parent pom (e.g. being an application as whole).

Maybe this structure was not the best example, imagine:

```<code>banking-app
    banking-core (dep.on: guava, commons, spring)
    investment (dep.on: banking-core)
    mortgage (dep.on: banking-core)
</code>```

Should still Investment explicitly declare Spring when it use @Component, and declare Guava if it uses Guava's LoadedCache?

答:
When a module uses a 3rd party library, the module should explicitly depend on that library in its pom.xml too. Imagine if another project should use the 'mortgage' module, and doesn't depend on Guava already, it will fail e.g. when a unit test comes upon a code path that involves Guava. An explicit dependency also covers you against the scenario where you refactor the 'investment' module so that it doesn't use Guava anymore. Your 'investment' module should be agnostic to such changes in its dependencies.

It's always correct to explicitly list your direct dependencies. When it comes to version, it's best to keep that in the dependencyManagement section of your parent pom so all child projects inherit that (same) version.

Body:
Suppose we are working on mortgage sub-module, and we are directly using the Google Guava classes in module code, but the dependcy for the guava is defined in other sub-module under the same parent and we have access to Guava classes only by transitive dependency on "investment" module:

banking-system (parent pom.xml)
|
|-- investment (pom.xml defines <dependency>guava</dependency>)
|
|-- mortgage (pom.xml defiens <dependency>investment</dependency>)

Should we still put a <dependency> to Guava in the mortgage pom.xml?

The cons looks like duplication in our pom.xml, the pros are: if someone developing "investment" will drop guava, then it will not stop our mortgage sub-module from being successfuly build.

If yes, then what <version> shoudle we specify? (none + <dependencyManagement> in parent pom?)

If yes, should we use a <provided> scope in some module then?

Note: Keep in mind, that I am asking in specific situation, when modules have common parent pom (e.g. being an application as whole).

Maybe this structure was not the best example, imagine:

banking-app
    banking-core (dep.on: guava, commons, spring)
    investment (dep.on: banking-core)
    mortgage (dep.on: banking-core)

Should still Investment explicitly declare Spring when it use @Component, and declare Guava if it uses Guava's LoadedCache?


问:
absolute css not working as expected
I'm trying to apply absolute positioning on class car. I expect it to be placed in top-left corner inside rectangle. The current behavior is being placed in top-left corner of the page which I don't want. As far as I know absolute element must be positioned inside its ancestor.

body {
  padding: 25px;
}

.car {
  position: absolute;
}

#rectangle {
  /* display: inline-block;
            position: absolute;
            top: 150px;
            left:25px; */
  width: 3324px;
  height: 5112px;
  background-color: #00b3ee;
}

#intro {
  /* position: absolute;
            top: 800px;
            left:25px; */
  border: solid 1px;
  padding: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>

  <div id="intro">
    <p>
      Floor <b><i>{{ $title }}</i></b> setup successfully finished!
      Return to floors.
    </p>
  </div>

  <div id="rectangle">
    <img src="{{ url($map_image_path) }}">

      <img id="dynamic" src="http://localhost/ParkingMinis/public/images/icons/car/reza1.png">

  </div>

</body></code>```

答: Add position: relative to the #rectangle class. Absolute positioning is relative to the first positioned ancestor.

Title: absolute css not working as expected

Body:
I'm trying to apply absolute positioning on class car. I expect it to be placed in top-left corner inside rectangle. The current behavior is being placed in top-left corner of the page which I don't want. As far as I know absolute element must be positioned inside its ancestor.

body {
  padding: 25px;
}

.car {
  position: absolute;
}

#rectangle {
  /* display: inline-block;
            position: absolute;
            top: 150px;
            left:25px; */
  width: 3324px;
  height: 5112px;
  background-color: #00b3ee;
}

#intro {
  /* position: absolute;
            top: 800px;
            left:25px; */
  border: solid 1px;
  padding: 10px;
}

      Floor {{ $title }} setup successfully finished!
      Return to floors.


问:
Convert attribute from NSNumber to NSString in CoreData Entity - LightWeightMigration
I'm trying migrate NSNumber to NSString attribute using lightweight migration in objective C. Version 0

Version 2

I've changed the core data model current version to 2

Since it won't resolved in light weight migration I tried with CoreDataMapping Model and NSEntity migration policy like below.

Have created a subclass of NSEntityMigrationPolicy and tried the below code

```<code>@interface SampleMigrationV1toV2 : NSEntityMigrationPolicy

@end

#import "SampleMigrationV1toV2.h"

@implementation SampleMigrationV1toV2

- (BOOL)createDestinationInstancesForSourceInstance:(NSManagedObject *)sInstance entityMapping:(NSEntityMapping *)mapping manager:(NSMigrationManager *)manager error:(NSError **)error
{
    NSManagedObject *newObject = [NSEntityDescription insertNewObjectForEntityForName:[mapping destinationEntityName] inManagedObjectContext:[manager destinationContext]];

    // Copy all the values from sInstance into newObject, making sure to apply the conversion for the string to int when appropriate. So you should have one of these for each attribute:
    [newObject setValue:[sInstance valueForKey:@"number"] forKey:@"number"];

    [manager associateSourceInstance:sInstance withDestinationInstance:newObject forEntityMapping:mapping];
    return YES;
}
@end
</code>```

In persistent coordinator I've changed the NSInferMappingModelAutomaticallyOption to NO like below,

```<code>- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

    if (persistentStoreCoordinator != nil) {
        return persistentStoreCoordinator;
    }

    NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"CoreDataMigrationPolicty.sqlite"];

    NSURL *storeUrl = [NSURL fileURLWithPath:storePath];

    NSMutableDictionary *options = [[NSMutableDictionary alloc] init];
    [options setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
    [options setObject:[NSNumber numberWithBool:NO] forKey:NSInferMappingModelAutomaticallyOption];

    NSError *error = nil;
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error])
    {
        //NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return persistentStoreCoordinator;
}
</code>```

After doing all these thing I'm getting error like " Error Domain=NSCocoaErrorDomain Code=134110 "(null)" UserInfo={NSUnderlyingException=Couldn't create mapping policy for class named (CoreDataMigrationPolicty.SampleMigrationV1toV2)} with userInfo dictionary

Mapping model is not being created/called. Is it correct approach to change the attribute datatype in core data. Is there any other way to fix this issue without crash/reinstalling the app.

答:
Finally I found mistake what I did from this answer.
Core Data Migration: Attribute Mapping Value Expression

The problem is with the expression I mentioned in the mapping model attribute.
Syntax is FUNCTION($entityPolicy, "convertNumberToString:" , $source.number) and the function definition is like

```<code>#import "SampleMigrationV1toV2.h"

@implementation SampleMigrationV1toV2

-(NSString *)convertNumberToString:(NSNumber *)number{
    return  [number stringValue];
}
@end
</code>```

FUNCTION($entityPolicy, "convertNumberToString:" , $source.number) :

$entityPolicy get the corresponding MappingPolicy (i.e SampleMigrationV1toV2) as we mentioned in the EntityMapping "SampleToSample" and the function "convertNumberToString:" migrate the number to string by taking the input value $source.Number

Body:
I'm trying migrate NSNumber to NSString attribute using lightweight migration in objective C. Version 0

Version 2

I've changed the core data model current version to 2

Since it won't resolved in light weight migration I tried with CoreDataMapping Model and NSEntity migration policy like below.

Have created a subclass of NSEntityMigrationPolicy and tried the below code

@interface SampleMigrationV1toV2 : NSEntityMigrationPolicy

@end

#import "SampleMigrationV1toV2.h"

@implementation SampleMigrationV1toV2

- (BOOL)createDestinationInstancesForSourceInstance:(NSManagedObject *)sInstance entityMapping:(NSEntityMapping *)mapping manager:(NSMigrationManager *)manager error:(NSError **)error
{
    NSManagedObject *newObject = [NSEntityDescription insertNewObjectForEntityForName:[mapping destinationEntityName] inManagedObjectContext:[manager destinationContext]];

    // Copy all the values from sInstance into newObject, making sure to apply the conversion for the string to int when appropriate. So you should have one of these for each attribute:
    [newObject setValue:[sInstance valueForKey:@"number"] forKey:@"number"];

    [manager associateSourceInstance:sInstance withDestinationInstance:newObject forEntityMapping:mapping];
    return YES;
}
@end

In persistent coordinator I've changed the NSInferMappingModelAutomaticallyOption to NO like below,

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

    if (persistentStoreCoordinator != nil) {
        return persistentStoreCoordinator;
    }

    NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"CoreDataMigrationPolicty.sqlite"];

    NSURL *storeUrl = [NSURL fileURLWithPath:storePath];

    NSMutableDictionary *options = [[NSMutableDictionary alloc] init];
    [options setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
    [options setObject:[NSNumber numberWithBool:NO] forKey:NSInferMappingModelAutomaticallyOption];

    NSError *error = nil;
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error])
    {
        //NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return persistentStoreCoordinator;
}

After doing all these thing I'm getting error like " Error Domain=NSCocoaErrorDomain Code=134110 "(null)" UserInfo={NSUnderlyingException=Couldn't create mapping policy for class named (CoreDataMigrationPolicty.SampleMigrationV1toV2)} with userInfo dictionary

Mapping model is not being created/called. Is it correct approach to change the attribute datatype in core data. Is there any other way to fix this issue without crash/reinstalling the app.

Body:
Finally I found mistake what I did from this answer.
Core Data Migration: Attribute Mapping Value Expression

The problem is with the expression I mentioned in the mapping model attribute.
Syntax is FUNCTION($entityPolicy, "convertNumberToString:" , $source.number) and the function definition is like

#import "SampleMigrationV1toV2.h"

@implementation SampleMigrationV1toV2

-(NSString *)convertNumberToString:(NSNumber *)number{
    return  [number stringValue];
}
@end

FUNCTION($entityPolicy, "convertNumberToString:" , $source.number) :

$entityPolicy get the corresponding MappingPolicy (i.e SampleMigrationV1toV2) as we mentioned in the EntityMapping "SampleToSample" and the function "convertNumberToString:" migrate the number to string by taking the input value $source.Number


问:
Hide separtor line between navigationBar and Content
I would like to delete this junction (The line between the navigation bar and the ImageView Orange):

Is there someone who knows how to do?

答:
Add below lines in your viewWillAppear

```<code>self.navigationController?.navigationBar.shadowImage = UIImage()
</code>```

Body:
Add below lines in your viewWillAppear

self.navigationController?.navigationBar.shadowImage = UIImage()


问:
Group elements from an array with a new element containing group value
I have an array like this one:

```<code>$array = [
     ['Categoria' => 'example', 'Servico' => 'name1'],
     ['Categoria' => 'example', 'Servico' => 'name2'],
     ['Categoria' => 'example', 'Servico' => 'name3'],
     ['Categoria' => 'example2', 'Servico' => 'name4'],
     ['Categoria' => 'example2', 'Servico' => 'name5'],
     ['Categoria' => 'example2', 'Servico' => 'name6'],
     ['Categoria' => 'example3', 'Servico' => 'name7'],
     ['Categoria' => 'example3', 'Servico' => 'name8'],
     ['Categoria' => 'example3', 'Servico' => 'name9']
];
</code>```

I need to transform this on something like:

```<code>[
    [
        'Servico' => 'example',
        'children' => [
            ['Servico' => 'name1'],
            ['Servico' => 'name2'],
            ['Servico' => 'name3'],
        ]
    ],
    [
        'Servico' => 'example2',
        'children' => [
            ['Servico' => 'name4'],
            ['Servico' => 'name5'],
            ['Servico' => 'name6'],
        ]
    ],
    [
        'Servico' => 'example3',
        'children' => [
            ['Servico' => 'name7'],
            ['Servico' => 'name8'],
            ['Servico' => 'name9'],
        ]
    ],
]
</code>```

I have read this topic and I successfully have grouped my array, but I couldn't find a way to format the array in a way I have Servico and children on each object.

Someone have any ideas?

答:
just assume $array is your array</p>

```<code>$i=0;
$temp = array();
foreach ($array as $arr)
{
    if($i !=0 && $arr['Categoria'] == $temp[$i-1]['Servico']){
        $temp[$i-1]['children']['Servico'] = $arr['Servico'];
    }else{
        $temp[$i]['Servico'] =$arr['Categoria'];
        $temp[$i]['children']['Servico'] = $arr['Servico'];
        $i++;
    }
}
//$temp is your new array
</code>```

Body:
I have an array like this one:

$array = [
     ['Categoria' => 'example', 'Servico' => 'name1'],
     ['Categoria' => 'example', 'Servico' => 'name2'],
     ['Categoria' => 'example', 'Servico' => 'name3'],
     ['Categoria' => 'example2', 'Servico' => 'name4'],
     ['Categoria' => 'example2', 'Servico' => 'name5'],
     ['Categoria' => 'example2', 'Servico' => 'name6'],
     ['Categoria' => 'example3', 'Servico' => 'name7'],
     ['Categoria' => 'example3', 'Servico' => 'name8'],
     ['Categoria' => 'example3', 'Servico' => 'name9']
];

I need to transform this on something like:

[
    [
        'Servico' => 'example',
        'children' => [
            ['Servico' => 'name1'],
            ['Servico' => 'name2'],
            ['Servico' => 'name3'],
        ]
    ],
    [
        'Servico' => 'example2',
        'children' => [
            ['Servico' => 'name4'],
            ['Servico' => 'name5'],
            ['Servico' => 'name6'],
        ]
    ],
    [
        'Servico' => 'example3',
        'children' => [
            ['Servico' => 'name7'],
            ['Servico' => 'name8'],
            ['Servico' => 'name9'],
        ]
    ],
]

I have read this topic and I successfully have grouped my array, but I couldn't find a way to format the array in a way I have Servico and children on each object.

Someone have any ideas?

Body:
just assume $array is your array

$i=0;
$temp = array();
foreach ($array as $arr)
{
    if($i !=0 && $arr['Categoria'] == $temp[$i-1]['Servico']){
        $temp[$i-1]['children']['Servico'] = $arr['Servico'];
    }else{
        $temp[$i]['Servico'] =$arr['Categoria'];
        $temp[$i]['children']['Servico'] = $arr['Servico'];
        $i++;
    }
}
//$temp is your new array


问:
How to make the calendar event text editable on click?
I'm trying to implement this calendar plugin

http://jsfiddle.net/minusplus/7a7gG/2/

What I can't figure out is how to make the calendar event text editable when it is clicked.

Looking through the documentation for the plugin, I can't find a method to call to edit the event text. The only example that shows how to set the text is upon initialization using a title indicator (to set it below to "Lunch with Mike"):

```<code>var eventData = {
    events : [
       {"id":1,
       "start": new Date(year, month, day, 12),
       "end": new Date(year, month, day, 13, 35),
       "title":"Lunch with Mike"},
    ]
};
</code>```

答:
Using the event eventClick you need to edit the data to store whatever value for the eventData.events.title you want, and then render it again, $(”#calendar”).weekCalendar(”today”);

I have never used this plugin, but this is what it looks like you need to do based on how I read the documentation.

Body:
I'm trying to implement this calendar plugin

http://jsfiddle.net/minusplus/7a7gG/2/

What I can't figure out is how to make the calendar event text editable when it is clicked.

Looking through the documentation for the plugin, I can't find a method to call to edit the event text. The only example that shows how to set the text is upon initialization using a title indicator (to set it below to "Lunch with Mike"):

var eventData = {
    events : [
       {"id":1,
       "start": new Date(year, month, day, 12),
       "end": new Date(year, month, day, 13, 35),
       "title":"Lunch with Mike"},
    ]
};