问:
DateTime that comes from a GET request uses different format than the one that comes from POST
the DateTime that comes from POST is binded correctly (according to my computer's format)

but DateTime values that come from GET doesn't bind correctly, it is using a different format

```<code>my format is dd.MM.yyyy, in GET it uses MM.dd.yyyy instead

I don't have this problem if I use the en-US format  (which is MM/dd/yyyy)
</code>```

anybody knows how to fix this?

is this a mvc bug ? (it doesn't consider Culture when binding get requests)

答:
No, it seems it isn't a bug. You can get more details here: MVC DateTime binding with incorrect date format

I've been using the following ModelBinder to solve that problem.

```<code>public class CurrentCultureDateTimeBinder : IModelBinder
{
    private const string PARSE_ERROR = "\"{0}\" is not a valid date";
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (valueProviderResult == null) return null;

        var date = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue;

        if (String.IsNullOrEmpty(date))
            return null;

        bindingContext.ModelState.SetModelValue(bindingContext.ModelName, bindingContext.ValueProvider.GetValue(bindingContext.ModelName));

        try
        {
            return DateTime.Parse(date);
        }
        catch (Exception)
        {
            bindingContext.ModelState.AddModelError(bindingContext.ModelName, String.Format(PARSE_ERROR, bindingContext.ModelName));
            return null;
        }
    }
}
</code>```

Hope it helps.

Body:
the DateTime that comes from POST is binded correctly (according to my computer's format)

but DateTime values that come from GET doesn't bind correctly, it is using a different format

my format is dd.MM.yyyy, in GET it uses MM.dd.yyyy instead

I don't have this problem if I use the en-US format  (which is MM/dd/yyyy)

anybody knows how to fix this?

is this a mvc bug ? (it doesn't consider Culture when binding get requests)

Body:
No, it seems it isn't a bug. You can get more details here: MVC DateTime binding with incorrect date format

I've been using the following ModelBinder to solve that problem.

public class CurrentCultureDateTimeBinder : IModelBinder
{
    private const string PARSE_ERROR = "\"{0}\" is not a valid date";
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (valueProviderResult == null) return null;

        var date = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue;

        if (String.IsNullOrEmpty(date))
            return null;

        bindingContext.ModelState.SetModelValue(bindingContext.ModelName, bindingContext.ValueProvider.GetValue(bindingContext.ModelName));

        try
        {
            return DateTime.Parse(date);
        }
        catch (Exception)
        {
            bindingContext.ModelState.AddModelError(bindingContext.ModelName, String.Format(PARSE_ERROR, bindingContext.ModelName));
            return null;
        }
    }
}

Hope it helps.


来源: stackexchange

问:
Binding: Value not shown in Textbox
I created a textbox bound to an property object of the viewmodel like this:

```<code><TextBox x:Name="tbAmount" Text="{Binding Receipt.Amount}" Grid.Column="0"/>
</code>```

which worked fine until now. Now the textbox stays empty.

Changing it to

```<code><TextBox x:Name="tbAmount" Text="{Binding Receipt.Amount, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, diag:PresentationTraceSources.TraceLevel=High}" Grid.Column="0"/>
</code>```

didn't help.

The code behind of the control looks like this

```<code>using System.Windows.Controls;
using System.Windows.Data;
using ViewModel.Receipts;

namespace tegControls
{

    public partial class Receipt : UserControl
    {
        public Receipt()
        {
            InitializeComponent();
        }

        public vmReceipt vmEr;

        private int id;

        public int Id
        {
            get { return id; }
            set
            {
                id = value;
                vmEr = new vmReceipt(id);
                this.DataContext = vmEr;

            }
        }

    }
}
</code>```

The control is initialized with the following line (hosting app is in vb.net)

```<code>Receipt1 = New tegControls.Receipt()
Receipt1.ID = int_ID
</code>```

The model class for receipt looks like this:

```<code>public class Receipt : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(PropertyChangedEventArgs propertyChangedEventArgs)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyChangedEventArgs.PropertyName));
        System.Diagnostics.Debug.Print("Receipt: {0}", propertyChangedEventArgs.PropertyName);
    }

    private int id;

    public int Id
    {
        get { return id; }
        set { id = value; OnPropertyChanged(new PropertyChangedEventArgs("Id")); }
    }

    public Single Amount
    {
        get { return Amount; }
        set
        {
            Amount = value;
            OnPropertyChanged(new PropertyChangedEventArgs("Amount"));
        }
    }

}
</code>```

And this is the viewmodel class which serves as datacontext for the xmal control

```<code>using System.Collections.ObjectModel;
using System.ComponentModel;
using Model;

namespace ViewModel.Receipts
{
    public class vmReceipt : Receipt, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(PropertyChangedEventArgs propertyChangedEventArgs)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyChangedEventArgs.PropertyName));
        }

        public vmReceipt()
        {
            base.PropertyChanged += VmReceipt_PropertyChanged;
        }

        private void VmReceipt_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {

            if (e.PropertyName == "Id")
            {
                Amount = 293.85F;
            }
        }

    }
}
</code>```

The output messages show the following:

```<code>System.Windows.Data Warning: 56 : Created BindingExpression (hash=39565849) for Binding (hash=50005411)
System.Windows.Data Warning: 58 :   Path: 'Receipt.Amount'
System.Windows.Data Warning: 62 : BindingExpression (hash=39565849): Attach to System.Windows.Controls.TextBox.Text (hash=29985742)
System.Windows.Data Warning: 67 : BindingExpression (hash=39565849): Resolving source
System.Windows.Data Warning: 70 : BindingExpression (hash=39565849): Found data context element: TextBox (hash=29985742) (OK)
System.Windows.Data Warning: 78 : BindingExpression (hash=39565849): Activate with root item vmReceipt (hash=4309405)
System.Windows.Data Warning: 107 : BindingExpression (hash=39565849):   At level 0 using cached accessor for vmReceipt.Receipt: RuntimePropertyInfo(Receipt)
System.Windows.Data Warning: 104 : BindingExpression (hash=39565849): Replace item at level 0 with vmReceipt (hash=4309405), using accessor RuntimePropertyInfo(Receipt)
System.Windows.Data Warning: 101 : BindingExpression (hash=39565849): GetValue at level 0 from vmReceipt (hash=4309405) using RuntimePropertyInfo(Receipt): <null>
System.Windows.Data Warning: 106 : BindingExpression (hash=39565849):   Item at level 1 is null - no accessor
System.Windows.Data Warning: 80 : BindingExpression (hash=39565849): TransferValue - got raw value {DependencyProperty.UnsetValue}
System.Windows.Data Warning: 88 : BindingExpression (hash=39565849): TransferValue - using fallback/default value ''
System.Windows.Data Warning: 89 : BindingExpression (hash=39565849): TransferValue - using final value ''
System.Windows.Data Warning: 56 : Created BindingExpression (hash=31936960) for Binding (hash=23337408)
System.Windows.Data Warning: 58 :   Path: 'Receipt.Amount'
System.Windows.Data Warning: 62 : BindingExpression (hash=31936960): Attach to System.Windows.Controls.TextBox.Text (hash=57648048)
System.Windows.Data Warning: 67 : BindingExpression (hash=31936960): Resolving source
System.Windows.Data Warning: 70 : BindingExpression (hash=31936960): Found data context element: TextBox (hash=57648048) (OK)
System.Windows.Data Warning: 78 : BindingExpression (hash=31936960): Activate with root item vmReceipt (hash=59679756)
System.Windows.Data Warning: 107 : BindingExpression (hash=31936960):   At level 0 using cached accessor for vmReceipt.Receipt: RuntimePropertyInfo(Receipt)
System.Windows.Data Warning: 104 : BindingExpression (hash=31936960): Replace item at level 0 with vmReceipt (hash=59679756), using accessor RuntimePropertyInfo(Receipt)
System.Windows.Data Warning: 101 : BindingExpression (hash=31936960): GetValue at level 0 from vmReceipt (hash=59679756) using RuntimePropertyInfo(Receipt): <null>
System.Windows.Data Warning: 106 : BindingExpression (hash=31936960):   Item at level 1 is null - no accessor
System.Windows.Data Warning: 80 : BindingExpression (hash=31936960): TransferValue - got raw value {DependencyProperty.UnsetValue}
System.Windows.Data Warning: 88 : BindingExpression (hash=31936960): TransferValue - using fallback/default value ''
System.Windows.Data Warning: 89 : BindingExpression (hash=31936960): TransferValue - using final value ''
System.Windows.Data Warning: 96 : BindingExpression (hash=31936960): Got PropertyChanged event from TextBox (hash=57648048) for DataContext
System.Windows.Data Warning: 79 : BindingExpression (hash=31936960): Deactivate
System.Windows.Data Warning: 103 : BindingExpression (hash=31936960): Replace item at level 0 with {NullDataItem}
System.Windows.Data Warning: 103 : BindingExpression (hash=31936960): Replace item at level 1 with {NullDataItem}
System.Windows.Data Warning: 78 : BindingExpression (hash=31936960): Activate with root item vmReceipt (hash=3436318)
System.Windows.Data Warning: 107 : BindingExpression (hash=31936960):   At level 0 using cached accessor for vmReceipt.Receipt: RuntimePropertyInfo(Receipt)
System.Windows.Data Warning: 104 : BindingExpression (hash=31936960): Replace item at level 0 with vmReceipt (hash=3436318), using accessor RuntimePropertyInfo(Receipt)
System.Windows.Data Warning: 101 : BindingExpression (hash=31936960): GetValue at level 0 from vmReceipt (hash=3436318) using RuntimePropertyInfo(Receipt): Receipt (hash=288552)
System.Windows.Data Warning: 107 : BindingExpression (hash=31936960):   At level 1 using cached accessor for Receipt.Amount: RuntimePropertyInfo(Amount)
System.Windows.Data Warning: 104 : BindingExpression (hash=31936960): Replace item at level 1 with Receipt (hash=288552), using accessor RuntimePropertyInfo(Amount)
System.Windows.Data Warning: 101 : BindingExpression (hash=31936960): GetValue at level 1 from Receipt (hash=288552) using RuntimePropertyInfo(Amount): '293.85'
System.Windows.Data Warning: 80 : BindingExpression (hash=31936960): TransferValue - got raw value '293.85'
System.Windows.Data Warning: 84 : BindingExpression (hash=31936960): TransferValue - implicit converter produced '293,85'
System.Windows.Data Warning: 89 : BindingExpression (hash=31936960): TransferValue - using final value '293,85'
</code>```

Since the value (293,85) is shown in the output window (i.e. trace information) but not displayed in the textbox itself, I can't figure out, where to go from here?

答:
You simply activated the TraceLevel at high level for your binding with the following specification

```<code>, diag:PresentationTraceSources.TraceLevel=High}
</code>```

so it is showing a very detailed output for the events setting a value to the TextBox, just as expected.

Edit

After you edited the question, I'd suggest you don't set the DataContext more than once, so a possible change could be to set the DataContext in the c.tor

```<code>    public Receipt()
    {
        InitializeComponent();
        vmEr = new vmReceipt(id);
        this.DataContext = vmEr;
    }
</code>```

and then only update a property.

```<code>    public int Id
    {
        get { return id; }
        set
        {
            id = value;
            vmEr.ID = id;
        }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Binding: Value not shown in Textbox

Body:
I created a textbox bound to an property object of the viewmodel like this:

<TextBox x:Name="tbAmount" Text="{Binding Receipt.Amount}" Grid.Column="0"/>

which worked fine until now. Now the textbox stays empty.

Changing it to

<TextBox x:Name="tbAmount" Text="{Binding Receipt.Amount, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, diag:PresentationTraceSources.TraceLevel=High}" Grid.Column="0"/>

didn't help.

The code behind of the control looks like this

using System.Windows.Controls;
using System.Windows.Data;
using ViewModel.Receipts;

namespace tegControls
{

    public partial class Receipt : UserControl
    {
        public Receipt()
        {
            InitializeComponent();
        }

        public vmReceipt vmEr;

        private int id;

        public int Id
        {
            get { return id; }
            set
            {
                id = value;
                vmEr = new vmReceipt(id);
                this.DataContext = vmEr;

            }
        }

    }
}

The control is initialized with the following line (hosting app is in vb.net)

Receipt1 = New tegControls.Receipt()
Receipt1.ID = int_ID

The model class for receipt looks like this:

public class Receipt : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(PropertyChangedEventArgs propertyChangedEventArgs)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyChangedEventArgs.PropertyName));
        System.Diagnostics.Debug.Print("Receipt: {0}", propertyChangedEventArgs.PropertyName);
    }

    private int id;

    public int Id
    {
        get { return id; }
        set { id = value; OnPropertyChanged(new PropertyChangedEventArgs("Id")); }
    }

    public Single Amount
    {
        get { return Amount; }
        set
        {
            Amount = value;
            OnPropertyChanged(new PropertyChangedEventArgs("Amount"));
        }
    }

}

And this is the viewmodel class which serves as datacontext for the xmal control

using System.Collections.ObjectModel;
using System.ComponentModel;
using Model;

namespace ViewModel.Receipts
{
    public class vmReceipt : Receipt, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(PropertyChangedEventArgs propertyChangedEventArgs)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyChangedEventArgs.PropertyName));
        }

        public vmReceipt()
        {
            base.PropertyChanged += VmReceipt_PropertyChanged;
        }

        private void VmReceipt_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {

            if (e.PropertyName == "Id")
            {
                Amount = 293.85F;
            }
        }

    }
}

The output messages show the following:

System.Windows.Data Warning: 56 : Created BindingExpression (hash=39565849) for Binding (hash=50005411)
System.Windows.Data Warning: 58 :   Path: 'Receipt.Amount'
System.Windows.Data Warning: 62 : BindingExpression (hash=39565849): Attach to System.Windows.Controls.TextBox.Text (hash=29985742)
System.Windows.Data Warning: 67 : BindingExpression (hash=39565849): Resolving source
System.Windows.Data Warning: 70 : BindingExpression (hash=39565849): Found data context element: TextBox (hash=29985742) (OK)
System.Windows.Data Warning: 78 : BindingExpression (hash=39565849): Activate with root item vmReceipt (hash=4309405)
System.Windows.Data Warning: 107 : BindingExpression (hash=39565849):   At level 0 using cached accessor for vmReceipt.Receipt: RuntimePropertyInfo(Receipt)
System.Windows.Data Warning: 104 : BindingExpression (hash=39565849): Replace item at level 0 with vmReceipt (hash=4309405), using accessor RuntimePropertyInfo(Receipt)
System.Windows.Data Warning: 101 : BindingExpression (hash=39565849): GetValue at level 0 from vmReceipt (hash=4309405) using RuntimePropertyInfo(Receipt): <null>
System.Windows.Data Warning: 106 : BindingExpression (hash=39565849):   Item at level 1 is null - no accessor
System.Windows.Data Warning: 80 : BindingExpression (hash=39565849): TransferValue - got raw value {DependencyProperty.UnsetValue}
System.Windows.Data Warning: 88 : BindingExpression (hash=39565849): TransferValue - using fallback/default value ''
System.Windows.Data Warning: 89 : BindingExpression (hash=39565849): TransferValue - using final value ''
System.Windows.Data Warning: 56 : Created BindingExpression (hash=31936960) for Binding (hash=23337408)
System.Windows.Data Warning: 58 :   Path: 'Receipt.Amount'
System.Windows.Data Warning: 62 : BindingExpression (hash=31936960): Attach to System.Windows.Controls.TextBox.Text (hash=57648048)
System.Windows.Data Warning: 67 : BindingExpression (hash=31936960): Resolving source
System.Windows.Data Warning: 70 : BindingExpression (hash=31936960): Found data context element: TextBox (hash=57648048) (OK)
System.Windows.Data Warning: 78 : BindingExpression (hash=31936960): Activate with root item vmReceipt (hash=59679756)
System.Windows.Data Warning: 107 : BindingExpression (hash=31936960):   At level 0 using cached accessor for vmReceipt.Receipt: RuntimePropertyInfo(Receipt)
System.Windows.Data Warning: 104 : BindingExpression (hash=31936960): Replace item at level 0 with vmReceipt (hash=59679756), using accessor RuntimePropertyInfo(Receipt)
System.Windows.Data Warning: 101 : BindingExpression (hash=31936960): GetValue at level 0 from vmReceipt (hash=59679756) using RuntimePropertyInfo(Receipt): <null>
System.Windows.Data Warning: 106 : BindingExpression (hash=31936960):   Item at level 1 is null - no accessor
System.Windows.Data Warning: 80 : BindingExpression (hash=31936960): TransferValue - got raw value {DependencyProperty.UnsetValue}
System.Windows.Data Warning: 88 : BindingExpression (hash=31936960): TransferValue - using fallback/default value ''
System.Windows.Data Warning: 89 : BindingExpression (hash=31936960): TransferValue - using final value ''
System.Windows.Data Warning: 96 : BindingExpression (hash=31936960): Got PropertyChanged event from TextBox (hash=57648048) for DataContext
System.Windows.Data Warning: 79 : BindingExpression (hash=31936960): Deactivate
System.Windows.Data Warning: 103 : BindingExpression (hash=31936960): Replace item at level 0 with {NullDataItem}
System.Windows.Data Warning: 103 : BindingExpression (hash=31936960): Replace item at level 1 with {NullDataItem}
System.Windows.Data Warning: 78 : BindingExpression (hash=31936960): Activate with root item vmReceipt (hash=3436318)
System.Windows.Data Warning: 107 : BindingExpression (hash=31936960):   At level 0 using cached accessor for vmReceipt.Receipt: RuntimePropertyInfo(Receipt)
System.Windows.Data Warning: 104 : BindingExpression (hash=31936960): Replace item at level 0 with vmReceipt (hash=3436318), using accessor RuntimePropertyInfo(Receipt)
System.Windows.Data Warning: 101 : BindingExpression (hash=31936960): GetValue at level 0 from vmReceipt (hash=3436318) using RuntimePropertyInfo(Receipt): Receipt (hash=288552)
System.Windows.Data Warning: 107 : BindingExpression (hash=31936960):   At level 1 using cached accessor for Receipt.Amount: RuntimePropertyInfo(Amount)
System.Windows.Data Warning: 104 : BindingExpression (hash=31936960): Replace item at level 1 with Receipt (hash=288552), using accessor RuntimePropertyInfo(Amount)
System.Windows.Data Warning: 101 : BindingExpression (hash=31936960): GetValue at level 1 from Receipt (hash=288552) using RuntimePropertyInfo(Amount): '293.85'
System.Windows.Data Warning: 80 : BindingExpression (hash=31936960): TransferValue - got raw value '293.85'
System.Windows.Data Warning: 84 : BindingExpression (hash=31936960): TransferValue - implicit converter produced '293,85'
System.Windows.Data Warning: 89 : BindingExpression (hash=31936960): TransferValue - using final value '293,85'

Since the value (293,85) is shown in the output window (i.e. trace information) but not displayed in the textbox itself, I can't figure out, where to go from here?

Body:
You simply activated the TraceLevel at high level for your binding with the following specification

, diag:PresentationTraceSources.TraceLevel=High}

so it is showing a very detailed output for the events setting a value to the TextBox, just as expected.

Edit

After you edited the question, I'd suggest you don't set the DataContext more than once, so a possible change could be to set the DataContext in the c.tor

    public Receipt()
    {
        InitializeComponent();
        vmEr = new vmReceipt(id);
        this.DataContext = vmEr;
    }

and then only update a property.

    public int Id
    {
        get { return id; }
        set
        {
            id = value;
            vmEr.ID = id;
        }
    }


问:
Python OrderedDict iterable over int
I'm learning about dictionaries and I wrote a small bit of code and built it.

```<code>from collections import OrderedDict

d1 = OrderedDict([('a',0),('b',9),('c',8),('d',7),('e',6)])
d2 = OrderedDict([(1),(2),(3),(4),(5)])
</code>```

I get the following error:

```<code>d2 = OrderedDict([(1),(2),(3),(4),(5)])
TypeError: 'int' object is not iterable
</code>```

I don't understand why it isn't iterable? And what has 'int' got to do with the problem?

Thanks

答:
OrderedDicts (or any sub-class of dict for that matter) are a set of key-value pairs.

```<code>>>> d1 = OrderedDict([('a',0),('b',9),('c',8),('d',7),('e',6)])
>>> d1['b']
9
</code>```

The following statement does not provide any such pairs.

```<code>d2 = OrderedDict([(1),(2),(3),(4),(5)])
</code>```

Also note that
(1) is an int.

(1,) is a tuple.

Title: Python OrderedDict iterable over int

Body:
I'm learning about dictionaries and I wrote a small bit of code and built it.

from collections import OrderedDict

d1 = OrderedDict([('a',0),('b',9),('c',8),('d',7),('e',6)])
d2 = OrderedDict([(1),(2),(3),(4),(5)])

I get the following error:

d2 = OrderedDict([(1),(2),(3),(4),(5)])
TypeError: 'int' object is not iterable

I don't understand why it isn't iterable? And what has 'int' got to do with the problem?

Thanks

Body:
OrderedDicts (or any sub-class of dict for that matter) are a set of key-value pairs.

>>> d1 = OrderedDict([('a',0),('b',9),('c',8),('d',7),('e',6)])
>>> d1['b']
9

The following statement does not provide any such pairs.

d2 = OrderedDict([(1),(2),(3),(4),(5)])

Also note that
(1) is an int.

(1,) is a tuple.


问:
ASP.NET Core - Viewing data error
I have problem in viewing my data.

What I am trying to achieve in my page is that I place all of them in 1 view for viewing data, and CRUD operation using bootstrap.

I received this kind of error:

Also, it was suggested that I should use new() since it stated that I should create a new instance but I don't know where to place it. I tried to put it in my model like public lstEmployee = new IEnumerable<Employee> { get; set; } and it seems to not be working at all.

This is my code:

Model:

```<code>using PEMCOLoan.DAL.Entities.Models;
namespace prjPEMCOLoan.Models
{
    public class ModelEmployee
    {
        public IEnumerable<Employee> lstEmployee { get; set; }
        public Employee employees { get; set; }
    }
}
</code>```

View:

@model prjPEMCOLoan.Models.ModelEmployee

@{
    ViewBag.Title = "List of Employees";
}
<form class="navbar-form navbar-right" style="margin-bottom: 10px;">

        <input type="text" class="form-control" placeholder="Search">

    <button type="submit" class="btn btn-default">Submit</button>
</form>

List of Employees

    <button type="button" class="btn btn-info btn-sm openAdd" data-toggle="modal" data-target="#myModal2"> Add</button>

        ID Employee
        Full Name
        Contact Number
        Position
        Action

    @foreach (var item in Model.lstEmployee)
    {

            @Html.DisplayFor(modelItem => item.EmployeeId)
            @Html.DisplayFor(modelItem => item.Fname)  @Html.DisplayFor(modelItem => item.Lname)
            @Html.DisplayFor(modelItem => item.PhoneNumber)
            @Html.DisplayFor(modelItem => item.Position)

                 Details
                <button type="button" class="btn btn-warning btn-sm openEdit" data-toggle="modal" data-target="#myModal" data-emp-id="@item.EmployeeId"> Edit</button>
                <button type="button" class="btn btn-danger btn-sm openDiag" data-toggle="modal" data-target="#myModal" data-emp-id="@item.EmployeeId"> Delete</button>

    }

```
</div>
</div>
</p>

<p>Controller:</p>

```[HttpGet]
public async Task<IActionResult> Index()
{
    var getAllEmployees = await _Context.Employee.ToListAsync();
    return View(getAllEmployees);
}
```

答:
Create a ViewModel:

```<code>public class EmployeeViewModel
{
    public List<Employee> Employees { get; set; }
}
</code>```

Your ViewModel will have to be:

```<code>@model EmployeeViewModel
</code>```

In your action you need to create the ViewModel and pass it to the view like:

```<code>[HttpGet]
public async Task<IActionResult> Index()
{
    var AllEmployees = await _Context.Employee.ToListAsync();

    var model = new EmployeeViewModel();
    model.Employees = AllEmployees;

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

Also edit the view to match the new ViewModel:

```<code>@foreach (var item in Model.Employees)
{
    <tr>
        <td>@Html.DisplayFor(modelItem => item.EmployeeId)</td>
        <td>@Html.DisplayFor(modelItem => item.Fname)  @Html.DisplayFor(modelItem => item.Lname)</td>
        <td>@Html.DisplayFor(modelItem => item.PhoneNumber)</td>
        <td>@Html.DisplayFor(modelItem => item.Position)</td>
        <td>
            <a class="btn btn-primary btn-sm" asp-controller="Employee" asp-action="Details" asp-route-id="@item.EmployeeId"><span class="glyphicon glyphicon-dashboard" style="vertical-align:middle;margin-top: -5px"></span> Details</a>
            <button type="button" class="btn btn-warning btn-sm openEdit" data-toggle="modal" data-target="#myModal" data-emp-id="@item.EmployeeId"><span class="glyphicon glyphicon-edit" style="vertical-align:middle;margin-top: -5px"></span> Edit</button>
            <button type="button" class="btn btn-danger btn-sm openDiag" data-toggle="modal" data-target="#myModal" data-emp-id="@item.EmployeeId"><span class="glyphicon glyphicon-trash" style="vertical-align:middle;margin-top: -5px"></span> Delete</button>
        </td>
    </tr>

}
</code>```

Title: ASP.NET Core - Viewing data error

Body:
I have problem in viewing my data.

What I am trying to achieve in my page is that I place all of them in 1 view for viewing data, and CRUD operation using bootstrap.

I received this kind of error:

Also, it was suggested that I should use new() since it stated that I should create a new instance but I don't know where to place it. I tried to put it in my model like public lstEmployee = new IEnumerable<Employee> { get; set; } and it seems to not be working at all.

This is my code:

Model:

using PEMCOLoan.DAL.Entities.Models;
namespace prjPEMCOLoan.Models
{
    public class ModelEmployee
    {
        public IEnumerable<Employee> lstEmployee { get; set; }
        public Employee employees { get; set; }
    }
}

View:

@model prjPEMCOLoan.Models.ModelEmployee

@{
    ViewBag.Title = "List of Employees";
}
<form class="navbar-form navbar-right" style="margin-bottom: 10px;">

        <input type="text" class="form-control" placeholder="Search">

    <button type="submit" class="btn btn-default">Submit</button>
</form>

List of Employees

    <button type="button" class="btn btn-info btn-sm openAdd" data-toggle="modal" data-target="#myModal2"> Add</button>

        ID Employee
        Full Name
        Contact Number
        Position
        Action

    @foreach (var item in Model.lstEmployee)
    {

            @Html.DisplayFor(modelItem => item.EmployeeId)
            @Html.DisplayFor(modelItem => item.Fname)  @Html.DisplayFor(modelItem => item.Lname)
            @Html.DisplayFor(modelItem => item.PhoneNumber)
            @Html.DisplayFor(modelItem => item.Position)

                 Details
                <button type="button" class="btn btn-warning btn-sm openEdit" data-toggle="modal" data-target="#myModal" data-emp-id="@item.EmployeeId"> Edit</button>
                <button type="button" class="btn btn-danger btn-sm openDiag" data-toggle="modal" data-target="#myModal" data-emp-id="@item.EmployeeId"> Delete</button>

    }

Controller:

[HttpGet]
public async Task<IActionResult> Index()
{
    var getAllEmployees = await _Context.Employee.ToListAsync();
    return View(getAllEmployees);
}

Body:
Create a ViewModel:

public class EmployeeViewModel
{
    public List<Employee> Employees { get; set; }
}

Your ViewModel will have to be:

@model EmployeeViewModel

In your action you need to create the ViewModel and pass it to the view like:

[HttpGet]
public async Task<IActionResult> Index()
{
    var AllEmployees = await _Context.Employee.ToListAsync();

    var model = new EmployeeViewModel();
    model.Employees = AllEmployees;

    return View(model);
}

Also edit the view to match the new ViewModel:

@foreach (var item in Model.Employees)
{
    <tr>
        <td>@Html.DisplayFor(modelItem => item.EmployeeId)</td>
        <td>@Html.DisplayFor(modelItem => item.Fname)  @Html.DisplayFor(modelItem => item.Lname)</td>
        <td>@Html.DisplayFor(modelItem => item.PhoneNumber)</td>
        <td>@Html.DisplayFor(modelItem => item.Position)</td>
        <td>
            <a class="btn btn-primary btn-sm" asp-controller="Employee" asp-action="Details" asp-route-id="@item.EmployeeId"><span class="glyphicon glyphicon-dashboard" style="vertical-align:middle;margin-top: -5px"></span> Details</a>
            <button type="button" class="btn btn-warning btn-sm openEdit" data-toggle="modal" data-target="#myModal" data-emp-id="@item.EmployeeId"><span class="glyphicon glyphicon-edit" style="vertical-align:middle;margin-top: -5px"></span> Edit</button>
            <button type="button" class="btn btn-danger btn-sm openDiag" data-toggle="modal" data-target="#myModal" data-emp-id="@item.EmployeeId"><span class="glyphicon glyphicon-trash" style="vertical-align:middle;margin-top: -5px"></span> Delete</button>
        </td>
    </tr>

}


问:
SimpleCursorAdapter within a ScrollView
I'm having  abit of an issue and i'm not too sure how to go about solving it.

Essentially i have an activity which has a base xml layout of ScrollView and i want this activity to list some results from a Cursor. So i thought i'd use SimpleCursorAdapter... however when i got it all set up it appears that the ListView that the SimpleCursorAdapter goes into doesn't play nice being within another scrollable layout element.

I've sorta got it working programmically but i'd much rather use a ListAdapter as it will make each list entry look like a button and keep it inline with the design of the rest of the application and can handle the ids of each item and where to send the user upon clicking.

So my question is this: is there anyway to either make ListView show all the items such that it never needs to scroll, or can i change the ListView to something like a LinearLayout?

I hope that makes sense!
Any help / insight / ideas are welcome!
Cheers!

答:
I agree with Shardul; trying to put a listview with a scrollview will make it impossible to scroll. Have a look at the links below to see what you can accomplish with just a ListView -
a.

custom backgrounds info.
custom adapters

ContentLicense: CC BY-SA 2.5

Title: SimpleCursorAdapter within a ScrollView


问:
How to delay loading of large background image
How can I delay /defer the loading of large background image? The reason am asking this question is because I have a poor score for "first meaningful paint" When I run performance tests on the page. I have tried reducing image size as much as possible. </p>

答:
If it is a background image you can use the Javascript onLoad event. This event excutes only after the whole page is finished loading.

Example:

```<code>function loadBGIMG(){
    document.getElementById("any-menu").style.backgroundImage="url(../images/any-menu.jpg)";
}
window.onload=loadBGIMG();
</code>```

Body:
If it is a background image you can use the Javascript onLoad event. This event excutes only after the whole page is finished loading.

Example:

function loadBGIMG(){
    document.getElementById("any-menu").style.backgroundImage="url(../images/any-menu.jpg)";
}
window.onload=loadBGIMG();


答:
As documented here you need to provide key-value pairs to OrderedDict.

At its core, OrderedDict is a dictionary and thus needs a value to store at a key.
Passing it (1) is wrong because:

```<code>>>a = (1)
>>type(a)
<class 'int'>
</code>```

So, (1) is not a tuple but an integer object.

Title: Python OrderedDict iterable over int

Body:
As documented here you need to provide key-value pairs to OrderedDict.

At its core, OrderedDict is a dictionary and thus needs a value to store at a key.
Passing it (1) is wrong because:

>>a = (1)
>>type(a)
<class 'int'>

So, (1) is not a tuple but an integer object.


答:
The list elements should be a tuple of 2 items (one key and another value).

(1) becomes 1 an int. So what python is doing is it is trying to split it into key-value pair. So you get that error.

Title: Python OrderedDict iterable over int


问:
Swift 3 : How to add a link in imessage?
I'm trying to add a link in iMessage Sticker app.  The link opens itunes sticker store page.  When I add these code in MessagesViewController.swift file, I get an error "'shared' is unvailable: Use view controller based solutions where appropriate instead". How to add the link properly? </p>

```<code> func clickMe(sender:UIButton!)
{
    UIApplication.shared.open(URL(string: "itms-apps://itunes.apple.com/app/id11111111")!)
    print("Button Clicked")
}
</code>```

答:
iOS Extensions have some limitations so you can not access every API that you can reach from an app.

Some APIs Are Unavailable to App Extensions

Because of its focused role in the system, an app extension is ineligible to participate in certain activities. An app extension cannot:

Access a sharedApplication object, and so cannot use any of the methods on that object...

For more details take a look at this App Extension Programming Guide

Body:
I'm trying to add a link in iMessage Sticker app.  The link opens itunes sticker store page.  When I add these code in MessagesViewController.swift file, I get an error "'shared' is unvailable: Use view controller based solutions where appropriate instead". How to add the link properly?

 func clickMe(sender:UIButton!)
{
    UIApplication.shared.open(URL(string: "itms-apps://itunes.apple.com/app/id11111111")!)
    print("Button Clicked")
}


问:
Why is the variable name replaced by its value causing " 'xxx' should be declared" error?
I wrote the following PL/SQL block:

```<code>declare
    v_name varchar2(20);
    v_sal integer;
begin
    EXECUTE IMMEDIATE ('CREATE TABLE EMP5 (name varchar2(20),sal integer,primary key(name))');
    dbms_output.put_line('Enter name : ');
    v_name:=&v_name;
    dbms_output.put_line('salary : ');
    v_sal :=&v_sal;
    insert into emp5 (name,sal) values (v_name,v_sal);
end;
/
</code>```

And then I got the following compiler output:

```<code>Enter a valeur for v_name : dhia
old 6 : v_name:=&v_name;
new 6 : v_name:=dhia;
Enter a valeur for v_sal : 10
old 8 : v_sal :=v_&sal;
new 8 : v_sal :=10;
v_name:=dhia;
      *
ERREUR at line 6 :
ORA-06550: line 6, colon 7 :
PLS-00201: the identifier 'DHIA' should be declared
ORA-06550: line 6, colon 1 :
PL/SQL: Statement ignored
ORA-06550: line9, colon 13 :
PL/SQL: ORA-00942: table or view does not exist
ORA-06550: line 9, colon 1 :
PL/SQL: SQL Statement ignored
</code>```

My question is why the variable 'name' replaced by its value 'dhia' in the script causing that error, and how to fix it?

答:
This is not compiler output, it's SQL*Plus output:

```<code>Enter a valeur for v_name : dhia
old 6 : v_name:=&v_name;
new 6 : v_name:=dhia;
</code>```

&v_name is a substitution variable (also known as a define variable), which means SQL*Plus blindly replaces &v_name with the literal text dhia before sending it to the database for compilation and execution. The new 6 line above is showing you what your code looks like after this text substitution. As you can see, v_name := dhia; would only be valid if there was another variable or function in scope named dhia. If you want to use a substitution variable for a text value, you need to quote it:

```<code>v_name := '&v_name';
</code>```

This also means your dbms_output commands will not be executed until after the substitution, which makes them somewhat useless. If you want to capture input from the user, use the accept command before the start of the PL/SQL block.

Another problem in your example is that if the EMP5 table does not exist, the block won't compile because of the reference to a non-existent table in the insert command; but if it does exist then your execute immediate will fail. You need to either create the table in a separate step, or else use execute immediate for all references to it and handle the case where it already exists.

Body:
I wrote the following PL/SQL block:

declare
    v_name varchar2(20);
    v_sal integer;
begin
    EXECUTE IMMEDIATE ('CREATE TABLE EMP5 (name varchar2(20),sal integer,primary key(name))');
    dbms_output.put_line('Enter name : ');
    v_name:=&v_name;
    dbms_output.put_line('salary : ');
    v_sal :=&v_sal;
    insert into emp5 (name,sal) values (v_name,v_sal);
end;
/

And then I got the following compiler output:

Enter a valeur for v_name : dhia
old 6 : v_name:=&v_name;
new 6 : v_name:=dhia;
Enter a valeur for v_sal : 10
old 8 : v_sal :=v_&sal;
new 8 : v_sal :=10;
v_name:=dhia;
      *
ERREUR at line 6 :
ORA-06550: line 6, colon 7 :
PLS-00201: the identifier 'DHIA' should be declared
ORA-06550: line 6, colon 1 :
PL/SQL: Statement ignored
ORA-06550: line9, colon 13 :
PL/SQL: ORA-00942: table or view does not exist
ORA-06550: line 9, colon 1 :
PL/SQL: SQL Statement ignored

My question is why the variable 'name' replaced by its value 'dhia' in the script causing that error, and how to fix it?

Body:
This is not compiler output, it's SQL*Plus output:

Enter a valeur for v_name : dhia
old 6 : v_name:=&v_name;
new 6 : v_name:=dhia;

&v_name is a substitution variable (also known as a define variable), which means SQL*Plus blindly replaces &v_name with the literal text dhia before sending it to the database for compilation and execution. The new 6 line above is showing you what your code looks like after this text substitution. As you can see, v_name := dhia; would only be valid if there was another variable or function in scope named dhia. If you want to use a substitution variable for a text value, you need to quote it:

v_name := '&v_name';

This also means your dbms_output commands will not be executed until after the substitution, which makes them somewhat useless. If you want to capture input from the user, use the accept command before the start of the PL/SQL block.

Another problem in your example is that if the EMP5 table does not exist, the block won't compile because of the reference to a non-existent table in the insert command; but if it does exist then your execute immediate will fail. You need to either create the table in a separate step, or else use execute immediate for all references to it and handle the case where it already exists.


问:
Test 32-bit assembly on a 64 bit windows with NUnit
I'm using C# and .NET 4.0 to build my current application. For unit testing I use NUnit in its latest version.

In my application I have to make use of a 32-bit DLL, and therefore I have to create the assembly with target 'x86'.

The application itself works fine under both 32-bit and 64-bit Windows, but I can't use NUnit as I get the following exception upon loading the 'x86' assembly:

In Settings->Assembly Isolation I use 'Run tests in separate process per Assembly', but to no use.

```<code>System.BadImageFormatException...

Server stack trace:
   bei System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)
   bei System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
   bei System.Reflection.Assembly.Load(AssemblyName assemblyRef)
   bei NUnit.Core.Builders.TestAssemblyBuilder.Load(String path)
   bei NUnit.Core.Builders.TestAssemblyBuilder.Build(String assemblyName, Boolean autoSuites)
   bei NUnit.Core.Builders.TestAssemblyBuilder.Build(String assemblyName, String testName, Boolean autoSuites)
   bei NUnit.Core.TestSuiteBuilder.BuildSingleAssembly(TestPackage package)
   bei NUnit.Core.TestSuiteBuilder.Build(TestPackage package)
   bei NUnit.Core.SimpleTestRunner.Load(TestPackage package)
   bei NUnit.Core.ProxyTestRunner.Load(TestPackage package)
   bei NUnit.Core.ProxyTestRunner.Load(TestPackage package)
   bei NUnit.Core.RemoteTestRunner.Load(TestPackage package)
   bei System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs)
   bei System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg, Int32 methodPtr, Boolean fExecuteInContext)

