问:
Converting a char to &str
I have a match statement which returns a &str:

```<code>match k {
    SP_KEY_1 => "KEY_1",
    SP_KEY_2 => "KEY_2",
    SP_KEY_3 => "KEY_3",
    SP_KEY_4 => "KEY_4",
    SP_KEY_5 => "KEY_5",
    SP_KEY_6 => "KEY_6",
    _ => (k as char), // I want to convert this to &str
}.as_bytes()
</code>```

I have tried to convert a char to a string first, and then taking a slice of that:

```<code>&(k as char).to_string()[..]
</code>```

But that gave me the lifetime error:

error[E0597]: borrowed value does not live long enough
```

Stating that (k as char).to_string()  is a temporary value, which makes sense as from what I can tell to_string() returns a clone.

I can add .to_string() to every &str literal above to make the return value String, but that seems both ugly (a lot of repeated code), and probably inefficient, as to_string() clones the original string slice.

The specific question is how would I make a char into a &str, but the broader question is that is there a better solution, what is commonly done this situation.

答:
Those are two very different things you want to treat in the same way: arrays of bytes known at compile time and a dynamically created array. They aren't allocated in the same area of memory and don't have the same lifetime. You can get away with a reference to a compile-time created array, because they live as long as the program, but you can't with a dynamically created one, since the reference won't last longer than the resource it borrows.

You may be better using only Strings:

```<code>match k {
    SP_KEY_1 => String::from("KEY_1"),
    ...
}
</code>```

than contorting. Keeping to &strs seems like premature optimization from where I stand.

Title: Converting a char to &str

Body:
I have a match statement which returns a &str:

match k {
    SP_KEY_1 => "KEY_1",
    SP_KEY_2 => "KEY_2",
    SP_KEY_3 => "KEY_3",
    SP_KEY_4 => "KEY_4",
    SP_KEY_5 => "KEY_5",
    SP_KEY_6 => "KEY_6",
    _ => (k as char), // I want to convert this to &str
}.as_bytes()

I have tried to convert a char to a string first, and then taking a slice of that:

&(k as char).to_string()[..]

But that gave me the lifetime error:

error[E0597]: borrowed value does not live long enough

Stating that (k as char).to_string()  is a temporary value, which makes sense as from what I can tell to_string() returns a clone.

I can add .to_string() to every &str literal above to make the return value String, but that seems both ugly (a lot of repeated code), and probably inefficient, as to_string() clones the original string slice.

The specific question is how would I make a char into a &str, but the broader question is that is there a better solution, what is commonly done this situation.

Body:
Those are two very different things you want to treat in the same way: arrays of bytes known at compile time and a dynamically created array. They aren't allocated in the same area of memory and don't have the same lifetime. You can get away with a reference to a compile-time created array, because they live as long as the program, but you can't with a dynamically created one, since the reference won't last longer than the resource it borrows.

You may be better using only Strings:

match k {
    SP_KEY_1 => String::from("KEY_1"),
    ...
}

than contorting. Keeping to &strs seems like premature optimization from where I stand.


来源: stackexchange

问:
PHP Remove Domain Name Extension from String
I was wondering of the best way of removing certain things from a domain using PHP.

For example:

"http://mydomain.com/" into "mydomain"

or

"http://mydomain.co.uk/" into "mydomain"

I'm looking for a quick function that will allow me to remove such things as:

"http://", "www.", ".com", ".co.uk", ".net", ".org", "/" etc

Thanks in advance :)

答:
Could you use string replace?

```<code>str_replace('http://', '');
</code>```

This would strip out 'http://' from a string. All you would have to do first is get the current url of the page and pass it through any string replace you wanted to..

ContentLicense: CC BY-SA 2.5

Body:
Could you use string replace?

str_replace('http://', '');

This would strip out 'http://' from a string. All you would have to do first is get the current url of the page and pass it through any string replace you wanted to..


问:
Rounding value of BigDecimal
I want to create a method that take two parameters. The first one is the amount (String) and the second is the Rounding type based on rounding type. It should round a value up or round down or so on...

```<code>public static String roundingAmount(String amount, String mode) {
    if (amount != null) {
        double dAmt = Double.parseDouble(amount);
        if (mode.equalsIgnoreCase("Rounded"))
            BigDecimal decimal = new BigDecimal(dAmt).setScale(0, RoundingMode.HALF_UP);
        else if (mode.equalsIgnoreCase("Round UP"))
            BigDecimal decimal = new BigDecimal(dAmt).setScale(0, RoundingMode.CEILING);
        else if (mode.equalsIgnoreCase("Round Down"))
            BigDecimal decimal = new BigDecimal(dAmt).setScale(0, RoundingMode.FLOOR);
        else if (mode.equalsIgnoreCase("NA")) {
            return amount;
        }
        String newNumber = String.format("%.2f", decimal.doubleValue());
        return newNumber;
    }
    return amount;
}
</code>```

It shows error decimal not found.
Can you help me?

答:
Expanding Alok's answer with the DRY principle (Don't Repeat Yourself):

```<code>public static String roundingAmount(String amount,String mode){
    RoundingMode roundingMode;
    if(amount!=null){
        if(mode.equalsIgnoreCase("Rounded"))
            roundingMode = RoundingMode.HALF_UP;
        else if(mode.equalsIgnoreCase("Round UP"))
            roundingMode = RoundingMode.CEILING;
        else if(mode.equalsIgnoreCase("Round Down"))
            roundingMode = RoundingMode.FLOOR;
        else if(mode.equalsIgnoreCase("NA"))
            return amount;
        else
            throw new IllegalArgumentException(mode + " is not an accepted mode");

        double dAmt=Double.parseDouble(amount);
        BigDecimal decimal = new BigDecimal(dAmt).setScale(0, roudingMode);
        String newNumber = String.format("%.2f" , decimal.doubleValue());
        return newNumber;
    }
    return amount;
}
</code>```

In order to improve this even more I would suggest passing the RoundingMode enum directly to the method instead of having to type it in the code itself. That would also enable using a switch statement instead of multipe String comparisons

ContentLicense: CC BY-SA 3.0

Title: Rounding value of BigDecimal

Body:
I want to create a method that take two parameters. The first one is the amount (String) and the second is the Rounding type based on rounding type. It should round a value up or round down or so on...

public static String roundingAmount(String amount, String mode) {
    if (amount != null) {
        double dAmt = Double.parseDouble(amount);
        if (mode.equalsIgnoreCase("Rounded"))
            BigDecimal decimal = new BigDecimal(dAmt).setScale(0, RoundingMode.HALF_UP);
        else if (mode.equalsIgnoreCase("Round UP"))
            BigDecimal decimal = new BigDecimal(dAmt).setScale(0, RoundingMode.CEILING);
        else if (mode.equalsIgnoreCase("Round Down"))
            BigDecimal decimal = new BigDecimal(dAmt).setScale(0, RoundingMode.FLOOR);
        else if (mode.equalsIgnoreCase("NA")) {
            return amount;
        }
        String newNumber = String.format("%.2f", decimal.doubleValue());
        return newNumber;
    }
    return amount;
}

It shows error decimal not found.
Can you help me?

Body:
Expanding Alok's answer with the DRY principle (Don't Repeat Yourself):

public static String roundingAmount(String amount,String mode){
    RoundingMode roundingMode;
    if(amount!=null){
        if(mode.equalsIgnoreCase("Rounded"))
            roundingMode = RoundingMode.HALF_UP;
        else if(mode.equalsIgnoreCase("Round UP"))
            roundingMode = RoundingMode.CEILING;
        else if(mode.equalsIgnoreCase("Round Down"))
            roundingMode = RoundingMode.FLOOR;
        else if(mode.equalsIgnoreCase("NA"))
            return amount;
        else
            throw new IllegalArgumentException(mode + " is not an accepted mode");

        double dAmt=Double.parseDouble(amount);
        BigDecimal decimal = new BigDecimal(dAmt).setScale(0, roudingMode);
        String newNumber = String.format("%.2f" , decimal.doubleValue());
        return newNumber;
    }
    return amount;
}

In order to improve this even more I would suggest passing the RoundingMode enum directly to the method instead of having to type it in the code itself. That would also enable using a switch statement instead of multipe String comparisons


问:
How to insert the q_auto in cloudinary url from variable in reactjs
I'm having trouble in inserting the "q_auto" in cloudinary variable. I will give some code.

```<code>let photoUrl = {
   url = https://res.cloudinary.com/demo/image/upload/w_600/beach_huts.jpg
}

let finalUrl = ..... some code;
</code>```

I want that in variable finalUrl is like has "q_auto", of course that's only example but lets just say that I don't know the url given my server.How can I do it ?

答:
I think this is what you are looking for.</p>

```<code>let photoUrl = {
   url: 'https://res.cloudinary.com/demo/image/upload/w_600/beach_huts.jpg'
};
let insertText = 'q_auto/';
let searchText = "res.cloudinary.com/demo/image/upload/";
let position = photoUrl.url.indexOf(searchText);
let insertPosition = position + searchText.length;
var output = [photoUrl.url.slice(0, insertPosition), insertText, photoUrl.url.slice(insertPosition)].join('');

console.log(output);  // https://res.cloudinary.com/demo/image/upload/q_auto/w_600/beach_huts.jpg
</code>```

Body:
I'm having trouble in inserting the "q_auto" in cloudinary variable. I will give some code.

let photoUrl = {
   url = https://res.cloudinary.com/demo/image/upload/w_600/beach_huts.jpg
}

let finalUrl = ..... some code;

I want that in variable finalUrl is like has "q_auto", of course that's only example but lets just say that I don't know the url given my server.How can I do it ?

Body:
I think this is what you are looking for.

let photoUrl = {
   url: 'https://res.cloudinary.com/demo/image/upload/w_600/beach_huts.jpg'
};
let insertText = 'q_auto/';
let searchText = "res.cloudinary.com/demo/image/upload/";
let position = photoUrl.url.indexOf(searchText);
let insertPosition = position + searchText.length;
var output = [photoUrl.url.slice(0, insertPosition), insertText, photoUrl.url.slice(insertPosition)].join('');

console.log(output);  // https://res.cloudinary.com/demo/image/upload/q_auto/w_600/beach_huts.jpg


问:
How to access the parent class inside a resource
I'm trying to create a complex tooltip, where one of the TextBlocks would be bound to a property of the UserControl in which this tooltip is defined as a resource. The simplified version of the XAML code looks like this:

```<code><UserControl x:Class="WpfApplication3.TestPage"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         xmlns:pixellab="clr-namespace:PixelLab.Wpf;assembly=UIControls"
         xmlns:my="clr-namespace:WpfApplication3"
         d:DesignHeight="499" d:DesignWidth="409"
         x:Name="PageInstance" >
<UserControl.Resources>
    <Grid x:Key="Tooltip">
        <TextBlock Text="{Binding ElementName=PageInstance, Path=PageTest}"/>
    </Grid>
</UserControl.Resources>
<Border Background="Red" ToolTip="{StaticResource Tooltip}" />
</code>```

UserControl is named PageInstance. The border displayed inside has a tooltip defined as a resource. If I try to bind Text with

```<code><TextBlock Text="{Binding ElementName=PageInstance, Path=PageTest}"/>
</code>```

I get a binding error when I run the app:

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=PageInstance'. BindingExpression:Path=PageTest; DataItem=null; target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')

What do I have to do to successfuly bind the text to the PageTest property in PageInstance usercontrol?

Thanks for any help. I still haven't completely figured out how Bindings work.
Gregor

答:
The Border will inherit the DataContext of the UserControl. Therefore modifying your tooltip as such...

```<code><Grid x:Key="Tooltip">
    <TextBlock Text="{Binding PageTest}"/>
</Grid>
</code>```

...and then setting the DataContext on your UserControl will push the model with the property PageTest down to your Border and subsequent children. This avoids the need to make use of FindAncestor in its entirety.

```<code>PageInstance.DataContext = model;
</code>```

Body:
I'm trying to create a complex tooltip, where one of the TextBlocks would be bound to a property of the UserControl in which this tooltip is defined as a resource. The simplified version of the XAML code looks like this:

<UserControl x:Class="WpfApplication3.TestPage"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         xmlns:pixellab="clr-namespace:PixelLab.Wpf;assembly=UIControls"
         xmlns:my="clr-namespace:WpfApplication3"
         d:DesignHeight="499" d:DesignWidth="409"
         x:Name="PageInstance" >
<UserControl.Resources>
    <Grid x:Key="Tooltip">
        <TextBlock Text="{Binding ElementName=PageInstance, Path=PageTest}"/>
    </Grid>
</UserControl.Resources>
<Border Background="Red" ToolTip="{StaticResource Tooltip}" />

UserControl is named PageInstance. The border displayed inside has a tooltip defined as a resource. If I try to bind Text with

<TextBlock Text="{Binding ElementName=PageInstance, Path=PageTest}"/>

I get a binding error when I run the app:

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=PageInstance'. BindingExpression:Path=PageTest; DataItem=null; target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')

What do I have to do to successfuly bind the text to the PageTest property in PageInstance usercontrol?

Thanks for any help. I still haven't completely figured out how Bindings work.
Gregor

Body:
The Border will inherit the DataContext of the UserControl. Therefore modifying your tooltip as such...

<Grid x:Key="Tooltip">
    <TextBlock Text="{Binding PageTest}"/>
</Grid>

...and then setting the DataContext on your UserControl will push the model with the property PageTest down to your Border and subsequent children. This avoids the need to make use of FindAncestor in its entirety.

PageInstance.DataContext = model;


问:
Why does this switch Statement not return anything when switching compilers from G++ to MSVC?
I was helping a friend with one of his C++ assignments and we found the following code snippet would throw exceptions in MSVC, but when compiling with G++, the exact same code would work fine. The exceptions were return because this function called getValue() wasn't returning anything.

```<code>string getValue(int value) {

    ostringstream convert;

    string rtnValue;

    switch (value) {
    case 11:
    {
        rtnValue = "J";
        break;
    }
    case 12:
    {
        rtnValue = "Q";
        break;
    }
    case 13:
    {
        rtnValue = "K";
        break;
    }
    case 14:
    {
        rtnValue = "A";
        break;
    }
    default:
    {
        //
        // if the value is a a number, we assume it is 2..10
        //
        convert << value;            // use a stream to convert the number
        rtnValue = convert.str();    // into a string
        if (value < 2 || value > 10)
        {
            rtnValue = "ERROR" + rtnValue + "ERROR";
        }
    }
    return rtnValue;
    }
}
</code>```

This program turns integers into strings. For the numbers 11-14 it uses switch statement (I know this isn't the best implementation but it's an introductory class).

We found that this could easily be solved by adding another return statement at the end.

```<code>string getValue(int value) {

    ostringstream convert;

    string rtnValue;

    switch (value) {
        case 11:
        {
            rtnValue = "J";
            break;
        }
        case 12:
        {
            rtnValue = "Q";
            break;
        }
        case 13:
        {
            rtnValue = "K";
            break;
        }
        case 14:
        {
            rtnValue = "A";
            break;
        }
        default:
        {
            //
            // if the value is a a number, we assume it is 2..10
            //
            convert << value;            // use a stream to convert the number
            rtnValue = convert.str();    // into a string
            if (value < 2 || value > 10)
            {
                rtnValue = "ERROR" + rtnValue + "ERROR";
            }
        }
        return rtnValue;
    }
    return rtnValue;
}
</code>```

And this now fixes it for MSVC (and I assume G++ if I checked).

Why did that fix work? Does MSVC and G++ treat parentheses differently with respect to switch statements?

答:
this is the problem

```<code> default:
{

    convert << value;            // use a stream to convert the number
    rtnValue = convert.str();    // into a string
    if (value < 2 || value > 10)
    {
        rtnValue = "ERROR" + rtnValue + "ERROR";
    }
}
return rtnValue;
}
</code>```

your return statement is in the wrong block, i.e , switch block.

what happens is that, when a case is satisfied it breaks out of the switch that is why it didn't return anything (because it is now out of switch statement).

In order to fix it you have to move your return statement to out of the switch statement to the end of the function.

This correction will we equivalent to the second code that you have provided.

But even in the second code remove the inner return statement.

Body:
I was helping a friend with one of his C++ assignments and we found the following code snippet would throw exceptions in MSVC, but when compiling with G++, the exact same code would work fine. The exceptions were return because this function called getValue() wasn't returning anything.

string getValue(int value) {

    ostringstream convert;

    string rtnValue;

    switch (value) {
    case 11:
    {
        rtnValue = "J";
        break;
    }
    case 12:
    {
        rtnValue = "Q";
        break;
    }
    case 13:
    {
        rtnValue = "K";
        break;
    }
    case 14:
    {
        rtnValue = "A";
        break;
    }
    default:
    {
        //
        // if the value is a a number, we assume it is 2..10
        //
        convert << value;            // use a stream to convert the number
        rtnValue = convert.str();    // into a string
        if (value < 2 || value > 10)
        {
            rtnValue = "ERROR" + rtnValue + "ERROR";
        }
    }
    return rtnValue;
    }
}

This program turns integers into strings. For the numbers 11-14 it uses switch statement (I know this isn't the best implementation but it's an introductory class).

We found that this could easily be solved by adding another return statement at the end.

string getValue(int value) {

    ostringstream convert;

    string rtnValue;

    switch (value) {
        case 11:
        {
            rtnValue = "J";
            break;
        }
        case 12:
        {
            rtnValue = "Q";
            break;
        }
        case 13:
        {
            rtnValue = "K";
            break;
        }
        case 14:
        {
            rtnValue = "A";
            break;
        }
        default:
        {
            //
            // if the value is a a number, we assume it is 2..10
            //
            convert << value;            // use a stream to convert the number
            rtnValue = convert.str();    // into a string
            if (value < 2 || value > 10)
            {
                rtnValue = "ERROR" + rtnValue + "ERROR";
            }
        }
        return rtnValue;
    }
    return rtnValue;
}

And this now fixes it for MSVC (and I assume G++ if I checked).

Why did that fix work? Does MSVC and G++ treat parentheses differently with respect to switch statements?

Body:
this is the problem

 default:
{

    convert << value;            // use a stream to convert the number
    rtnValue = convert.str();    // into a string
    if (value < 2 || value > 10)
    {
        rtnValue = "ERROR" + rtnValue + "ERROR";
    }
}
return rtnValue;
}

your return statement is in the wrong block, i.e , switch block.

what happens is that, when a case is satisfied it breaks out of the switch that is why it didn't return anything (because it is now out of switch statement).

In order to fix it you have to move your return statement to out of the switch statement to the end of the function.

This correction will we equivalent to the second code that you have provided.

But even in the second code remove the inner return statement.


问:
How do you find the average of a dictionary?
So let's say I have this dictionary

```<code>{'Taylor Swift': ['Kanye West']}
</code>```

I would expect 1.0 from this as there is one value (which is 'Kanye West') divided by one key (which is 'Taylor Swift') to get the average of 1.0.

And let's say I have this dictionary

```<code>{'Taylor Swift': ['Kanye West', 'Elvis Presley'], 'Adam Sandler': ['Johnny Depp', 'Tom Hanks']}
</code>```

I would expect the average of 2.0 from this as there are 4 values divided by 2 keys.

This is the code I have tried:

```<code>average = 0
sum = 0
for n in data:
    sum = sum + n