Exception rethrown at [0]:
   bei System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   bei System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   bei NUnit.Core.TestRunner.Load(TestPackage package)
   bei NUnit.Util.TestDomain.Load(TestPackage package)
   bei NUnit.Core.ProxyTestRunner.Load(TestPackage package)
   bei NUnit.Util.RemoteTestAgent.AgentRunner.Load(TestPackage package)
   bei System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs)
   bei System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg, Int32 methodPtr, Boolean fExecuteInContext)

Exception rethrown at [1]:
   bei System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   bei System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   bei NUnit.Core.TestRunner.Load(TestPackage package)
   bei NUnit.Core.ProxyTestRunner.Load(TestPackage package)
   bei NUnit.Util.ProcessRunner.Load(TestPackage package)
   bei NUnit.Util.AggregatingTestRunner.Load(TestPackage package)
   bei NUnit.Util.TestLoader.LoadTest(String testName)
</code>```

How to get those tests running on a 64-bit version of Windows?

答: The question is answered in How do I investigate the course of a test's assembly refusing to load in NUnit?. (Ref Ian Ringrose's comment to the question.)

Body:
I'm using C# and .NET 4.0 to build my current application. For unit testing I use NUnit in its latest version.

In my application I have to make use of a 32-bit DLL, and therefore I have to create the assembly with target 'x86'.

The application itself works fine under both 32-bit and 64-bit Windows, but I can't use NUnit as I get the following exception upon loading the 'x86' assembly:

In Settings->Assembly Isolation I use 'Run tests in separate process per Assembly', but to no use.

System.BadImageFormatException...

Server stack trace:
   bei System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)
   bei System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
   bei System.Reflection.Assembly.Load(AssemblyName assemblyRef)
   bei NUnit.Core.Builders.TestAssemblyBuilder.Load(String path)
   bei NUnit.Core.Builders.TestAssemblyBuilder.Build(String assemblyName, Boolean autoSuites)
   bei NUnit.Core.Builders.TestAssemblyBuilder.Build(String assemblyName, String testName, Boolean autoSuites)
   bei NUnit.Core.TestSuiteBuilder.BuildSingleAssembly(TestPackage package)
   bei NUnit.Core.TestSuiteBuilder.Build(TestPackage package)
   bei NUnit.Core.SimpleTestRunner.Load(TestPackage package)
   bei NUnit.Core.ProxyTestRunner.Load(TestPackage package)
   bei NUnit.Core.ProxyTestRunner.Load(TestPackage package)
   bei NUnit.Core.RemoteTestRunner.Load(TestPackage package)
   bei System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs)
   bei System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg, Int32 methodPtr, Boolean fExecuteInContext)

Exception rethrown at [0]:
   bei System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   bei System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   bei NUnit.Core.TestRunner.Load(TestPackage package)
   bei NUnit.Util.TestDomain.Load(TestPackage package)
   bei NUnit.Core.ProxyTestRunner.Load(TestPackage package)
   bei NUnit.Util.RemoteTestAgent.AgentRunner.Load(TestPackage package)
   bei System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs)
   bei System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg, Int32 methodPtr, Boolean fExecuteInContext)

Exception rethrown at [1]:
   bei System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   bei System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   bei NUnit.Core.TestRunner.Load(TestPackage package)
   bei NUnit.Core.ProxyTestRunner.Load(TestPackage package)
   bei NUnit.Util.ProcessRunner.Load(TestPackage package)
   bei NUnit.Util.AggregatingTestRunner.Load(TestPackage package)
   bei NUnit.Util.TestLoader.LoadTest(String testName)

How to get those tests running on a 64-bit version of Windows?


问:
Server Tomcat v8.0 Server at localhost failed to start. after declaring servlet name and mapping in web.xml file
I am making a simple servlet for hello world to check that servlet is working properly or not but after making servlet and mapping web.xml file when I run the servlet it gives me an error.

My code:

Web.xml

Please help me to solve my problem ??

答:
The problem occurs because your web.xml is referencing the servlet annotated with @WebServlet annotation.

If you want to register your servlet using deployment descripter(web.xml), you have to remove @WebServlet annotation in your servlet class.

```<code>@WebServlet(
    urlPatterns = { "/HelloWorld" },
    initParams = {
            @WebInitParam(name = "name", value = "helloworld")
    })