average = sum / len(data)
</code>```

I have tried many other ways too through online search and the common error I get is this:

```<code>TypeError: unsupported operand type(s) for +: 'int' and 'str'
</code>```

答:
Could use reduce here too:</p>

```<code>from functools import reduce
data = {'Taylor Swift': ['Kanye West', 'Elvis Presley'], 'Adam Sandler': ['Johnny Depp', 'Tom Hanks']}
reduce((lambda x, y: len(x)+len(y)), data .values()) / len(data )
</code>```

Body:
So let's say I have this dictionary

{'Taylor Swift': ['Kanye West']}

I would expect 1.0 from this as there is one value (which is 'Kanye West') divided by one key (which is 'Taylor Swift') to get the average of 1.0.

And let's say I have this dictionary

{'Taylor Swift': ['Kanye West', 'Elvis Presley'], 'Adam Sandler': ['Johnny Depp', 'Tom Hanks']}

I would expect the average of 2.0 from this as there are 4 values divided by 2 keys.

This is the code I have tried:

average = 0
sum = 0
for n in data:
    sum = sum + n
average = sum / len(data)

I have tried many other ways too through online search and the common error I get is this:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Body:
Could use reduce here too:

from functools import reduce
data = {'Taylor Swift': ['Kanye West', 'Elvis Presley'], 'Adam Sandler': ['Johnny Depp', 'Tom Hanks']}
reduce((lambda x, y: len(x)+len(y)), data .values()) / len(data )


问:
Gorm multiple Preloadings don't work
Good Monday Morning everyone!
I am having a problem with preloading entities! I am doing multiple preloadings of entities. The Countryentity is working fine, but the Report is not being preloaded. Any ideas what might be causing that?

```<code>type Review struct {
  ID             int
  Report   Report 'gorm:"ForeignKey:ReportId"'
  ReportId uint
  Country        Country      'gorm:"ForeignKey:CountryId"'
  CountryId      uint
}
func FindApprovedReviews(page int, countryId int) ([]Review, int, error) {
  var reviews [] Review

// Subtract one to fix Offset but keep page number correct
  page -= 1
  err := db.Where("approved_at IS NOT NULL").
//TODO: Change this to a configuration file value
      Limit(10).
      Where("approved_by IS NOT NULL").
      Where("country_id = ?", countryId).
//TODO: Change this (the 10) to a configuration value
      Offset(page * 10).
      Order("id desc").
      Preload("Report").
      Preload("Country").
      Find(&reviews).
      Error
  if err != nil {
      return nil, 0, err
  }

  return reviews, count, err
}
</code>```

The two related structs (Country and Report) are simply made up of gorm.Model for teting purpose.

Thanks in advance for the help!!

EDIT: I am using the mysql driver.

P.S. The [...] represent business data that has been hidden, but they are simple columns that are working fine.

答:
Just realised I was selecting queries where the relation (i.e. FK) with the Report table was null.

Works fine if the relation key is not null.

Title: Gorm multiple Preloadings don't work

Body:
Good Monday Morning everyone!
I am having a problem with preloading entities! I am doing multiple preloadings of entities. The Countryentity is working fine, but the Report is not being preloaded. Any ideas what might be causing that?

type Review struct {
  ID             int
  Report   Report 'gorm:"ForeignKey:ReportId"'
  ReportId uint
  Country        Country      'gorm:"ForeignKey:CountryId"'
  CountryId      uint
}
func FindApprovedReviews(page int, countryId int) ([]Review, int, error) {
  var reviews [] Review

// Subtract one to fix Offset but keep page number correct
  page -= 1
  err := db.Where("approved_at IS NOT NULL").
//TODO: Change this to a configuration file value
      Limit(10).
      Where("approved_by IS NOT NULL").
      Where("country_id = ?", countryId).
//TODO: Change this (the 10) to a configuration value
      Offset(page * 10).
      Order("id desc").
      Preload("Report").
      Preload("Country").
      Find(&reviews).
      Error
  if err != nil {
      return nil, 0, err
  }

  return reviews, count, err
}

The two related structs (Country and Report) are simply made up of gorm.Model for teting purpose.

Thanks in advance for the help!!

EDIT: I am using the mysql driver.

P.S. The [...] represent business data that has been hidden, but they are simple columns that are working fine.


问:
JS in Firefox: more than three digits after comma
I have an issue calculating a rate in a form. This is how it works well in Chrome:

$('body').on('change, keyup', 'input[data-rate]', function() {
    var val = parseFloat($(this).val().replace(',', '.'));
    window.console.log('val:'+val);
    if (val > 0) {
        var result = val * parseFloat($(this).data('rate'));
        var rate_id = $(this).data('rate-id');
        $('input[data-ratesum-id=' + rate_id + ']').val(number_format(result, 2, ',', '.'));
    }
});

/**
     * http://locutus.io/php/strings/number_format/
     * @param number
     * @param decimals
     * @param decPoint
     * @param thousandsSep
     */
    window.number_format = function (number, decimals, decPoint, thousandsSep) {
        number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
        var n = !isFinite(+number) ? 0 : +number;
        var prec = !isFinite(+decimals) ? 0 : Math.abs(decimals);
        var sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep;
        var dec = (typeof decPoint === 'undefined') ? '.' : decPoint;
        var s = '';
        var toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + (Math.round(n * k) / k)
                    .toFixed(prec)
        };
        // @todo: for IE parseFloat(0.55).toFixed(0) = 0;
        s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
        if (s[0].length > 3) {
            s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep)
        }
        if ((s[1] || '').length < prec) {
            s[1] = s[1] || '';
            s[1] += new Array(prec - s[1].length + 1).join('0')
        }
        return s.join(dec);
    };```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<input type="number" name="number[19]" class="form-control" data-rate="780.00" data-rate-id="19">
<input type="text" name="sum" data-ratesum-id="19" class="form-control" disabled=""></code>```

When I am typing in Chrome 15,625 (german way), then in console I see this:

```<code>val:1
val:15
val:15.6
val:15.62
val:15.625
</code>```

But when I do the same in FF, then I see this:

```<code>val:1
val:15
val:15.6
val:15.62
val:15625
</code>```

Now you can imagine, the result is beeing calculated wrong in Firefox. Chrome gives me the right answer 12187,50, in FF I get 12187500,00
With only 2 digits after comma it would be okay, but I need the third digit.
I don't know how to fix.

Thanks
Alex

答: Right answer is the type of the input field. Changing from type="number" to type="text" solved the issue.</p>

Body:
I have an issue calculating a rate in a form. This is how it works well in Chrome:

$('body').on('change, keyup', 'input[data-rate]', function() {
    var val = parseFloat($(this).val().replace(',', '.'));
    window.console.log('val:'+val);
    if (val > 0) {
        var result = val * parseFloat($(this).data('rate'));
        var rate_id = $(this).data('rate-id');
        $('input[data-ratesum-id=' + rate_id + ']').val(number_format(result, 2, ',', '.'));
    }
});

/**
     * http://locutus.io/php/strings/number_format/
     * @param number
     * @param decimals
     * @param decPoint
     * @param thousandsSep
     */
    window.number_format = function (number, decimals, decPoint, thousandsSep) {
        number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
        var n = !isFinite(+number) ? 0 : +number;
        var prec = !isFinite(+decimals) ? 0 : Math.abs(decimals);
        var sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep;
        var dec = (typeof decPoint === 'undefined') ? '.' : decPoint;
        var s = '';
        var toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + (Math.round(n * k) / k)
                    .toFixed(prec)
        };
        // @todo: for IE parseFloat(0.55).toFixed(0) = 0;
        s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
        if (s[0].length > 3) {
            s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep)
        }
        if ((s[1] || '').length < prec) {
            s[1] = s[1] || '';
            s[1] += new Array(prec - s[1].length + 1).join('0')
        }
        return s.join(dec);
    };

<input type="number" name="number[19]" class="form-control" data-rate="780.00" data-rate-id="19">
<input type="text" name="sum" data-ratesum-id="19" class="form-control" disabled="">

When I am typing in Chrome 15,625 (german way), then in console I see this:

val:1
val:15
val:15.6
val:15.62
val:15.625

But when I do the same in FF, then I see this:

val:1
val:15
val:15.6
val:15.62
val:15625

Now you can imagine, the result is beeing calculated wrong in Firefox. Chrome gives me the right answer 12187,50, in FF I get 12187500,00
With only 2 digits after comma it would be okay, but I need the third digit.
I don't know how to fix.

Thanks
Alex


问:
persistence.xml file is not in the classpath
So I am trying to build an adminsystem in Eclipse with Maven using Wildfly, JPA, Hibernate and MariaDB. I configured my data source in the WildFly administration console and everything is fine.
Succesful connection picture in WildFly
Now I am trying to write into the database with Entity Manager Factory in Eclipse from the project. But I've got this error message:
Error message in Eclipse
Here you can see my project tree:
Project tree

Here is my pom:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.gyurmatag.adminsystem</groupId>
<artifactId>adminsystem</artifactId>
<version>1.0</version>
<packaging>war</packaging>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>

    <servlet.version>3.1.0</servlet.version>
    <jsf.version>2.2.12</jsf.version>
    <primefaces.version>5.3</primefaces.version>

    <version.wildfly>9.0.2.Final</version.wildfly>
    <jboss.home>${project.build.directory}/wildfly-${version.wildfly}
    </jboss.home>
    <server.config>standalone.xml</server.config>

    <maven-compiler-plugin.version>3.3</maven-compiler-plugin.version>
    <maven-dependency-plugin>2.10</maven-dependency-plugin>
    <maven-resources-plugin.version>2.7</maven-resources-plugin.version>
    <wildfly-maven-plugin.version>1.1.0.Alpha5</wildfly-maven-plugin.version>
</properties>

<dependencies>
    <!-- Servlet -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>${servlet.version}</version>
        <scope>provided</scope>
    </dependency>
    <!-- JSF -->
    <dependency>
        <groupId>com.sun.faces</groupId>
        <artifactId>jsf-api</artifactId>
        <version>${jsf.version}</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>com.sun.faces</groupId>
        <artifactId>jsf-impl</artifactId>
        <version>${jsf.version}</version>
        <scope>compile</scope>
    </dependency>
    <!-- PrimeFaces -->
    <dependency>
        <groupId>org.primefaces</groupId>
        <artifactId>primefaces</artifactId>
        <version>${primefaces.version}</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-
client -->
    <dependency>
        <groupId>org.mariadb.jdbc</groupId>
        <artifactId>mariadb-java-client</artifactId>
        <version>2.2.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.12.Final</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.1-api</artifactId>
        <version>1.0.0.Final</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-
entitymanager -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.2.12.Final</version>
    </dependency>

</dependencies>

<build>
<pluginManagement>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>${maven-compiler-plugin.version}</version>
            <configuration>
                <source>${java.version}</source>
                <target>${java.version}</target>
            </configuration>
        </plugin>
        <!-- Unpack the distribution -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>${maven-resources-plugin.version}</version>
            <executions>
                <execution>
                    <id>unpack-wildfly</id>
                    <phase>generate-sources</phase>
                    <goals>
                        <goal>unpack</goal>
                    </goals>
                    <configuration>
                        <artifactItems>
                            <artifactItem>
                                <groupId>org.wildfly</groupId>
                                <artifactId>wildfly-dist</artifactId>
                                <version>${version.wildfly}</version>
                                <type>zip</type>
                                <overWrite>false</overWrite>
                                <outputDirectory>${project.build.directory}
</outputDirectory>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <!-- Copy server configuration -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <version>${maven-resources-plugin.version}</version>
            <executions>
                <execution>
                    <id>copy-standalone-xml</id>
                    <phase>generate-sources</phase>
                    <goals>
                        <goal>copy-resources</goal>
                    </goals>
                    <configuration>

<outputDirectory>${jboss.home}/standalone/configuration</outputDirectory>
                        <resources>
                            <resource>
                                <directory>src/main/resources</directory>
                            </resource>
                        </resources>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <!-- Maven WildFly plugin -->
        <plugin>
            <groupId>org.wildfly.plugins</groupId>
            <artifactId>wildfly-maven-plugin</artifactId>
            <version>${wildfly-maven-plugin.version}</version>
            <configuration>
                <jbossHome>${jboss.home}</jbossHome>
                <serverConfig>${server.config}</serverConfig>
            </configuration>
        </plugin>
    </plugins>
    </pluginManagement>
</build>
</code>```

Here is my persistance.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
         version="2.0">

           <persistence-unit name="adminsystem" transaction-type="JTA">
           <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

               <jta-data-source>jboss/MariaDBDS</jta-data-source>

               <properties>
                     <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
                     <property name="hibernate.hbm2ddl.auto" value="validate" />
                     <property name="hibernate.show_sql" value="true" />
                     <property name="hibernate.format_sql" value="true" />
                     <property name="hibernate.connection.release_mode" value="auto" />
               </properties>
           </persistence-unit>
</code>```

Here is my JPAUtility class:

```<code>package com.gyurmatag.adminsystem.model;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class JPAUtility {
private static final EntityManagerFactory emFactory;
static {
       emFactory = Persistence.createEntityManagerFactory("adminsystem");
}
public static EntityManager getEntityManager(){
    return emFactory.createEntityManager();
}
public static void close(){
    emFactory.close();
}
}
</code>```

If you want to take a more closer look to my project, you can find it here: Bitbucket repo

Can you help me with this?

Thank you very much! :)

答:
I suspect that you have the all too common "too many dependencies error".

Replace all of your dependencies with:

```<code><dependencies>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>7.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.primefaces</groupId>
        <artifactId>primefaces</artifactId>
        <version>${primefaces.version}</version>
    </dependency>
</dependencies>
</code>```

and see how you go...

Body:
So I am trying to build an adminsystem in Eclipse with Maven using Wildfly, JPA, Hibernate and MariaDB. I configured my data source in the WildFly administration console and everything is fine.
Succesful connection picture in WildFly
Now I am trying to write into the database with Entity Manager Factory in Eclipse from the project. But I've got this error message:
Error message in Eclipse
Here you can see my project tree:
Project tree

Here is my pom:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.gyurmatag.adminsystem</groupId>
<artifactId>adminsystem</artifactId>
<version>1.0</version>
<packaging>war</packaging>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>

    <servlet.version>3.1.0</servlet.version>
    <jsf.version>2.2.12</jsf.version>
    <primefaces.version>5.3</primefaces.version>

    <version.wildfly>9.0.2.Final</version.wildfly>
    <jboss.home>${project.build.directory}/wildfly-${version.wildfly}
    </jboss.home>
    <server.config>standalone.xml</server.config>

    <maven-compiler-plugin.version>3.3</maven-compiler-plugin.version>
    <maven-dependency-plugin>2.10</maven-dependency-plugin>
    <maven-resources-plugin.version>2.7</maven-resources-plugin.version>
    <wildfly-maven-plugin.version>1.1.0.Alpha5</wildfly-maven-plugin.version>
</properties>

<dependencies>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>${servlet.version}</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>com.sun.faces</groupId>
        <artifactId>jsf-api</artifactId>
        <version>${jsf.version}</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>com.sun.faces</groupId>
        <artifactId>jsf-impl</artifactId>
        <version>${jsf.version}</version>
        <scope>compile</scope>
    </dependency>

    <dependency>
        <groupId>org.primefaces</groupId>
        <artifactId>primefaces</artifactId>
        <version>${primefaces.version}</version>
    </dependency>

    <dependency>
        <groupId>org.mariadb.jdbc</groupId>
        <artifactId>mariadb-java-client</artifactId>
        <version>2.2.0</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.12.Final</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.1-api</artifactId>
        <version>1.0.0.Final</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.2.12.Final</version>
    </dependency>

</dependencies>

<build>
<pluginManagement>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>${maven-compiler-plugin.version}</version>
            <configuration>
                <source>${java.version}</source>
                <target>${java.version}</target>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>${maven-resources-plugin.version}</version>
            <executions>
                <execution>
                    <id>unpack-wildfly</id>
                    <phase>generate-sources</phase>
                    <goals>
                        <goal>unpack</goal>
                    </goals>
                    <configuration>
                        <artifactItems>
                            <artifactItem>
                                <groupId>org.wildfly</groupId>
                                <artifactId>wildfly-dist</artifactId>
                                <version>${version.wildfly}</version>
                                <type>zip</type>
                                <overWrite>false</overWrite>
                                <outputDirectory>${project.build.directory}
</outputDirectory>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <version>${maven-resources-plugin.version}</version>
            <executions>
                <execution>
                    <id>copy-standalone-xml</id>
                    <phase>generate-sources</phase>
                    <goals>
                        <goal>copy-resources</goal>
                    </goals>
                    <configuration>

<outputDirectory>${jboss.home}/standalone/configuration</outputDirectory>
                        <resources>
                            <resource>
                                <directory>src/main/resources</directory>
                            </resource>
                        </resources>
                    </configuration>
                </execution>
            </executions>
        </plugin>

        <plugin>
            <groupId>org.wildfly.plugins</groupId>
            <artifactId>wildfly-maven-plugin</artifactId>
            <version>${wildfly-maven-plugin.version}</version>
            <configuration>
                <jbossHome>${jboss.home}</jbossHome>
                <serverConfig>${server.config}</serverConfig>
            </configuration>
        </plugin>
    </plugins>
    </pluginManagement>
</build>

Here is my persistance.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
         version="2.0">

           <persistence-unit name="adminsystem" transaction-type="JTA">
           <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

               <jta-data-source>jboss/MariaDBDS</jta-data-source>

               <properties>
                     <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
                     <property name="hibernate.hbm2ddl.auto" value="validate" />
                     <property name="hibernate.show_sql" value="true" />
                     <property name="hibernate.format_sql" value="true" />
                     <property name="hibernate.connection.release_mode" value="auto" />
               </properties>
           </persistence-unit>

Here is my JPAUtility class:

package com.gyurmatag.adminsystem.model;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class JPAUtility {
private static final EntityManagerFactory emFactory;
static {
       emFactory = Persistence.createEntityManagerFactory("adminsystem");
}
public static EntityManager getEntityManager(){
    return emFactory.createEntityManager();
}
public static void close(){
    emFactory.close();
}
}

If you want to take a more closer look to my project, you can find it here: Bitbucket repo

Can you help me with this?

Thank you very much! :)

Body:
I suspect that you have the all too common "too many dependencies error".

Replace all of your dependencies with:

<dependencies>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>7.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.primefaces</groupId>
        <artifactId>primefaces</artifactId>
        <version>${primefaces.version}</version>
    </dependency>
</dependencies>

and see how you go...


问:
Re-loading the controller after Navigation ( SAP UI 5)
I have a UI5 Application with (JS View)  a  few pages & navigation between them.  I am  using  mutual oModels for transfering data ( For example I am choosing some item on 2. page and I am showing the choosen items on 3. page etc.)

My problem is  after navigation the Controller will be loaded only once.  And I can't update my Models which means my View won't show the latest  datas that I've added to oModel .

Is there anyway for me to handle this problem ? How can I manage to  reload my Controllers ( onInit lifecycle function etc. )

PS:  oModel.refresh(true) on navigation function doesn't do what I need-

If you need to see my code I can add the relevant part

答:
The onInit lifecycle function is only supposed to run once.
If your goal is to run some logic every time you enter one of your screens, you should implement a RoutePatternMatched event handler in your controllers.

Use sap.ui.core.UIComponent.getRouterFor(this); to get your router instance and call the function attachRoutePatternMatched to attach your event. You can look into https://openui5.hana.ondemand.com/#/api/sap.m.routing.Router for more details.


问:
React Native cant log specific part

Okay i got a kind of special problem just with react native i think

Here is the code

       login(){
    fetch('http://52.28.212.104:8081/milltimeLogin', {
            method: 'POST',
            headers: {
                'Authorization':"basic " + this.state.username + ":" + this.state.passw ,
            },
    }).then(response => response.text())
          .then(text => {
            console.log(text['mta:loginResponse']);

          })
}
```

this exact log works in reactjs but not in react native the reason that i have the ['mta:...'] is that the response has the mta: tags so i have to use [''] but i doesnt seem to work in react native. if i just log text i get the whole response but i need to get specific parts of it. Anyone know how to do this in react native?

答:
I think you can make it work this way, read it as json object except of text.