</code>```

Or delete <servlet> and <servlet-mapping> defined in web.xml in order to use @WebServlet.

```<code><servlet>
    <servlet-name>HelloWorld</servlet-name>
    <servlet-class>com.jsp.first.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>HelloWorld</servlet-name>
    <url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
</code>```

And it should work.

Body:
The problem occurs because your web.xml is referencing the servlet annotated with @WebServlet annotation.

If you want to register your servlet using deployment descripter(web.xml), you have to remove @WebServlet annotation in your servlet class.

@WebServlet(
    urlPatterns = { "/HelloWorld" },
    initParams = {
            @WebInitParam(name = "name", value = "helloworld")
    })

Or delete <servlet> and <servlet-mapping> defined in web.xml in order to use @WebServlet.

<servlet>
    <servlet-name>HelloWorld</servlet-name>
    <servlet-class>com.jsp.first.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>HelloWorld</servlet-name>
    <url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>

And it should work.


问:
How to create modal box using html, css and jquery?
How to create modal box using html, css and jquery?
    </p>

```<code><button id="myBtn">Open Modal</button>
</code>```

<p>
    </p>

```<code>  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">×</span>
    <p>Some text in the Modal..</p>
  </div>

</div>
</code>```

答:
this an example multiple modal create, just check it out.

function createModal(){
  var dataModal = "";
      var countModal = $(".modalWrap").length;
      if(typeof countModal === "undefined" || countModal == 0){
        countModal = 0;
      }
      /*this just an example, you can try improv it more like load file or url to fill your modal data.*/
      dataModal = '

This Modal '+(countModal+1)+'
<input type="button" value="modal create" onclick="createModal();"/> <input type="button" onclick="closeModal(\'#modal-'+(countModal+1)+'\');" value="close modal"/>

';
      $('body').append(dataModal);
}

function closeModal(idModal){
$(idModal).remove();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.modalWrap{
width : 100%;
background : rgba(0,0,0,0.5);
min-height : 500px;
position : fixed;
top:0;
left:0;
}

.modalBody{
width : 60%;
min-height: 250px;
background : #fff;
margin-top : 10%;
}</code>```