login(){
  fetch('http://52.28.212.104:8081/milltimeLogin', {
    method: 'POST',
    headers: {
      'Authorization':"basic " + this.state.username + ":" + this.state.passw ,
    },
}).then(response => response.json())
    .then(json => {
      console.log(json['mta:loginResponse']);
    })
}
```

Title: React Native cant log specific part

Body:
Okay i got a kind of special problem just with react native i think

Here is the code

       login(){
    fetch('http://52.28.212.104:8081/milltimeLogin', {
            method: 'POST',
            headers: {
                'Authorization':"basic " + this.state.username + ":" + this.state.passw ,
            },
    }).then(response => response.text())
          .then(text => {
            console.log(text['mta:loginResponse']);

          })
}

this exact log works in reactjs but not in react native the reason that i have the ['mta:...'] is that the response has the mta: tags so i have to use [''] but i doesnt seem to work in react native. if i just log text i get the whole response but i need to get specific parts of it. Anyone know how to do this in react native?


问:
Trying to load new view upon orientation change
I am trying to create an application in Xcode that will switch to a new view when the phone is rotated from one orientation to another.

Here is the "switchviewcontroller.h" file code:

```<code>#import <UIKit/UIKit.h>

@interface SwitchViewController : UIViewController {

}

-(IBAction)switchview:(id)sender;

@end
</code>```

And here is the "switchviewcontroller.m" file code:

```<code>#import "SwitchViewController.h"
#import "secondview.h"

@implementation SwitchViewController

-(IBAction)switchview:(id)sender {}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return YES;
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    if((fromInterfaceOrientation == UIInterfaceOrientationLandscapeLeft) ||
       (fromInterfaceOrientation == UIInterfaceOrientationLandscapeRight))
    {
        [[secondview alloc] initWithNibName:@"secondview" bundle:[NSBundle mainBundle]];
    }

}
</code>```

It runs in iPhone simulator with no errors, but, when I rotate it doesn't load the new view. For starters I think I need the app to open in landscape mode, which I don't know how to do, but it still wouldn't work anyway and I think it has something to to with the "initWithNibName" part of the code because I have .xib files and not .nib files. Can anyone help me with these 2 things? Thanks.

答:
You are not pushing or presenting anything, you are only init'ing the view.

```<code>secondview *second = [[secondview alloc] initWithNibName:@"secondview" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:second animated:YES];
</code>```

However, its not a good place to show a new view.

If you want to show the same view in a different orientation, try something this:

```<code>- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    if(((interfaceOrientation == UIInterfaceOrientationLandscapeLeft) ||
        (interfaceOrientation == UIInterfaceOrientationLandscapeRight))){

        self.view = landscape;

    }else if(((interfaceOrientation == UIInterfaceOrientationPortrait) ||
              (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown))){

        self.view = portrait;

    }

    return YES;
}
</code>```

Note that portrait and landscape are UIViews in your UIViewController that you define in your header and connect through Interface Builder.

Additionaly, these need to be in .h / .m:

.h

```<code>IBOutlet UIView *portrait;
IBOutlet UIView *landscape;

@property(nonatomic,retain) UIView portrait;
@property(nonatomic,retain) UIView landscape;
</code>```

.m

```<code>@synthesize portrait,landscape;
</code>```

Body:
I am trying to create an application in Xcode that will switch to a new view when the phone is rotated from one orientation to another.

Here is the "switchviewcontroller.h" file code:

#import <UIKit/UIKit.h>

@interface SwitchViewController : UIViewController {

}

-(IBAction)switchview:(id)sender;

@end

And here is the "switchviewcontroller.m" file code:

#import "SwitchViewController.h"
#import "secondview.h"

@implementation SwitchViewController

-(IBAction)switchview:(id)sender {}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return YES;
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    if((fromInterfaceOrientation == UIInterfaceOrientationLandscapeLeft) ||
       (fromInterfaceOrientation == UIInterfaceOrientationLandscapeRight))
    {
        [[secondview alloc] initWithNibName:@"secondview" bundle:[NSBundle mainBundle]];
    }

}

It runs in iPhone simulator with no errors, but, when I rotate it doesn't load the new view. For starters I think I need the app to open in landscape mode, which I don't know how to do, but it still wouldn't work anyway and I think it has something to to with the "initWithNibName" part of the code because I have .xib files and not .nib files. Can anyone help me with these 2 things? Thanks.

Body:
You are not pushing or presenting anything, you are only init'ing the view.

secondview *second = [[secondview alloc] initWithNibName:@"secondview" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:second animated:YES];

However, its not a good place to show a new view.

If you want to show the same view in a different orientation, try something this:

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    if(((interfaceOrientation == UIInterfaceOrientationLandscapeLeft) ||
        (interfaceOrientation == UIInterfaceOrientationLandscapeRight))){

        self.view = landscape;

    }else if(((interfaceOrientation == UIInterfaceOrientationPortrait) ||
              (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown))){

        self.view = portrait;

    }

    return YES;
}

Note that portrait and landscape are UIViews in your UIViewController that you define in your header and connect through Interface Builder.

Additionaly, these need to be in .h / .m:

.h

IBOutlet UIView *portrait;
IBOutlet UIView *landscape;

@property(nonatomic,retain) UIView portrait;
@property(nonatomic,retain) UIView landscape;

.m

@synthesize portrait,landscape;


问:
Cannot send Email in codeigniter
I'm using codeigniter email library to send mail. The following is my email.php library file configuration

```<code>public $useragent   = 'CodeIgniter';

public $mailpath    = '/usr/sbin/sendmail'; // Sendmail path

public $protocol    = 'smtp';       // mail/sendmail/smtp

public $smtp_host   = 'smtp.mailhostbox.com';

public $smtp_user   = 'myemailid';

public $smtp_pass   = 'mypassword';

public $smtp_port   = 25;

public $smtp_timeout    = 5;

public $smtp_keepalive  = FALSE;

public $smtp_crypto = '';

public $wordwrap    = TRUE;

public $wrapchars   = 76;

public $mailtype    = 'html';

public $charset     = 'iso-8859-1';
</code>```

and here is my send email function in controller:

```<code>$message = '<div>test</div>';
$this->email->message($message);
$this->email->to(ADMIN_EMAIL);
$this->email->from($email, $userName); // if $email = 'myemailid', then its working

$this->email->subject('SenderID Request');
if($path != '')
     $this->email->attach(USER_PROFILE_PATH.$path);
if($this->email->send()){
    $result = $this->User_model->senderIDStatus($senderIDID, 3);
    if($result == 1) {

         $this->session->set_flashdata('Status','success');
         $this->session->set_flashdata('Message','SenderID submitted for approval, we will notify you soon');
    }
    else {
       $this->session->set_flashdata('Status','failure');
       $this->session->set_flashdata('Message', 'An error occured, please try again');
    }
}
else {
    print_r($this->email->print_debugger());
}
</code>```

I can send email if, $this->email->from() is myemailid, which is set in email library. If I tried to send email from another email id it shows an error like
The following SMTP error was encountered: 553 5.7.1 : Sender address rejected: not owned by user myemailid

答: The mail server is rejecting your email because you're trying to send from a username which differs from the username you're logging in as, e.g. you've set the From: to be no-reply@mydomain.com, which is obviously not the same as myemailid

Title: Cannot send Email in codeigniter

Body:
I'm using codeigniter email library to send mail. The following is my email.php library file configuration

public $useragent   = 'CodeIgniter';

public $mailpath    = '/usr/sbin/sendmail'; // Sendmail path

public $protocol    = 'smtp';       // mail/sendmail/smtp

public $smtp_host   = 'smtp.mailhostbox.com';

public $smtp_user   = 'myemailid';

public $smtp_pass   = 'mypassword';

public $smtp_port   = 25;

public $smtp_timeout    = 5;

public $smtp_keepalive  = FALSE;

public $smtp_crypto = '';

public $wordwrap    = TRUE;

public $wrapchars   = 76;

public $mailtype    = 'html';

public $charset     = 'iso-8859-1';

and here is my send email function in controller:

$message = '
test
';
$this->email->message($message);
$this->email->to(ADMIN_EMAIL);
$this->email->from($email, $userName); // if $email = 'myemailid', then its working

$this->email->subject('SenderID Request');
if($path != '')
     $this->email->attach(USER_PROFILE_PATH.$path);
if($this->email->send()){
    $result = $this->User_model->senderIDStatus($senderIDID, 3);
    if($result == 1) {

         $this->session->set_flashdata('Status','success');
         $this->session->set_flashdata('Message','SenderID submitted for approval, we will notify you soon');
    }
    else {
       $this->session->set_flashdata('Status','failure');
       $this->session->set_flashdata('Message', 'An error occured, please try again');
    }
}
else {
    print_r($this->email->print_debugger());
}

I can send email if, $this->email->from() is myemailid, which is set in email library. If I tried to send email from another email id it shows an error like
The following SMTP error was encountered: 553 5.7.1 : Sender address rejected: not owned by user myemailid


问:
ReadAsAsync deserializing HttpResponseMessage result
This queston may possible duplicated but I am calling a service as the following below :

```<code>   HttpClient httpClinet = new HttpClient();
   httpClinet.DefaultRequestHeaders.Accept.Clear();
   httpClinet.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
   var str = "XrayService.asmx/GetOrdData?" + string.Format("ordId={0}&code={1}", range.ordId, range.code);
   HttpResponseMessage response;
   httpClinet.BaseAddress = new Uri("http://172.16.203.27:6043/");
   response = httpClinet.GetAsync(str).Result;
   if (response.IsSuccessStatusCode)
         var caseInfos = response.Content.ReadAsAsync<IEnumerable<PI>>().Result;//Here is exception
</code>```

everything is going fine, but when I want to run ReadAsAsync I got the exception as below:

Error:System.AggregateException: One or more errors occurred. ---> System.AggregateException: One or more errors occurred. ---> System.Runtime.Serialization.SerializationException: Error in line 1 position 5. Expecting element 'ArrayOfPI' from namespace 'http://schemas.datacontract.org/2004/07/SATA_DTOs'.. Encountered 'Element'  with name 'PI', namespace ''.
     at System.Runtime.Serialization.DataContractSerializer.InternalReadObject(XmlReaderDelegator xmlReader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
     at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
     at System.Runtime.Serialization.DataContractSerializer.ReadObject(XmlReader reader)
     at System.Net.Http.Formatting.XmlMediaTypeFormatter.ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
     at System.Net.Http.Formatting.XmlMediaTypeFormatter.ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
  --- End of stack trace from previous location where exception was thrown ---

I am testing that service by Google Advanced Rest Client and see the result as :

Status : 200 OK

Response Header:

```<code>cache-control: private, max-age=0
content-length: 360
content-type: text/xml; charset=utf-8
server:Microsoft-IIS/8.5
x-aspnet-version:4.0.30319
x-powered-by: ASP.NET
date: Sun, 03 Dec 2017 08:37:21 GMT
</code>```

and OutPut :

```<code><?xml version="1.0" encoding="utf-8" ?>
<PI>
<ordId>950177248</ordId>
<fnm>بهسا</fnm>
<lnm>حسنی</lnm>
<fthNm>علی</fthNm>
<pId>p2535154</pId>
<sex>F</sex>
<brthD>2003-02-05</brthD>
<addrs />
<nId>0025351540</nId>
<srvNm>|دندان بصورت پانورک</srvNm>
<rfrPhy>مهرزاد اميري-41853</rfrPhy>
 </PI>
</code>```

I also decorated DTO like :

```<code>namespace SATA_DTOs
{
    [DataContract(Name = "PI")]
    public class PI
    {
        [DataMember] public string ordId { get; set; }
        [DataMember] public string fnm { get; set; }
        [DataMember] public string lnm { get; set; }
        [DataMember] public string fthNm { get; set; }
        [DataMember] public string pId { get; set; }
        [DataMember] public string sex { get; set; }
        [DataMember] public string brthD { get; set; }
        [DataMember] public string addrs { get; set; }
        [DataMember] public string nId { get; set; }
        [DataMember] public string srvNm { get; set; }
        [DataMember] public string rfrPhy { get; set; }
    }
}
</code>```

UPDATE:

Just as another try I want to get the result here either JSON or XML but this is also does not make difference:

```<code>List<PI> model = null;
var client = new HttpClient();
var task = client.GetAsync(httpClinet.BaseAddress.ToString() + str)
      .ContinueWith((taskwithresponse) =>
       {
           var response1 = taskwithresponse.Result;
           var jsonString = response1.Content.ReadAsStringAsync();
                  m_Logging.Log(SharedLib.LoggingMode.Prompt, "JSON string created {0}...", jsonString);
           jsonString.Wait();
           model = Newtonsoft.Json.JsonConvert.DeserializeObject<List<PI>>(jsonString.Result);
        });
task.Wait();
</code>```

答:
After many copy pasting patch on server and improving the log I finally resolve the problem,

As the last try which @NKosi suggested with little changes:

```<code>var response1 = httpClinet.GetAsync(str).Result;
IEnumerable<PI> caseInfos1 = Enumerable.Empty<PI>();
try
{
    caseInfos1 = response1.Content.ReadAsAsync<IEnumerable<PI>>().Result;
}
catch (Exception ex)
{
    try
    {
        m_Logging.Log(SharedLib.LoggingMode.Error, "IEnumerable failed, EXP:{0}", ex);
        var singleObject = response1.Content.ReadAsAsync<PI>().Result;
        if (singleObject != null)
        {
            m_Logging.Log(SharedLib.LoggingMode.Error, "singleObject succeeded...");
            caseInfos1 = new[] { singleObject };
        }
    }
    catch (Exception exp)
    {
        m_Logging.Log(SharedLib.LoggingMode.Error, "singleObject failed, EXP:{0}", exp);
    }
}
</code>```

I crossed with the below exception also:

System.Runtime.Serialization.SerializationException: Error in line 1 position 5. Expecting element 'ArrayOfPI' from namespace 'http://schemas.datacontract.org/2004/07/SATA_DTOs'.. Encountered 'Element'  with name 'PI', namespace ''....

.....

as the exception mentioned it can't be able to deserialize the result I guessed the out put type may is text/html not text/xml although Rest Client Tester specified it as text/xml,

for this reason I came to this conclusion to use ReadAsStringAsync and deserialize it to PI, so by the below snipped code I finally get the result:

```<code>PI caseInfos = null;
try
{
    string strasd = response.Content.ReadAsStringAsync().Result;
    m_Logging.Log(SharedLib.LoggingMode.Prompt, "ReadAsStringAsync() result:{0}", strasd);
    System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(PI));
    using (TextReader reader = new StringReader(strasd))
        caseInfos = (PI)serializer.Deserialize(reader);
    m_Logging.Log(SharedLib.LoggingMode.Prompt, "Deserializing caseInfos model succeeded...");
}
catch (Exception ex)
{
    m_Logging.Log(SharedLib.LoggingMode.Error, "creating model failed, EXP:{0}", ex);
}
</code>```

I appreciate all crossed this question especially those who shared his/her knowledge in this discussion!!!

Body:
This queston may possible duplicated but I am calling a service as the following below :

   HttpClient httpClinet = new HttpClient();
   httpClinet.DefaultRequestHeaders.Accept.Clear();
   httpClinet.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
   var str = "XrayService.asmx/GetOrdData?" + string.Format("ordId={0}&code={1}", range.ordId, range.code);
   HttpResponseMessage response;
   httpClinet.BaseAddress = new Uri("http://172.16.203.27:6043/");
   response = httpClinet.GetAsync(str).Result;
   if (response.IsSuccessStatusCode)
         var caseInfos = response.Content.ReadAsAsync<IEnumerable<PI>>().Result;//Here is exception

everything is going fine, but when I want to run ReadAsAsync I got the exception as below:

Error:System.AggregateException: One or more errors occurred. ---> System.AggregateException: One or more errors occurred. ---> System.Runtime.Serialization.SerializationException: Error in line 1 position 5. Expecting element 'ArrayOfPI' from namespace 'http://schemas.datacontract.org/2004/07/SATA_DTOs'.. Encountered 'Element'  with name 'PI', namespace ''.
     at System.Runtime.Serialization.DataContractSerializer.InternalReadObject(XmlReaderDelegator xmlReader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
     at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
     at System.Runtime.Serialization.DataContractSerializer.ReadObject(XmlReader reader)
     at System.Net.Http.Formatting.XmlMediaTypeFormatter.ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
     at System.Net.Http.Formatting.XmlMediaTypeFormatter.ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
  --- End of stack trace from previous location where exception was thrown ---

I am testing that service by Google Advanced Rest Client and see the result as :

Status : 200 OK

Response Header:

cache-control: private, max-age=0
content-length: 360
content-type: text/xml; charset=utf-8
server:Microsoft-IIS/8.5
x-aspnet-version:4.0.30319
x-powered-by: ASP.NET
date: Sun, 03 Dec 2017 08:37:21 GMT

and OutPut :

<?xml version="1.0" encoding="utf-8" ?>
<PI>
<ordId>950177248</ordId>
<fnm>بهسا</fnm>
<lnm>حسنی</lnm>
<fthNm>علی</fthNm>
<pId>p2535154</pId>
<sex>F</sex>
<brthD>2003-02-05</brthD>
<addrs />
<nId>0025351540</nId>
<srvNm>|دندان بصورت پانورک</srvNm>
<rfrPhy>مهرزاد اميري-41853</rfrPhy>
 </PI>

I also decorated DTO like :

namespace SATA_DTOs
{
    [DataContract(Name = "PI")]
    public class PI
    {
        [DataMember] public string ordId { get; set; }
        [DataMember] public string fnm { get; set; }
        [DataMember] public string lnm { get; set; }
        [DataMember] public string fthNm { get; set; }
        [DataMember] public string pId { get; set; }
        [DataMember] public string sex { get; set; }
        [DataMember] public string brthD { get; set; }
        [DataMember] public string addrs { get; set; }
        [DataMember] public string nId { get; set; }
        [DataMember] public string srvNm { get; set; }
        [DataMember] public string rfrPhy { get; set; }
    }
}

UPDATE:

Just as another try I want to get the result here either JSON or XML but this is also does not make difference:

List<PI> model = null;
var client = new HttpClient();
var task = client.GetAsync(httpClinet.BaseAddress.ToString() + str)
      .ContinueWith((taskwithresponse) =>
       {
           var response1 = taskwithresponse.Result;
           var jsonString = response1.Content.ReadAsStringAsync();
                  m_Logging.Log(SharedLib.LoggingMode.Prompt, "JSON string created {0}...", jsonString);
           jsonString.Wait();
           model = Newtonsoft.Json.JsonConvert.DeserializeObject<List<PI>>(jsonString.Result);
        });
task.Wait();

Body:
After many copy pasting patch on server and improving the log I finally resolve the problem,

As the last try which @NKosi suggested with little changes:

var response1 = httpClinet.GetAsync(str).Result;
IEnumerable<PI> caseInfos1 = Enumerable.Empty<PI>();
try
{
    caseInfos1 = response1.Content.ReadAsAsync<IEnumerable<PI>>().Result;
}
catch (Exception ex)
{
    try
    {
        m_Logging.Log(SharedLib.LoggingMode.Error, "IEnumerable failed, EXP:{0}", ex);
        var singleObject = response1.Content.ReadAsAsync<PI>().Result;
        if (singleObject != null)
        {
            m_Logging.Log(SharedLib.LoggingMode.Error, "singleObject succeeded...");
            caseInfos1 = new[] { singleObject };
        }
    }
    catch (Exception exp)
    {
        m_Logging.Log(SharedLib.LoggingMode.Error, "singleObject failed, EXP:{0}", exp);
    }
}

I crossed with the below exception also:

System.Runtime.Serialization.SerializationException: Error in line 1 position 5. Expecting element 'ArrayOfPI' from namespace 'http://schemas.datacontract.org/2004/07/SATA_DTOs'.. Encountered 'Element'  with name 'PI', namespace ''....

.....

as the exception mentioned it can't be able to deserialize the result I guessed the out put type may is text/html not text/xml although Rest Client Tester specified it as text/xml,

for this reason I came to this conclusion to use ReadAsStringAsync and deserialize it to PI, so by the below snipped code I finally get the result:

PI caseInfos = null;
try
{
    string strasd = response.Content.ReadAsStringAsync().Result;
    m_Logging.Log(SharedLib.LoggingMode.Prompt, "ReadAsStringAsync() result:{0}", strasd);
    System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(PI));
    using (TextReader reader = new StringReader(strasd))
        caseInfos = (PI)serializer.Deserialize(reader);
    m_Logging.Log(SharedLib.LoggingMode.Prompt, "Deserializing caseInfos model succeeded...");
}
catch (Exception ex)
{
    m_Logging.Log(SharedLib.LoggingMode.Error, "creating model failed, EXP:{0}", ex);
}

I appreciate all crossed this question especially those who shared his/her knowledge in this discussion!!!


问:
Push data to Azure SQL database
I am pretty new using Azure SQL database. I have been given a task to push a 100 million record text file to Azure SQL database. I'm looking for suggestions how to do it in an efficient manner. </p>

答:
You have several options to upload on-premise data to your SQL Azure database

SSIS - As Randy mentioned you can create an SSIS package (using SSMS) and schedule an SQL Agent job to run this package periodically.

Azure Data Factory - You can define an ADF pipeline that periodically uploads data from your on-premise file to your SQL Azure database. Depending on your requirements you might need just the initial 'Connect and collect' part of the pipeline or you might want to add further additional processing in the pipeline

bcp - The 'bulk copy program' utility can be used to copy data between SqlServer and a data file.Similar to the SSIS package you can use an SQL Agent job to schedule periodic uploads using bcp.

SqlBulkCopy - I doubt if you would need this, but in case you need to integrate this into your application programmatically this class helps you achieve the same as the bcp utility (bcp is faster) via .NET code.

Title: Push data to Azure SQL database

ContentLicense: CC BY-SA 4.0


问:
trouble with PHP to Excel
before i asked here my coding first,

```<code><?php
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=T1/T2.xls");
header("Pragma: no-cache");
header("Expires: 0");
?>