<input type="button" value="modal create" onclick="createModal();"/>

```

you can use this if you want multiple modal create.

Body:
How to create modal box using html, css and jquery?

<button id="myBtn">Open Modal</button>

    ×

Some text in the Modal..

Body:
this an example multiple modal create, just check it out.

function createModal(){
  var dataModal = "";
      var countModal = $(".modalWrap").length;
      if(typeof countModal === "undefined" || countModal == 0){
        countModal = 0;
      }
      /*this just an example, you can try improv it more like load file or url to fill your modal data.*/
      dataModal = '<div align="center" class="modalWrap" id="modal-'+(countModal+1)+'" style="z-index:'+(countModal+1)+'"><div class="modalBody" id="modalBody-'+(countModal+1)+'"> <h1>This Modal '+(countModal+1)+'</h1><input type="button" value="modal create" onclick="createModal();"/> <input type="button" onclick="closeModal(\'#modal-'+(countModal+1)+'\');" value="close modal"/></div></div>';
      $('body').append(dataModal);
}

function closeModal(idModal){
$(idModal).remove();
}

.modalWrap{
width : 100%;
background : rgba(0,0,0,0.5);
min-height : 500px;
position : fixed;
top:0;
left:0;
}

.modalBody{
width : 60%;
min-height: 250px;
background : #fff;
margin-top : 10%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<input type="button" value="modal create" onclick="createModal();"/>
</body>
</html>

you can use this if you want multiple modal create.


问:
Using dot leaders for a food menu with bootstrap grids
I'm creating a food menu using the grid column system with bootstrap 3, and I'm trying to create dot leaders between the menu item and the price. I kind of got it to work, but I can't seem to get the dot leaders to extend to the right of the item, instead it breaks the line and continues under the menu.
Here's what I'm getting:

I tried

```<code>display:block; display:inline-block; display:inline;
</code>```

in the CSS. The only way I seem to be able to stop it from breaking is shortening the

```<code>content: '...'
</code>```

Is there a way I can get this to work, or do I have put the content in a table or use list items?

Here is the rest of my code, if anyone could help, I would appreciate it, thanks.

Cheese

White

Special

$8.99

$9.99

$13.50

$10.99

$11.99

$15.50

$12.99

$13.99

$17.50

    .dots::after {
       display: inline-flex;
       white-space: nowrap;
       overflow: hidden;
       text-overflow: clip;
       content:
        " . . . . . . . . . . . . . . . . . . . . "
        ". . . . . . . . . . . . . . . . . . . . "
        ". . . . . . . . . . . . . . . . . . . . "
        ". . . . . . . . . . . . . . . . . . . . "
     }```

答:
You could do a display: flex trick with these 2 rules

```<code>.dots {
  display: flex;
}
.dots::after {
  white-space: nowrap;
  overflow: hidden;
  direction: rtl;
  content: " . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ."
}
</code>```

Stack snippet

.dots {
  display: flex;
}
.dots::after {
  white-space: nowrap;
  overflow: hidden;
  direction: rtl;
  content: " . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ."
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<div class="container">
  <div class="row">
    <div class=" col-xs-6 ">
      <p class="item dots ">Cheese</p>
      <p class="item dots ">White</p>
      <p class="item dots ">Special</p>
    </div>
    <div class="col-xs-2">
      <p class="item ">$8.99</p>
      <p class="item ">$9.99</p>
      <p class="item ">$13.50</p>
    </div>
    <div class="col-xs-2">
      <p class="item ">$10.99</p>
      <p class="item ">$11.99</p>
      <p class="item ">$15.50</p>
    </div>
    <div class="col-xs-2">
      <p class="item ">$12.99</p>
      <p class="item ">$13.99</p>
      <p class="item ">$17.50</p>
    </div>
  </div>
</div></code>```

Body:
I'm creating a food menu using the grid column system with bootstrap 3, and I'm trying to create dot leaders between the menu item and the price. I kind of got it to work, but I can't seem to get the dot leaders to extend to the right of the item, instead it breaks the line and continues under the menu.
Here's what I'm getting:

I tried

display:block; display:inline-block; display:inline;

in the CSS. The only way I seem to be able to stop it from breaking is shortening the

content: '...'

Is there a way I can get this to work, or do I have put the content in a table or use list items?

Here is the rest of my code, if anyone could help, I would appreciate it, thanks.

Cheese

White

Special

$8.99

$9.99

$13.50

$10.99

$11.99

$15.50

$12.99

$13.99

$17.50

    .dots::after {
       display: inline-flex;
       white-space: nowrap;
       overflow: hidden;
       text-overflow: clip;
       content:
        " . . . . . . . . . . . . . . . . . . . . "
        ". . . . . . . . . . . . . . . . . . . . "
        ". . . . . . . . . . . . . . . . . . . . "
        ". . . . . . . . . . . . . . . . . . . . "
     }

Body:
You could do a display: flex trick with these 2 rules

.dots {
  display: flex;
}
.dots::after {
  white-space: nowrap;
  overflow: hidden;
  direction: rtl;
  content: " . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ."
}

Stack snippet

.dots {
  display: flex;
}
.dots::after {
  white-space: nowrap;
  overflow: hidden;
  direction: rtl;
  content: " . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ."
}

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

<div class="container">
  <div class="row">
    <div class=" col-xs-6 ">
      <p class="item dots ">Cheese</p>
      <p class="item dots ">White</p>
      <p class="item dots ">Special</p>
    </div>
    <div class="col-xs-2">
      <p class="item ">$8.99</p>
      <p class="item ">$9.99</p>
      <p class="item ">$13.50</p>
    </div>
    <div class="col-xs-2">
      <p class="item ">$10.99</p>
      <p class="item ">$11.99</p>
      <p class="item ">$15.50</p>
    </div>
    <div class="col-xs-2">
      <p class="item ">$12.99</p>
      <p class="item ">$13.99</p>
      <p class="item ">$17.50</p>
    </div>
  </div>
</div>


问:
Parse one field from nested Json to String Value
i have one field nested JSON in my API response :

```<code>"ratingBest": 10,
"reviewCount": 1,
"coordinate": {
    "latitude": "-7.2768",
    "longitude": "112.7927"
},
...
</code>```

I save above data to Android local DB using ORMLite, but i want just one field coordinate to be String. Cause Gson automatically convert in specific type.

I already try to use a class field type as String. But still not work

Any workaround for that?

Thank you

答:
You can do this in the following way:

```<code>myObj = {
    "ratingBest": 10,
    "reviewCount": 1,
     "coordinate": {
     "latitude": "-7.2768",
     "longitude": "112.7927"
       }
    }
var latitudex = myObj.coordinate.latitude;
var longitudex = myObj.coordinate.longitude;
</code>```

Hope it will help you.

Body:
i have one field nested JSON in my API response :

"ratingBest": 10,
"reviewCount": 1,
"coordinate": {
    "latitude": "-7.2768",
    "longitude": "112.7927"
},
...

I save above data to Android local DB using ORMLite, but i want just one field coordinate to be String. Cause Gson automatically convert in specific type.

I already try to use a class field type as String. But still not work

Any workaround for that?

Thank you

Body:
You can do this in the following way:

myObj = {
    "ratingBest": 10,
    "reviewCount": 1,
     "coordinate": {
     "latitude": "-7.2768",
     "longitude": "112.7927"
       }
    }
var latitudex = myObj.coordinate.latitude;
var longitudex = myObj.coordinate.longitude;

Hope it will help you.


问:
how to merge odd number line and even number line in vim?
In order to merge the odd number line and the even number line in two methods.
One use command :s, the other use command :g and :s.

It's our homework and I could not get appropriate answer from the google.

And I had worked out the first one, which means I can solve it with command :s:

```<code>:%s/\(^.*$\)\n\(^.*$\)/\1 \2
</code>```

And how could I use command :d and :s to solve it?

BEFORE:

```<code> 1 aa
 2 bb
 3 abc
 4 abc
 5 an apple
 6 is a bug
 7 mazic
 8 homework!
 9 try a time
10 dodo
</code>```

AFTER:

```<code> 1 aa bb
 2 abc abc
 3 an apple is a bug
 4 mazic homework!
 5 try a time dodo
</code>```

thanks to everyone and I have leant about how to solve it before the lesson.hah

:g/\(^.*$\)\n\(^.*$\)/s//\1 \2

答:
What you can do here is :
Move the cursor to the line number to which you want to append the next line and then type below command in normal mode.

```<code>:s/\n/ /
</code>```

Another way is go to the particular line and press SHIFT+V and then type below command:

```<code>:'<,'>s/\n/, /
</code>```

Note that when you are in visual mode and press : then :'<,'> will automatically get typed. You just need to type regex ahead of that.

In both the above commands, g is not needed as it will not do any impact because only one \n will be there for each line.

Body:
In order to merge the odd number line and the even number line in two methods.
One use command :s, the other use command :g and :s.

It's our homework and I could not get appropriate answer from the google.

And I had worked out the first one, which means I can solve it with command :s:

:%s/\(^.*$\)\n\(^.*$\)/\1 \2

And how could I use command :d and :s to solve it?

BEFORE:

 1 aa
 2 bb
 3 abc
 4 abc
 5 an apple
 6 is a bug
 7 mazic
 8 homework!
 9 try a time
10 dodo

AFTER:

 1 aa bb
 2 abc abc
 3 an apple is a bug
 4 mazic homework!
 5 try a time dodo

thanks to everyone and I have leant about how to solve it before the lesson.hah

:g/\(^.*$\)\n\(^.*$\)/s//\1 \2

Body:
What you can do here is :
Move the cursor to the line number to which you want to append the next line and then type below command in normal mode.

:s/\n/ /

Another way is go to the particular line and press SHIFT+V and then type below command:

:'<,'>s/\n/, /

Note that when you are in visual mode and press : then :'<,'> will automatically get typed. You just need to type regex ahead of that.

In both the above commands, g is not needed as it will not do any impact because only one \n will be there for each line.


问:
How to perform selective rbind on datasets in R
I am trying to use rbind to append different datasets countrywise. The list of the datasets is

```<code>data <- c('a1','a2','a3','b1','b2','bu3','bu4','c1','c3')
code <- c('a','b','bu',c)
</code>```

The structure of the data is somewhat like this -

```<code>countrya1 <- c("a","a","a")
yeara1 <- c("1","1","1")
inca1 <- c("1","2","3")
a1 <- data.frame(countrya1,yeara1,inca1)
countrya2 <- c("a","a","a")
yeara2 <- c("2","2","2")
inca2 <- c("1","4","3")
a2 <- data.frame(countrya2,yeara2,inca2)
countryb1 <- c("b","b","b")
yearb1 <- c("1","1","1")
incb1 <- c("1","2","7")
b1 <- data.frame(countryb1,yearb1,incb1)
countryb2 <- c("b","b","b")
yearb2 <- c("2","2","2")
incb2 <- c("6","2","3")
b2 <- data.frame(countryb2,yearb2,incb2)
</code>```

The code that I used to combine all the datasets is as follows -

```<code>df=NULL
for (i in length(data)){
df1 <-read.dta(data[i])
df <-rbind(df,df1)
}
</code>```

This binds all the datasets together in df.
Is there a way to bind a1,a2,a3 together and b1,b2,b3 together and so on. In short, I want to bind the datasets by 'code'. Is there a way to do it in R?
Thanks in advance for the help.

答:
We can split the 'data' by creating a group without the numbers and then with read.dta, read the datasets and rbind the datasets of same name

```<code>lst <- lapply(split(data, sub("\\d+", "", data)),
             function(x) do.call(rbind, lapply(x, read.dta)))
</code>```

If we want to use the 'code', then use grep by looping through the 'code'

```<code>lapply(code, function(x) do.call(rbind, lapply(grep(x, data, value = TRUE), read.dta)))
</code>```

data

```<code>code <- c('a','b','bu','c')
</code>```

Body:
I am trying to use rbind to append different datasets countrywise. The list of the datasets is

data <- c('a1','a2','a3','b1','b2','bu3','bu4','c1','c3')
code <- c('a','b','bu',c)

The structure of the data is somewhat like this -

countrya1 <- c("a","a","a")
yeara1 <- c("1","1","1")
inca1 <- c("1","2","3")
a1 <- data.frame(countrya1,yeara1,inca1)
countrya2 <- c("a","a","a")
yeara2 <- c("2","2","2")
inca2 <- c("1","4","3")
a2 <- data.frame(countrya2,yeara2,inca2)
countryb1 <- c("b","b","b")
yearb1 <- c("1","1","1")
incb1 <- c("1","2","7")
b1 <- data.frame(countryb1,yearb1,incb1)
countryb2 <- c("b","b","b")
yearb2 <- c("2","2","2")
incb2 <- c("6","2","3")
b2 <- data.frame(countryb2,yearb2,incb2)

The code that I used to combine all the datasets is as follows -

df=NULL
for (i in length(data)){
df1 <-read.dta(data[i])
df <-rbind(df,df1)
}

This binds all the datasets together in df.
Is there a way to bind a1,a2,a3 together and b1,b2,b3 together and so on. In short, I want to bind the datasets by 'code'. Is there a way to do it in R?
Thanks in advance for the help.

Body:
We can split the 'data' by creating a group without the numbers and then with read.dta, read the datasets and rbind the datasets of same name

lst <- lapply(split(data, sub("\\d+", "", data)),
             function(x) do.call(rbind, lapply(x, read.dta)))

If we want to use the 'code', then use grep by looping through the 'code'

lapply(code, function(x) do.call(rbind, lapply(grep(x, data, value = TRUE), read.dta)))

data

code <- c('a','b','bu','c')


问:
Dagger2 Not Generating Dagger* classes
As the title says, Dagger2 is not generating the Dagger* prefixed classes. I looked at some other similar posts here but nothing seems to work.

I cloned this repo https://github.com/ecgreb/mvpc, Invalidated the cache of Android Studio and restarted it, I deleted $Project/.gradle and $Home/.gradle/caches, Clean and Rebuild the project and still not working.

This has also happened on some projects that are using Dagger2

Am I missing something?

```<code>apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'

android {
  compileSdkVersion 24
  buildToolsVersion "24.0.3"

  defaultConfig {
    applicationId "com.example.ecgreb.mvpc"
    minSdkVersion 15
    targetSdkVersion 24
    versionCode 1
    versionName "1.0"
  }
  buildTypes {
    release {
      minifyEnabled false
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
  }
}

tasks.withType(Test) {
  testLogging {
    exceptionFormat "full"
    events "started", "skipped", "passed", "failed"
    showStandardStreams true
  }
}

repositories {
  mavenCentral()
}

dependencies {
  compile 'com.android.support:appcompat-v7:24.2.1'
  compile 'com.android.support:design:24.2.1'

  compile "com.google.dagger:dagger:2.7"
  annotationProcessor "com.google.dagger:dagger-compiler:2.7"
  provided 'javax.annotation:jsr250-api:1.0'

  testCompile 'junit:junit:4.12'
  testCompile 'org.mockito:mockito-core:1.10.19'
  testCompile 'org.assertj:assertj-core:1.7.1'
  testCompile 'org.robolectric:robolectric:3.1.2'
  testCompile 'org.khronos:opengl-api:gl1.1-android-2.1_r1'
}
</code>```

The Application class.

```<code>package com.example.ecgreb.mvpc;

import android.app.Application;

import com.example.ecgreb.mvpc.controller.LoginActivity;

import javax.inject.Singleton;

import dagger.Component;
public class MvpcApplication extends Application {

  @Singleton @Component(modules = { LoginModule.class }) public interface ApplicationComponent {
    void inject(LoginActivity loginActivity);
  }

  private ApplicationComponent component;

  @Override public void onCreate() {
    super.onCreate();
    //DaggerApplicationComponent IS NOT BEING GENERATED
    component = DaggerApplicationComponent.builder().build();
  }

  public ApplicationComponent component() {
    return component;
  }
}
</code>```

答: For anyone who has this kind of issues when using Jack Compiler with your project, you might have seen that none of the solutions work, and the reason is linked to Dagger2 itself. The latest versions don't work well with Jack, I manager to make it work up until the 2.2 version of Dagger2.</p>

Title: Dagger2 Not Generating Dagger* classes

Body:
As the title says, Dagger2 is not generating the Dagger* prefixed classes. I looked at some other similar posts here but nothing seems to work.

I cloned this repo https://github.com/ecgreb/mvpc, Invalidated the cache of Android Studio and restarted it, I deleted $Project/.gradle and $Home/.gradle/caches, Clean and Rebuild the project and still not working.

This has also happened on some projects that are using Dagger2

Am I missing something?

apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'

android {
  compileSdkVersion 24
  buildToolsVersion "24.0.3"

  defaultConfig {
    applicationId "com.example.ecgreb.mvpc"
    minSdkVersion 15
    targetSdkVersion 24
    versionCode 1
    versionName "1.0"
  }
  buildTypes {
    release {
      minifyEnabled false
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
  }
}

tasks.withType(Test) {
  testLogging {
    exceptionFormat "full"
    events "started", "skipped", "passed", "failed"
    showStandardStreams true
  }
}

repositories {
  mavenCentral()
}

dependencies {
  compile 'com.android.support:appcompat-v7:24.2.1'
  compile 'com.android.support:design:24.2.1'

  compile "com.google.dagger:dagger:2.7"
  annotationProcessor "com.google.dagger:dagger-compiler:2.7"
  provided 'javax.annotation:jsr250-api:1.0'

  testCompile 'junit:junit:4.12'
  testCompile 'org.mockito:mockito-core:1.10.19'
  testCompile 'org.assertj:assertj-core:1.7.1'
  testCompile 'org.robolectric:robolectric:3.1.2'
  testCompile 'org.khronos:opengl-api:gl1.1-android-2.1_r1'
}

The Application class.

package com.example.ecgreb.mvpc;

import android.app.Application;

import com.example.ecgreb.mvpc.controller.LoginActivity;

import javax.inject.Singleton;

import dagger.Component;
public class MvpcApplication extends Application {

  @Singleton @Component(modules = { LoginModule.class }) public interface ApplicationComponent {
    void inject(LoginActivity loginActivity);
  }

  private ApplicationComponent component;

  @Override public void onCreate() {
    super.onCreate();
    //DaggerApplicationComponent IS NOT BEING GENERATED
    component = DaggerApplicationComponent.builder().build();
  }

  public ApplicationComponent component() {
    return component;
  }
}


问:
how to break promise chain
I a promise in such fashion,

```<code>function getMode(){
    var deferred = Promise.defer();

    checkIf('A')
    .then(function(bool){
        if(bool){
            deferred.resolve('A');
        }else{
            return checkIf('B');
        }
    }).then(function(bool){
        if(bool){
            deferred.resolve('B');
        }else{
            return checkIf('C');
        }
    }).then(function(bool){
        if(bool){
            deferred.resolve('C');
        }else{
            deferred.reject();
        }
    });

    return deferred.promise;
}
</code>```

checkIf returns a promise, and yes checkIf cannot be modified.

How do I break out of the chain at the first match? (any way other than explicitly throwing error?)

答:
Probably coming late the party here, but I recently posted an answer using generators and the co library that would answer this question (see solution 2):

https://stackoverflow.com/a/43166487/1337392

The code would be something like:

```<code>const requestHandler = function*() {

        const survey = yield Survey.findOne({
            _id: "bananasId"
        });

        if (survey !== null) {
            console.log("use HTTP PUT instead!");
            return;
        }

        try {
            //saving empty object for demonstration purposes
            yield(new Survey({}).save());
            console.log("Saved Successfully !");
            return;
        }
        catch (error) {
            console.log(`Failed to save with error:  ${error}`);
            return;
        }

    };

    co(requestHandler)
        .then(() => {
            console.log("finished!");
        })
        .catch(console.log);
</code>```

You would pretty much write synchronous code that would be in reality asynchronous !

Hope it helps!

Title: how to break promise chain

Body:
I a promise in such fashion,

function getMode(){
    var deferred = Promise.defer();

    checkIf('A')
    .then(function(bool){
        if(bool){
            deferred.resolve('A');
        }else{
            return checkIf('B');
        }
    }).then(function(bool){
        if(bool){
            deferred.resolve('B');
        }else{
            return checkIf('C');
        }
    }).then(function(bool){
        if(bool){
            deferred.resolve('C');
        }else{
            deferred.reject();
        }
    });

    return deferred.promise;
}

checkIf returns a promise, and yes checkIf cannot be modified.

How do I break out of the chain at the first match? (any way other than explicitly throwing error?)

Body:
Probably coming late the party here, but I recently posted an answer using generators and the co library that would answer this question (see solution 2):

https://stackoverflow.com/a/43166487/1337392

The code would be something like:

const requestHandler = function*() {

        const survey = yield Survey.findOne({
            _id: "bananasId"
        });

        if (survey !== null) {
            console.log("use HTTP PUT instead!");
            return;
        }

        try {
            //saving empty object for demonstration purposes
            yield(new Survey({}).save());
            console.log("Saved Successfully !");
            return;
        }
        catch (error) {
            console.log(`Failed to save with error:  ${error}`);
            return;
        }

    };

    co(requestHandler)
        .then(() => {
            console.log("finished!");
        })
        .catch(console.log);

You would pretty much write synchronous code that would be in reality asynchronous !

Hope it helps!


问:
Read the final line in a text file
I am currently learning Go, and I need to read the final line in a text file.

I have searched everywhere and there does not seem to be a definitive explanation on how one would do this.

How would I do this?

答:
Starting the search from the very beginning of the file can be an expensive option esp. if your file(s) are large.

A better option may be to - Use os.Open to open the file and stat method (https://golang.org/pkg/os/#File.Stat) to get the size of the file. Start reading from end of the file using ReadAt (https://golang.org/pkg/os/#File.ReadAt - read the last byte first, second last byte next..), all the way reverse till you find the second newline character. That's the beginning of the last line. Hope this helps.

Title: Read the final line in a text file


问:
What is switchMap equivalent to in unflattened form?
If flatMap() is equivalent to map().mergeAll(),
then what is switchMap() equivalent to ?

答:
The switchMap() operator is equivalent to using map().switch().

Since the switch() operator works only with higher-order Observables the preceding map() has to return an Observable. There's no switchAll() operator because the switch() operator already works with higher-order Observables(just like all *all() operators).


问:
AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
I have an error when building my code on an Android device.

When I click button start to get the coordinate, the coordinate is shown on the monitor, but my application was stopped and does not send data coordinate on my server.

The error report from Android Studio:

```<code>--------- beginning of crash E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
  Process: id.codefun.gps, PID: 2418
  java.lang.RuntimeException: An error occurred while executing doInBackground()
      at android.os.AsyncTask$3.done(AsyncTask.java:325)
      at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
      at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
      at java.util.concurrent.FutureTask.run(FutureTask.java:242)
      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
      at java.lang.Thread.run(Thread.java:761)
   Caused by: java.lang.ClassCastException: com.android.okhttp.internal.huc.HttpURLConnectionImpl cannot be cast
to javax.net.ssl.HttpsURLConnection
      at id.codefun.gps.BackgroundTask.doInBackground(BackgroundTask.java:41)
      at id.codefun.gps.BackgroundTask.doInBackground(BackgroundTask.java:19)
      at android.os.AsyncTask$2.call(AsyncTask.java:305)
      at java.util.concurrent.FutureTask.run(FutureTask.java:237)
      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
      at java.lang.Thread.run(Thread.java:761)  I/Choreographer: Skipped 41 frames!  The application may be doing too
much work on its main thread. Application terminated.
</code>```

MainActivity.java

```<code>import android.Manifest; import android.content.BroadcastReceiver;
import android.content.Context; import android.content.Intent; import
android.content.IntentFilter; import
android.content.pm.PackageManager; import android.os.Build; import
android.support.annotation.NonNull; import
android.support.v4.content.ContextCompat; import
android.support.v7.app.AppCompatActivity; import android.os.Bundle;
import android.view.View; import android.widget.Button; import
android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private Button btn_start, btn_stop;
    private TextView textView;
    private BroadcastReceiver broadcastReceiver;
    String dataf;

    @Override
    protected void onResume() {
        super.onResume();
        if(broadcastReceiver == null){
            broadcastReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {

                    textView.append("\n" +intent.getExtras().get("coodinates"));

                    dataf = intent.getExtras().get("coodinates").toString();
                    System.out.println(dataf);
                    String method = "dataKirim";
                    BackgroundTask backgroundTask = new BackgroundTask(this);
                    backgroundTask.execute(method,dataf);
                    finish();
                }
            };
        }
        registerReceiver(broadcastReceiver, new IntentFilter("location_update"));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(broadcastReceiver != null){
            unregisterReceiver(broadcastReceiver);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn_start = (Button) findViewById(R.id.button);
        btn_stop  = (Button) findViewById(R.id.button2);
        textView  = (TextView) findViewById(R.id.textView);

        if(!runtime_permissions())
            enable_buttons();
    }

    private void enable_buttons() {
        btn_start.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                Intent i =new Intent(getApplicationContext(),gps.class);
                startService(i);
            }
        });
        btn_stop.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                Intent i =new Intent(getApplicationContext(),gps.class);
                stopService(i);
            }
        });
    }

    private boolean runtime_permissions(){
        if(Build.VERSION.SDK_INT >=23 && ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED){
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},100);
            return true;
        }
        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults){
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode==100){
            if(grantResults[0]==PackageManager.PERMISSION_GRANTED && grantResults[1]==PackageManager.PERMISSION_GRANTED){
                enable_buttons();
            }else{
                runtime_permissions();
            }
        }
    } }