<table width="100%"" cellpadding="5" cellspacing="0">
<tr>
  <td>+62-21-5900755</td>
  <td>2017-11-01</td>
</tr>
</table>
</code>```

When i'm starting running this code, well is working, but my problem is the output not same on php. like +62-21-5900755 change into -5900714 and date 2017-11-01 change into 01/11/2017. How to make my output excel same value as input on php???

Found Solution (Well not really too)
So add type ' on first string, and you will get format became like these '+62-21-5900755 and '2017-11-01. Thanks Vityata.

答:
Try like this:

```<code><table width="100%"" cellpadding="5" cellspacing="0">
<tr>
  <td>'+62-21-5900755</td>
  <td>'2017-11-01</td>
</tr>
</code>```

The ' part will leave it converted as a text.

Title: trouble with PHP to Excel

Body:
before i asked here my coding first,

<?php
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=T1/T2.xls");
header("Pragma: no-cache");
header("Expires: 0");
?>

  +62-21-5900755
  2017-11-01

When i'm starting running this code, well is working, but my problem is the output not same on php. like +62-21-5900755 change into -5900714 and date 2017-11-01 change into 01/11/2017. How to make my output excel same value as input on php???

Found Solution (Well not really too)
So add type ' on first string, and you will get format became like these '+62-21-5900755 and '2017-11-01. Thanks Vityata.

Body:
Try like this:

<table width="100%"" cellpadding="5" cellspacing="0">
<tr>
  <td>'+62-21-5900755</td>
  <td>'2017-11-01</td>
</tr>

The ' part will leave it converted as a text.


问:
How to retry a consumed Observable?
I am trying to re-execute a defined observable that failed. Using Retrofit2 and RxJava2 together i want to retry a specific request with its subscription and behavior when clicking a button. is that possible? </p>

```<code>service.excecuteLoginService(url,
            tokenModel,
            RetrofitManager.apiKey)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(....)
</code>```

答:
An option is to create Publisher, which emission is controlled by your button.

```<code>final PublishSubject<Object> retrySubject = PublishSubject.create();

service.excecuteLoginService(url,
            tokenModel,
            RetrofitManager.apiKey)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnError(throwable -> showButton())
            .retryWhen(observable -> observable.zipWith(retrySubject, (o, o2) -> o))
            .subscribeWith(result -> {}, error -> {});
</code>```

Your button will just emit an item from the Subject:

```<code>retrySubject.onNext(EMPTY);
</code>```

Title: How to retry a consumed Observable?

Body:
I am trying to re-execute a defined observable that failed. Using Retrofit2 and RxJava2 together i want to retry a specific request with its subscription and behavior when clicking a button. is that possible?

service.excecuteLoginService(url,
            tokenModel,
            RetrofitManager.apiKey)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(....)

Body:
An option is to create Publisher, which emission is controlled by your button.

final PublishSubject<Object> retrySubject = PublishSubject.create();

service.excecuteLoginService(url,
            tokenModel,
            RetrofitManager.apiKey)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnError(throwable -> showButton())
            .retryWhen(observable -> observable.zipWith(retrySubject, (o, o2) -> o))
            .subscribeWith(result -> {}, error -> {});

Your button will just emit an item from the Subject:

retrySubject.onNext(EMPTY);


问:
React component does not re-render reactively (Redux Observable + rxjs + rx-http-requst)
I have an API endpoint that returns a list of users in an 'application/stream+json' type response. The items are separated by a new line character.
Example data can be seen here.

Component

```<code>class UserList extends Component {
    componentDidMount() {
        const { fetchUsers } = this.props;
        fetchUsers();
    }

    render() {
        const { isFetching = false, users = [] } = this.props;
        if (isFetching) {
            return <Loader message="Users are loading..." />;
        }
        if (!users || users.length === 0) {
            return 'No users found.';
        }
        const children = users
            .map(user => <UserListItem key={user.id} user={user} />);
        return (
            <div className="UserList">
                <Paper>
                    <List>
                        <Subheader>Users</Subheader>
                        {children}
                    </List>
                </Paper>
            </div>
        );
    }
}

UserList.propTypes = {
    users: PropTypes.arrayOf(PropTypes.any),
    isFetching: PropTypes.bool.isRequired,
    fetchUsers: PropTypes.func.isRequired,
};

UserList.defaultProps = {
    users: [],
};

function mapStateToProps(state) {
    const { users, isFetching } = state.users;
    return {
        users,
        isFetching,
    };
}