</code>```

gps.java

```<code>import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;

public class gps extends Service {

    private LocationListener listener;
    private LocationManager locationManager;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        listener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location){
                Intent i = new Intent("location_update");
                i.putExtra("coodinates",location.getLongitude()+"-"+location.getLatitude()+"-");
                sendBroadcast(i);
            }

            @Override
            public void onProviderDisabled(String s) {
                Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
            }
        };
        locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        //noinspection MissingPermission
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,0,listener);

    }
}
</code>```

BackgroundTask.java

```<code>import android.content.BroadcastReceiver; import
android.content.Context; import android.os.AsyncTask; import
android.widget.Toast;

import java.io.BufferedWriter; import java.io.IOException; import
java.io.InputStream; import java.io.OutputStream; import
java.io.OutputStreamWriter; import java.net.MalformedURLException;
import java.net.URL; import java.net.URLEncoder;

import javax.net.ssl.HttpsURLConnection;

import static android.widget.Toast.makeText;

public class BackgroundTask extends AsyncTask<String, Void, String> {

    BroadcastReceiver ctx;
    BackgroundTask(BroadcastReceiver ctx){
        this.ctx = ctx;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {
        String post_url = "http://codefun.id/jajal_query_mysqli.php";
        String method = params[0];
        System.out.println(method);
        System.out.println(params[1]);
        if(method.equals("dataKirim")){
            String datag = params[1];
            try {
                URL url = new URL(post_url);
                HttpsURLConnection httpsURLConnection = (HttpsURLConnection)url.openConnection();
                httpsURLConnection.setRequestMethod("POST");
                httpsURLConnection.setDoOutput(true);
                OutputStream OS = httpsURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS,"UTF-8"));
                String Data = URLEncoder.encode("latlon","UTF-8") +"="+ URLEncoder.encode(datag,"UTF-8");
                bufferedWriter.write(Data);
                bufferedWriter.flush();
                bufferedWriter.close();
                OS.close();
                InputStream IS = httpsURLConnection.getInputStream();
                IS.close();
                return "kirim sukses";
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {
        //makeText(ctx, result,Toast.LENGTH_LONG).show();
    }

}
</code>```

Please help.

答:
Please note that your URL protocol is HTTP and not HTTPS. Try either using a java.net.HttpURLConnection object or a "https://..." URL.

```<code> import javax.net.ssl.HttpsURLConnection;
</code>```

replace with

```<code> java.net.HttpURLConnection
</code>```

Body:
I have an error when building my code on an Android device.

When I click button start to get the coordinate, the coordinate is shown on the monitor, but my application was stopped and does not send data coordinate on my server.

The error report from Android Studio:

--------- beginning of crash E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
  Process: id.codefun.gps, PID: 2418
  java.lang.RuntimeException: An error occurred while executing doInBackground()
      at android.os.AsyncTask$3.done(AsyncTask.java:325)
      at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
      at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
      at java.util.concurrent.FutureTask.run(FutureTask.java:242)
      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
      at java.lang.Thread.run(Thread.java:761)
   Caused by: java.lang.ClassCastException: com.android.okhttp.internal.huc.HttpURLConnectionImpl cannot be cast
to javax.net.ssl.HttpsURLConnection
      at id.codefun.gps.BackgroundTask.doInBackground(BackgroundTask.java:41)
      at id.codefun.gps.BackgroundTask.doInBackground(BackgroundTask.java:19)
      at android.os.AsyncTask$2.call(AsyncTask.java:305)
      at java.util.concurrent.FutureTask.run(FutureTask.java:237)
      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
      at java.lang.Thread.run(Thread.java:761)  I/Choreographer: Skipped 41 frames!  The application may be doing too
much work on its main thread. Application terminated.

MainActivity.java

import android.Manifest; import android.content.BroadcastReceiver;
import android.content.Context; import android.content.Intent; import
android.content.IntentFilter; import
android.content.pm.PackageManager; import android.os.Build; import
android.support.annotation.NonNull; import
android.support.v4.content.ContextCompat; import
android.support.v7.app.AppCompatActivity; import android.os.Bundle;
import android.view.View; import android.widget.Button; import
android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private Button btn_start, btn_stop;
    private TextView textView;
    private BroadcastReceiver broadcastReceiver;
    String dataf;

    @Override
    protected void onResume() {
        super.onResume();
        if(broadcastReceiver == null){
            broadcastReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {

                    textView.append("\n" +intent.getExtras().get("coodinates"));

                    dataf = intent.getExtras().get("coodinates").toString();
                    System.out.println(dataf);
                    String method = "dataKirim";
                    BackgroundTask backgroundTask = new BackgroundTask(this);
                    backgroundTask.execute(method,dataf);
                    finish();
                }
            };
        }
        registerReceiver(broadcastReceiver, new IntentFilter("location_update"));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(broadcastReceiver != null){
            unregisterReceiver(broadcastReceiver);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn_start = (Button) findViewById(R.id.button);
        btn_stop  = (Button) findViewById(R.id.button2);
        textView  = (TextView) findViewById(R.id.textView);

        if(!runtime_permissions())
            enable_buttons();
    }

    private void enable_buttons() {
        btn_start.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                Intent i =new Intent(getApplicationContext(),gps.class);
                startService(i);
            }
        });
        btn_stop.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                Intent i =new Intent(getApplicationContext(),gps.class);
                stopService(i);
            }
        });
    }

    private boolean runtime_permissions(){
        if(Build.VERSION.SDK_INT >=23 && ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED){
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},100);
            return true;
        }
        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults){
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode==100){
            if(grantResults[0]==PackageManager.PERMISSION_GRANTED && grantResults[1]==PackageManager.PERMISSION_GRANTED){
                enable_buttons();
            }else{
                runtime_permissions();
            }
        }
    } }

gps.java

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;

public class gps extends Service {

    private LocationListener listener;
    private LocationManager locationManager;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        listener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location){
                Intent i = new Intent("location_update");
                i.putExtra("coodinates",location.getLongitude()+"-"+location.getLatitude()+"-");
                sendBroadcast(i);
            }

            @Override
            public void onProviderDisabled(String s) {
                Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
            }
        };
        locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        //noinspection MissingPermission
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,0,listener);

    }
}

BackgroundTask.java

import android.content.BroadcastReceiver; import
android.content.Context; import android.os.AsyncTask; import
android.widget.Toast;

import java.io.BufferedWriter; import java.io.IOException; import
java.io.InputStream; import java.io.OutputStream; import
java.io.OutputStreamWriter; import java.net.MalformedURLException;
import java.net.URL; import java.net.URLEncoder;

import javax.net.ssl.HttpsURLConnection;

import static android.widget.Toast.makeText;

public class BackgroundTask extends AsyncTask<String, Void, String> {

    BroadcastReceiver ctx;
    BackgroundTask(BroadcastReceiver ctx){
        this.ctx = ctx;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {
        String post_url = "http://codefun.id/jajal_query_mysqli.php";
        String method = params[0];
        System.out.println(method);
        System.out.println(params[1]);
        if(method.equals("dataKirim")){
            String datag = params[1];
            try {
                URL url = new URL(post_url);
                HttpsURLConnection httpsURLConnection = (HttpsURLConnection)url.openConnection();
                httpsURLConnection.setRequestMethod("POST");
                httpsURLConnection.setDoOutput(true);
                OutputStream OS = httpsURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS,"UTF-8"));
                String Data = URLEncoder.encode("latlon","UTF-8") +"="+ URLEncoder.encode(datag,"UTF-8");
                bufferedWriter.write(Data);
                bufferedWriter.flush();
                bufferedWriter.close();
                OS.close();
                InputStream IS = httpsURLConnection.getInputStream();
                IS.close();
                return "kirim sukses";
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {
        //makeText(ctx, result,Toast.LENGTH_LONG).show();
    }

}

Please help.

Body:
Please note that your URL protocol is HTTP and not HTTPS. Try either using a java.net.HttpURLConnection object or a "https://..." URL.

 import javax.net.ssl.HttpsURLConnection;

replace with

 java.net.HttpURLConnection


问:
How do you replace all numbers in a string with a defined character in PHP?

How would you replace all numbers in a string with a pre-defined character?

Replace each individual number with a dash "-".

```<code>$str = "John is 28 years old and donated $40.39!";
</code>```

Desired output:

```<code>"John is -- years old and donated $--.--!"
</code>```

I am assuming preg_replace() will be used but I am not sure how to target just numbers.

答:
Simple solution using strtr(to translate all digits) and str_repeat functions:

```<code>$str = "John is 28 years old and donated $40.39!";
$result = strtr($str, '0123456789', str_repeat('-', 10));

print_r($result);
</code>```

The output:

```<code>John is -- years old and donated $--.--!
</code>```

As alternative approach you may also use array_fill function(to create "replace_pairs"):

```<code>$str = "John is 28 years old and donated $40.39!";
$result = strtr($str, '0123456789', array_fill(0, 10, '-'));
</code>```

http://php.net/manual/en/function.strtr.php

ContentLicense: CC BY-SA 4.0

Body:
How would you replace all numbers in a string with a pre-defined character?

Replace each individual number with a dash "-".

$str = "John is 28 years old and donated $40.39!";

Desired output:

"John is -- years old and donated $--.--!"

I am assuming preg_replace() will be used but I am not sure how to target just numbers.

Body:
Simple solution using strtr(to translate all digits) and str_repeat functions:

$str = "John is 28 years old and donated $40.39!";
$result = strtr($str, '0123456789', str_repeat('-', 10));

print_r($result);

The output:

John is -- years old and donated $--.--!

As alternative approach you may also use array_fill function(to create "replace_pairs"):

$str = "John is 28 years old and donated $40.39!";
$result = strtr($str, '0123456789', array_fill(0, 10, '-'));

http://php.net/manual/en/function.strtr.php


问:
How to hide "duplicate" row values in SQL
I have a problem with SQL database in Serposcope. Basically what I'm trying to do is select all keywords with their rank and date. I managed to came up with something like this so far:

```<code>select keyword,
    rank,
    day
from GOOGLE_SEARCH
inner join GOOGLE_RANK on GOOGLE_SEARCH.id = GOOGLE_RANK.google_search_id
inner join RUN on GOOGLE_RANK.run_id = RUN.id
order by day;
</code>```

and it gives me this result:

```<code>+-----------+------+------------+
| keyword   | rank | day        |
+-----------+------+------------+
| keyword1  |    4 | 2017-04-01 |
| keyword1  |    4 | 2017-04-02 |
+-----------+------+------------+
</code>```

what I'm trying to do is to return in HTML something like this:

```<code>+-----------+------+------------+
| keyword   | rank | day        |
+-----------+------+------------+
| keyword1  |    4 | 2017-04-01 |
|           |    4 | 2017-04-02 |
+-----------+------+------------+
</code>```

so the keywords don't duplicate. Could you give me a hint if I can do this staight from SQL or I need to hide them in HTML/PHP? I'm not a dev so please forgive me if I asked a trivial question.

答:
First, you need to order them by the grouping row and then you can add other orderby columns:

```<code>order by keyword, day;
</code>```

second, you need to skip the similar elements in your loop:

```<code>if ($result = $mysqli->query($query)) {
    $last_keyword = null;
    // fetch associative array
    while ($row = $result->fetch_assoc()) {
        if($row["keyword"] != $last_keyword){
             // print the changed keyword
             echo $row["keyword"];
             // set the last keyword to the new keyword
             $last_keyword = $row["keyword"];
        }
        // do your other listings here
    }

    // free result set
    $result->free();
}
</code>```

Body:
I have a problem with SQL database in Serposcope. Basically what I'm trying to do is select all keywords with their rank and date. I managed to came up with something like this so far:

select keyword,
    rank,
    day
from GOOGLE_SEARCH
inner join GOOGLE_RANK on GOOGLE_SEARCH.id = GOOGLE_RANK.google_search_id
inner join RUN on GOOGLE_RANK.run_id = RUN.id
order by day;

and it gives me this result:

+-----------+------+------------+
| keyword   | rank | day        |
+-----------+------+------------+
| keyword1  |    4 | 2017-04-01 |
| keyword1  |    4 | 2017-04-02 |
+-----------+------+------------+

what I'm trying to do is to return in HTML something like this:

+-----------+------+------------+
| keyword   | rank | day        |
+-----------+------+------------+
| keyword1  |    4 | 2017-04-01 |
|           |    4 | 2017-04-02 |
+-----------+------+------------+

so the keywords don't duplicate. Could you give me a hint if I can do this staight from SQL or I need to hide them in HTML/PHP? I'm not a dev so please forgive me if I asked a trivial question.

Body:
First, you need to order them by the grouping row and then you can add other orderby columns:

order by keyword, day;

second, you need to skip the similar elements in your loop:

if ($result = $mysqli->query($query)) {
    $last_keyword = null;
    // fetch associative array
    while ($row = $result->fetch_assoc()) {
        if($row["keyword"] != $last_keyword){
             // print the changed keyword
             echo $row["keyword"];
             // set the last keyword to the new keyword
             $last_keyword = $row["keyword"];
        }
        // do your other listings here
    }

    // free result set
    $result->free();
}