function mapDispatchToProps(dispatch) {
    return {
        fetchUsers: bindActionCreators(actions.fetchUsers, dispatch),
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(UserList);
</code>```

Reducer

```<code>const initialState = {
    users: [],
    isFetching: false,
};

function fetchUsers(state) {
    return {
        ...state,
        isFetching: true,
    };
}

function fetchUsersItemReceived(state, action) {
    const { user } = action;
    return {
        ...state,
        users: [...state.users, user],
        isFetching: false,
    };
}

export default function (state = initialState, action) {
    switch (action.type) {
    case actionTypes.FETCH_USERS_REQUEST:
        return fetchUsers(state);
    case actionTypes.FETCH_USERS_ITEM_RECEIVED:
        return fetchUsersItemReceived(state, action);
    default:
        return state;
    }
}
</code>```

Action (the parser is the Streaming JSON Parser found here)

```<code>export function fetchUsers() {
    return {
        type: actionTypes.FETCH_USERS_REQUEST,
    };
}

function fetchUsersItemReceived(user) {
    return {
        type: actionTypes.FETCH_USERS_ITEM_RECEIVED,
        user,
    };
}

function fetchUsersSuccess() {
    return {
        type: actionTypes.FETCH_USERS_SUCCESS,
    };
}

function fetchUsersFailure(error) {
    return {
        type: actionTypes.FETCH_USERS_FAILURE,
        error,
    };
}

function getJsonStream(url) {
    const emitter = new Subject();
    const req$ = RxHR
        .get(url)
        .flatMap(resp => resp.body)
        .subscribe(
            (data) => {
                parser.write(data);
                parser.onValue = (value) => {
                    if (!parser.key) {
                        emitter.next(value);
                    }
                };
            },
            err => emitter.error(err),
            () => emitter.complete(),
        );
    return emitter;
}

export const fetchUsersEpic = action$ =>
    action$.ofType(actionTypes.FETCH_USERS_REQUEST)
        .concatMap(() => getJsonStream(`${api.API_BASE_URL}/user`))
        .map(user => fetchUsersItemReceived(user));
</code>```

configureStore.js

```<code>const logger = createLogger();

const epicMiddleware = createEpicMiddleware(rootEpic);
const createStoreWithMiddleware = applyMiddleware(epicMiddleware, logger)(createStore);

export default function configureStore(initialState) {
    return createStoreWithMiddleware(rootReducer, initialState);
}
</code>```

While the list component should be refreshed after EACH item is received, it is refreshed AFTER the whole list is received. Can someone point me to the blocking point in the code?

答:
Turns out the problem was with the jsonParse lib. Switching to oboe.js
fixed it. Using the "!" node selector to select multiple root JSON elements i was able to transform the character stream to a user object stream.

Action

```<code>function getJsonStream(url) {
    const emitter = new Subject();
    const emitter = new Subject();
    oboe(url)
        .node('!', (item) => {
            emitter.next(item);
        })
        .fail((error) => {
            emitter.error(error);
        });
    return emitter;
}

export const fetchUsersEpic = action$ =>
    action$.ofType(actionTypes.FETCH_USERS_REQUEST)
        .switchMap(() => getJsonStream(`${api.API_BASE_URL}/user`))
        .map(user => fetchUsersItemReceived(user));
</code>```

Body:
I have an API endpoint that returns a list of users in an 'application/stream+json' type response. The items are separated by a new line character.
Example data can be seen here.

Component

class UserList extends Component {
    componentDidMount() {
        const { fetchUsers } = this.props;
        fetchUsers();
    }

    render() {
        const { isFetching = false, users = [] } = this.props;
        if (isFetching) {
            return <Loader message="Users are loading..." />;
        }
        if (!users || users.length === 0) {
            return 'No users found.';
        }
        const children = users
            .map(user => <UserListItem key={user.id} user={user} />);
        return (

                <Paper>
                    <List>
                        <Subheader>Users</Subheader>
                        {children}
                    </List>
                </Paper>

        );
    }
}

UserList.propTypes = {
    users: PropTypes.arrayOf(PropTypes.any),
    isFetching: PropTypes.bool.isRequired,
    fetchUsers: PropTypes.func.isRequired,
};

UserList.defaultProps = {
    users: [],
};

function mapStateToProps(state) {
    const { users, isFetching } = state.users;
    return {
        users,
        isFetching,
    };
}

function mapDispatchToProps(dispatch) {
    return {
        fetchUsers: bindActionCreators(actions.fetchUsers, dispatch),
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(UserList);

Reducer

const initialState = {
    users: [],
    isFetching: false,
};

function fetchUsers(state) {
    return {
        ...state,
        isFetching: true,
    };
}

function fetchUsersItemReceived(state, action) {
    const { user } = action;
    return {
        ...state,
        users: [...state.users, user],
        isFetching: false,
    };
}

export default function (state = initialState, action) {
    switch (action.type) {
    case actionTypes.FETCH_USERS_REQUEST:
        return fetchUsers(state);
    case actionTypes.FETCH_USERS_ITEM_RECEIVED:
        return fetchUsersItemReceived(state, action);
    default:
        return state;
    }
}

Action (the parser is the Streaming JSON Parser found here)

export function fetchUsers() {
    return {
        type: actionTypes.FETCH_USERS_REQUEST,
    };
}

function fetchUsersItemReceived(user) {
    return {
        type: actionTypes.FETCH_USERS_ITEM_RECEIVED,
        user,
    };
}

function fetchUsersSuccess() {
    return {
        type: actionTypes.FETCH_USERS_SUCCESS,
    };
}

function fetchUsersFailure(error) {
    return {
        type: actionTypes.FETCH_USERS_FAILURE,
        error,
    };
}

function getJsonStream(url) {
    const emitter = new Subject();
    const req$ = RxHR
        .get(url)
        .flatMap(resp => resp.body)
        .subscribe(
            (data) => {
                parser.write(data);
                parser.onValue = (value) => {
                    if (!parser.key) {
                        emitter.next(value);
                    }
                };
            },
            err => emitter.error(err),
            () => emitter.complete(),
        );
    return emitter;
}

export const fetchUsersEpic = action$ =>
    action$.ofType(actionTypes.FETCH_USERS_REQUEST)
        .concatMap(() => getJsonStream(`${api.API_BASE_URL}/user`))
        .map(user => fetchUsersItemReceived(user));

configureStore.js

const logger = createLogger();

const epicMiddleware = createEpicMiddleware(rootEpic);
const createStoreWithMiddleware = applyMiddleware(epicMiddleware, logger)(createStore);

export default function configureStore(initialState) {
    return createStoreWithMiddleware(rootReducer, initialState);
}

While the list component should be refreshed after EACH item is received, it is refreshed AFTER the whole list is received. Can someone point me to the blocking point in the code?

Body:
Turns out the problem was with the jsonParse lib. Switching to oboe.js
fixed it. Using the "!" node selector to select multiple root JSON elements i was able to transform the character stream to a user object stream.

Action

function getJsonStream(url) {
    const emitter = new Subject();
    const emitter = new Subject();
    oboe(url)
        .node('!', (item) => {
            emitter.next(item);
        })
        .fail((error) => {
            emitter.error(error);
        });
    return emitter;
}

export const fetchUsersEpic = action$ =>
    action$.ofType(actionTypes.FETCH_USERS_REQUEST)
        .switchMap(() => getJsonStream(`${api.API_BASE_URL}/user`))
        .map(user => fetchUsersItemReceived(user));


问:
ASP.NET MVC5 Razor Refresh modal dialog
I'm tryin' to get actual time in modal dialog every time a user press the Order button.

```<code><a class="btn btn-primary" data-toggle="modal" data-target="#OrderModal">@MEDONET.Language.Doctor.Texts.Order</a>
</code>```

So every time he do this in the modal div OrderModal

```<code><div id="OrderModal" class="modal fade" role="dialog">
    @Html.Action("CreateOrderForm", Model.CreateOrderVM)
</div>
</code>```

Which calls to CreateOrderForm action

```<code>public ActionResult CreateOrderForm(CreateOrderVM createOrderVM)
    {
        createOrderVM.Minute = DateTime.Now.Minute.ToString().PadLeft(2, '0');
        return View("CreateOrderForm", createOrderVM);
    }
</code>```

So that action is actually running every time and calls CreateOrderForm.cshtml file

```<code>@{
Layout = null;
}
@model MEDONET.Models.CreateOrderVM

<div class="modal-dialog modal-sm">
<!-- Modal content-->
<div class="modal-content">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">×</button>
        <h4 class="modal-title text-center">Order To Line</h4>
    </div>
    <div class="modal-body">
        @using (Html.BeginForm("CreateOrder", "Doctors", FormMethod.Post))
        {
            @Html.AntiForgeryToken()
            @Html.HiddenFor(m => m.DoctorId)
            <div class="row text-center">
                <p>Date & Time</p>
                @Html.Label("Year")
                @Html.EditorFor(model => model.Year, new { htmlAttributes = new { @class = "form-control", @Value = DateTime.Now.Year } })<br />
                @Html.Label("Month")
                @Html.EditorFor(model => model.Month, new { htmlAttributes = new { @class = "form-control", @Value = DateTime.Now.Month } })<br />
                @Html.Label("Day")
                @Html.EditorFor(model => model.Day, new { htmlAttributes = new { @class = "form-control", @Value = DateTime.Now.Day } })<br />
                @Html.Label("Hour")
                @Html.EditorFor(model => model.Hour, new { htmlAttributes = new { @class = "form-control", @Value = DateTime.Now.Hour } })<br />
                @Html.Label("Minute")
                @Html.EditorFor(model => model.Minute, new { htmlAttributes = new { @class = "form-control" } })<br />
                @if (this.User.IsInRole("Registrator"))
                {
                    @Html.EditorFor(model => model.PhoneNumber, new { htmlAttributes = new { @class = "form-control" } })<br />
                }
                <button type="submit" class="btn btn-default">Submit</button>
            </div>
        }
    </div>
    <div class="modal-footer">

    </div>
</div>
</code>```

BUT! The popup fields are still filled with the first time given while parent page loading.

How can I give a user new time every time he press the Order button?

答:
I'm guessing that the method use some kind of post and than returns the new form.
In this cases it happens that when you return the same view the model state is the one that populate those fields. In order to solve it add in the action

```<code>ModelState.Clear();
</code>```

Or

```<code>ModelState.Remove("myChangeValue");
</code>```

you can look for more info in https://blogs.msdn.microsoft.com/simonince/2010/05/05/asp-net-mvcs-html-helpers-render-the-wrong-value/

If you just want to change the time in the modal I would recommend to change it with javascript when you show the modal.

```<code>$('#OrderModal #Minute').val(new Data().getMinutes());
</code>```

Title: ASP.NET MVC5 Razor Refresh modal dialog

Body:
I'm tryin' to get actual time in modal dialog every time a user press the Order button.

@MEDONET.Language.Doctor.Texts.Order

So every time he do this in the modal div OrderModal

    @Html.Action("CreateOrderForm", Model.CreateOrderVM)

Which calls to CreateOrderForm action

public ActionResult CreateOrderForm(CreateOrderVM createOrderVM)
    {
        createOrderVM.Minute = DateTime.Now.Minute.ToString().PadLeft(2, '0');
        return View("CreateOrderForm", createOrderVM);
    }

So that action is actually running every time and calls CreateOrderForm.cshtml file

@{
Layout = null;
}
@model MEDONET.Models.CreateOrderVM

        <button type="button" class="close" data-dismiss="modal">×</button>

Order To Line

        @using (Html.BeginForm("CreateOrder", "Doctors", FormMethod.Post))
        {
            @Html.AntiForgeryToken()
            @Html.HiddenFor(m => m.DoctorId)

Date & Time

                @Html.Label("Year")
                @Html.EditorFor(model => model.Year, new { htmlAttributes = new { @class = "form-control", @Value = DateTime.Now.Year } })

                @Html.Label("Month")
                @Html.EditorFor(model => model.Month, new { htmlAttributes = new { @class = "form-control", @Value = DateTime.Now.Month } })

                @Html.Label("Day")
                @Html.EditorFor(model => model.Day, new { htmlAttributes = new { @class = "form-control", @Value = DateTime.Now.Day } })

                @Html.Label("Hour")
                @Html.EditorFor(model => model.Hour, new { htmlAttributes = new { @class = "form-control", @Value = DateTime.Now.Hour } })

                @Html.Label("Minute")
                @Html.EditorFor(model => model.Minute, new { htmlAttributes = new { @class = "form-control" } })

                @if (this.User.IsInRole("Registrator"))
                {
                    @Html.EditorFor(model => model.PhoneNumber, new { htmlAttributes = new { @class = "form-control" } })

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

        }

BUT! The popup fields are still filled with the first time given while parent page loading.

How can I give a user new time every time he press the Order button?

Body:
I'm guessing that the method use some kind of post and than returns the new form.
In this cases it happens that when you return the same view the model state is the one that populate those fields. In order to solve it add in the action

ModelState.Clear();

Or

ModelState.Remove("myChangeValue");

you can look for more info in https://blogs.msdn.microsoft.com/simonince/2010/05/05/asp-net-mvcs-html-helpers-render-the-wrong-value/

If you just want to change the time in the modal I would recommend to change it with javascript when you show the modal.

$('#OrderModal #Minute').val(new Data().getMinutes());