问:
Display ASP.Net MSChart / File Issue
I’ve add MSChart to a webpage and I’m also using a Survey page I got from 4GuysFromRolla.  Both work on my development machine but when I move them to my hosting site there are issues.

With MSChart page the chart is not displayed although it’s included the Page Source code:

```<code>src="/ClubInformationTracking/ChartImg.axd?i=chart_3d90c53b0f844807a2491a1d79a636a1_0.png&g=75fecf0f14cf4121b623691d383263aa" alt="" style="height:300px;width:700px;border-width:0px;" />
</code>```

And when I try to open the Survey page I get this:
Parser Error Message: Could not load file or assembly 'sstchur.web.survey' or one of its dependencies. The system cannot find the file specified.

Source Error:

```<code><%@ Register TagPrefix = "sstchur" Namespace = "sstchur.web.survey" Assembly = "sstchur.web.survey" %>
<%@ Page Language = "C#" %>
</code>```

Assembly Load Trace: The following information can be helpful to determine why the assembly sstchur.web.survey could not be loaded.

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.

Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

The Hosting site is using Version 4.0 and the dll needed for the survey is in the BIN directory.

When I moved my files to the hosting site I had to change every instance when I referred to a file from:

```<code>“~/FileName”
</code>```

To

```<code>“FileName”
</code>```

I’ve tried all of the “fixes” I could find for the MSChart that involved changes to the web.config file but because of the error messages associated with the Survey page I’m guessing this is the issue.

Any suggestions?

答:
ASP.NET only looks for DLLs in the application's root /bin folder. If you just added the ClubInformationTracking folder yourself and did not configure it to be an IIS application or virtual directory via the web hosting provider's control panel, then that is the problem, as ASP.NET is looking for any DLLs in /Bin (or, perhaps, /public/Bin, depending on how things are setup).

There are two possible remedies here:

Move the Bin folder (and its contents) from the ClubInformationTracking subfolder into public and see if that works. If not, try moving it to root

From the web hosting provider's control panel, make the ClubInformationTracking folder a virtual directory or IIS application. If you're unclear on how do to this, contact your web hosting provider's support.

Thanks, and happy programming!

Title: Display ASP.Net MSChart / File Issue

Body:
I’ve add MSChart to a webpage and I’m also using a Survey page I got from 4GuysFromRolla.  Both work on my development machine but when I move them to my hosting site there are issues.

With MSChart page the chart is not displayed although it’s included the Page Source code:

src="/ClubInformationTracking/ChartImg.axd?i=chart_3d90c53b0f844807a2491a1d79a636a1_0.png&g=75fecf0f14cf4121b623691d383263aa" alt="" style="height:300px;width:700px;border-width:0px;" />

And when I try to open the Survey page I get this:
Parser Error Message: Could not load file or assembly 'sstchur.web.survey' or one of its dependencies. The system cannot find the file specified.

Source Error:

<%@ Register TagPrefix = "sstchur" Namespace = "sstchur.web.survey" Assembly = "sstchur.web.survey" %>
<%@ Page Language = "C#" %>

Assembly Load Trace: The following information can be helpful to determine why the assembly sstchur.web.survey could not be loaded.

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.

Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

The Hosting site is using Version 4.0 and the dll needed for the survey is in the BIN directory.

When I moved my files to the hosting site I had to change every instance when I referred to a file from:

“~/FileName”

To

“FileName”

I’ve tried all of the “fixes” I could find for the MSChart that involved changes to the web.config file but because of the error messages associated with the Survey page I’m guessing this is the issue.

Any suggestions?


来源: stackexchange

问:
Can More Than One Tenant Read/Write a Contact?
I have a very basic requirement for a CRM I'm building in the Consumer Debt space.  An issuer, say Bank of America, has to charge off a credit card, so then send the credit card with the information to the collections department which can either farm it out to a collection agency, or sell the charged-off debt to another debt buying company.  While they're trying to collect the debt, they'll log bits of information about the customer: last address, are they working, did a collection company get involved.  That is, they'll collect information about the consumer behind the credit card.

Usually, the debt is passed on to a debt buyer who goes through this whole process again, usually with almost no information from BofA about the previous attempt to collect.

So here's the question: is there any capability in Microsoft CRM (or Salesforce) that would allow this customer record to be sold/transferred/shared between tenants?  The idea is that the consumer would be much better represented if their information flowed with the credit card as it made it's way through the debt buyers and collection agencies.

答:
Dynamics 365 (formerly CRM) can import and export data effortlessly to/from Excel files.

I don't have a clue about Salesforce, but it's reasonable to believe it can too.

ContentLicense: CC BY-SA 3.0


问:
Function returning "This" object in C++
So, following is a member function of Class Sales_data which is defined outside the class,

```<code>Sales_data& Sales_data::combine(const Sales_data &rhs) {
    units_sold += rhs.units_sold;
    revenue += rhs.revenue; //adding the members of rhs into the members of "this" object
    return *this;
} //units_sold and revenue are both data members of class
</code>```

When the function is called, it is called like

```<code>total.combine(trans); //total and trans are the objects of class
</code>```

What i am not understanding is the function returning *this,
i understand it returns an instance of the object but it is not returning that instance to anything as we can see during function call, also if i don't write the return statement, would it work any differently.

Someone please explain elaborately because i am just not getting it.

答:
It is a common way to make the next construction work:

```<code>Sales_data x, y, z;
// some code here
auto res = x.combine(y).combine(z);
</code>```

When you call:

```<code>x.combine(y)
</code>```

x is changed and reference to x is returned, so you have an opportunity to call combine() on this changed instance via the reference returned on the prevous step once more time:

```<code>x.combine(y).combine(z);
</code>```

Another popular example is operator=() implementation. So, if you implement operator= for a custom class it is often a good idea to return a reference to the instance:

```<code>class Foo
{
public:
    Foo& operator=(const Foo&)
    {
        // impl
        return *this;
    }
};
</code>```

Which makes an assignment work for your class as it works for standard types:

```<code>Foo x, y, z;
// some code here
x = y = z;
</code>```

Title: Function returning "This" object in C++

Body:
So, following is a member function of Class Sales_data which is defined outside the class,

Sales_data& Sales_data::combine(const Sales_data &rhs) {
    units_sold += rhs.units_sold;
    revenue += rhs.revenue; //adding the members of rhs into the members of "this" object
    return *this;
} //units_sold and revenue are both data members of class

When the function is called, it is called like

total.combine(trans); //total and trans are the objects of class

What i am not understanding is the function returning *this,
i understand it returns an instance of the object but it is not returning that instance to anything as we can see during function call, also if i don't write the return statement, would it work any differently.

Someone please explain elaborately because i am just not getting it.

Body:
It is a common way to make the next construction work:

Sales_data x, y, z;
// some code here
auto res = x.combine(y).combine(z);

When you call:

x.combine(y)

x is changed and reference to x is returned, so you have an opportunity to call combine() on this changed instance via the reference returned on the prevous step once more time:

x.combine(y).combine(z);

Another popular example is operator=() implementation. So, if you implement operator= for a custom class it is often a good idea to return a reference to the instance:

class Foo
{
public:
    Foo& operator=(const Foo&)
    {
        // impl
        return *this;
    }
};

Which makes an assignment work for your class as it works for standard types:

Foo x, y, z;
// some code here
x = y = z;


问:
Angular 4 server side rendering in Asp.Net MVC 5 Framework (non Core)
I'm trying to set up a project in Asp.Net 4.5.2 (VS2017) with Angular 4.

All examples seem to use Asp.Net Core, but we're trying not to jump into .NET Core just yet, if possible.

We would like to have server side rendering though, samples seem to use this asp-prerender-module attribute from "Microsoft ASP.NET Core JavaScript Services".

Is it possible to render angular 4 server side with MVC 5?

答:
Officially there is no Asp.Net Framework (non Core) support.

As stated in https://universal.angular.io/overview/:

In addition to node.js, however, Angular Universal has ASP.NET Core
  support. In the near future we hope to add support for Java, PHP and
  Python

EDIT: "Microsoft ASP.NET Core JavaScript Services" only supports ASP.NET Core which means the site needs to deployed ASP.NET Core style. But this all can run in .NET 4.5.2 so you can still reference your good old .NET Framework libraries in your project.


问:
Reflection methods fail when types are in other assembly
I'm making a little tool to analyze code dependencies recursively. I found a problem: if I try to get a member of a class whose signature contains a reference to another dll the method fails. For example, if I have a simple class in Main.exe

```<code>public class MainClass  {
    public MainClass () {
        foo();
    }

    public ContainedClass GetPublicClass () {
        return new ContainedClass ();
    }

}
</code>```

and ContainedClass is defined in other file refers.dll, when I try the following code it throw a FileNotFoundException  in met3.ReturnType() method cause .net not find refers.dll.

```<code>Assembly assem = Assembly.LoadFile(@"D:\dir\Main.exe");
Type typ =  assem.GetType ("MultipleReference.MainClass");
MethodInfo met3 = typ.GetMethod ("GetPublicClass");
met3.ReturnType.ToString ();
</code>```

Is there any way to indicate where to search the dll?

Thanks in advance and sorry for my English.

答:
Use LoadFrom instead of LoadFile because it will also resolve and load dependent assemblies. Quoting the documentation:

Use the LoadFile method to load and
  examine assemblies that have the same
  identity, but are located in different
  paths. LoadFile does not load files
  into the LoadFrom context, and does
  not resolve dependencies using the
  load path, as the LoadFrom method
  does. LoadFile is useful in this
  limited scenario because LoadFrom
  cannot be used to load assemblies that
  have the same identities but different
  paths; it will load only the first
  such assembly.

ContentLicense: CC BY-SA 2.5

Body:
I'm making a little tool to analyze code dependencies recursively. I found a problem: if I try to get a member of a class whose signature contains a reference to another dll the method fails. For example, if I have a simple class in Main.exe

public class MainClass  {
    public MainClass () {
        foo();
    }

    public ContainedClass GetPublicClass () {
        return new ContainedClass ();
    }

}

and ContainedClass is defined in other file refers.dll, when I try the following code it throw a FileNotFoundException  in met3.ReturnType() method cause .net not find refers.dll.

Assembly assem = Assembly.LoadFile(@"D:\dir\Main.exe");
Type typ =  assem.GetType ("MultipleReference.MainClass");
MethodInfo met3 = typ.GetMethod ("GetPublicClass");
met3.ReturnType.ToString ();

Is there any way to indicate where to search the dll?

Thanks in advance and sorry for my English.


问:
Regular expression to match any word followed by a literal string
So I have the following:

```<code>^[a-zA-Z]+\b(myword+-)\b*
</code>```

which I thought would match

^ start of string

[a-zA-Z] any alpha character

+ of one or more characters

\b followed by a word break

(myword+-) followed by myword which could include one or more special characters

\b followed by a word break

\* followed by anything at all

One: it does not work - it does not match anything

Two: any special characters included in {myword+-) throws an error

I could escape the special characters, but I don't know in advance what they might be, so I would have to escape all the possibilites, or perhaps I could just escape every character in {\m\y\w\o\r\d\\+\\-)

Edited to add:

Sorry, I knew I should have given more information

I have a series of strings to seach through in the form:

extra android-sdk and more that is of no interest

extra android-ndk and more that is of no interest

extra anjuta-extra and more that is of no interest

community c++-gtk-utils and more that is of no interest

and I have a list of items to search for in the strings:

android-sdk

android-ndk

extra

c++-gtk-utils

The item should only match if the second word in the string is an exact match to the item, so:

android-sdk will match the first string

android-ndk will match the second string

extra wuill NOT match the third string

c++-gtk-utils will match the fourth string

So (myword+-) is the item I am searching for "which could include one or more special characters"

Thanks for the help

Andrew

答:
Disclaimer: Since your question lacks information what input and output is expected, I will give it a try to tell you why your Regex isn't working at all. Since it's not a full answer you might not want to mark it as accepted and possibly wait for someone to give you an example of working solution, as soon as you provide necessary information.

Notes:

quantifier characters (*, +, ? etc.) are applied to literal character or character class (a.k.a character group, namely characters/ranges inside [ ]) - when in your regex you write (myword+-) the only thing the + sign is applied to is letter 'd', nothing else.

what is myword in your regex? If you want a set of characters use [ ] combined with character ranges and/or character tokens such as \w (all word characters, such as letters and some special characters) or \d (all digit characters)

you also seem to misunderstand and misuse groups ("( )"), character classes ("[ ]") and quantifier notation ("{ }")

Body:
So I have the following:

^[a-zA-Z]+\b(myword+-)\b*

which I thought would match

^ start of string

[a-zA-Z] any alpha character

+ of one or more characters

\b followed by a word break

(myword+-) followed by myword which could include one or more special characters

\b followed by a word break

\* followed by anything at all

One: it does not work - it does not match anything

Two: any special characters included in {myword+-) throws an error

I could escape the special characters, but I don't know in advance what they might be, so I would have to escape all the possibilites, or perhaps I could just escape every character in {\m\y\w\o\r\d\\+\\-)

Edited to add:

Sorry, I knew I should have given more information

I have a series of strings to seach through in the form:

extra android-sdk and more that is of no interest

extra android-ndk and more that is of no interest

extra anjuta-extra and more that is of no interest

community c++-gtk-utils and more that is of no interest

and I have a list of items to search for in the strings:

android-sdk

android-ndk

extra

c++-gtk-utils

The item should only match if the second word in the string is an exact match to the item, so:

android-sdk will match the first string

android-ndk will match the second string

extra wuill NOT match the third string

c++-gtk-utils will match the fourth string

So (myword+-) is the item I am searching for "which could include one or more special characters"

Thanks for the help

Andrew


问:
Create a colormap for a histogram based off a data array
I've looked in a variety of places for how to do this but haven't been able to find exactly what I need/find validation if this is even possible.

I have a 2d histogram of height on y axis (given by rdata1) and intensity on x axis (given by intensity). The histogram plots fine, but I'd like to scale the colorbar rather than have it normalised.

I have already defined a colourmap, and I simply want to scale it using my plotted data.

I would like to scale the data so that the colorbar (which currently runs from 0-1) scales from 0 to (number of points in bin)/(len(time)). This is so I can find out the probability of a point being in a certain intensity bin at a certain height. I was unsure whether to do this by making a second histogram (which I wouldn't plot) and exporting the max/min values from that to scale the colourbar, or using a number of for loops and lists to append values into bins for each height range and then max/min the number of values in those bins.

Code is attached below:

```<code>import numpy as np
import file_reader as fr
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import matplotlib as mpl

time = [0.01649999991059303, 0.02584999985992908]
rdata = [-600.020751953125, -570.04150390625, -540.062255859375, -510.0830078125, -480.1037902832031, -450.1245422363281, -420.1452941894531, -390.1660461425781, -360.1867980957031, -330.2075500488281]
intensity = [[-37.32464981079102, -38.3233528137207], [-37.70231628417969, -38.05134201049805], [-38.27889251708984, -38.82979583740234], [-28.01022720336914, -27.68825912475586], [-8.408446311950684, -8.440451622009277], [-8.749446868896484, -8.750232696533203], [-9.431790351867676, -9.41820240020752], [-10.09048461914062, -10.23848724365234], [-10.84317588806152, -10.84869194030762], [-11.61933135986328, -11.67543029785156]]

range_bins = np.linspace(rdata[0],rdata[-1],(len(rdata)+1))
intensity_bins = np.linspace(-70,30,100)

intensity = np.array(intensity).ravel()
rdata1 = np.repeat(rdata,len(time))

cdict = {'red': ((0.0, 1.0, 1.0),
                 (0.25, 0.0, 0.0),
                 (0.55, 0.35, 0.35),
                 (0.75, 0.75, 0.75),
                 (1.0, 1.0, 1.0)),

       'green': ((0.0, 1.0, 1.0),
                 (0.25, 0.1, 0.1),
                 (0.55, 0.6, 0.6),
                 (0.75, 0.8, 0.8),
                 (1.0, 0.0, 0.0)),

        'blue': ((0.0, 1.0, 1.0),
                 (0.25, 1.0, 1.0),
                 (0.55, 0.2, 0.2),
                 (0.75, 0.1, 0.1),
                 (1.0, 0.0, 0.0))
        }

radar_map = LinearSegmentedColormap('radar_map', cdict)

H, range_bins, intensity_bins = np.histogram2d(rdata1,intensity,bins=(range_bins,intensity_bins))

fig = plt.figure()
X,Y = np.meshgrid(intensity_bins,range_bins)
plt.pcolormesh(X,Y,H, cmap=radar_map)

cax = fig.add_axes([0.95, 0.2, 0.02, 0.6])
cb = mpl.colorbar.ColorbarBase(cax, cmap=radar_map, spacing='proportional')
</code>```

Any help with this would be massively appreciated. Sorry for the rather lengthy post.

答:
At the moment, the colorbar is independend of the shown pcolormesh.
If you link the colorbar to the pcolormesh, it will automatically scale to the minimum and maximum level of the plot. Use plt.colorbar(pc), where pc is the return of the pcolormesh.

To normalize the histogram counts you may divide the histogram by whatever quantity you want, e.g.

```<code>plt.pcolormesh( X,Y,H/float(len(time)) )
</code>```

Example:

```<code>fig = plt.figure()
X,Y = np.meshgrid(intensity_bins,range_bins)
pc = plt.pcolormesh(X,Y,H/float(len(time)), cmap=radar_map)

cax = fig.add_axes([0.90, 0.2, 0.02, 0.6])
cb = plt.colorbar(pc, cax=cax)
</code>```

Body:
I've looked in a variety of places for how to do this but haven't been able to find exactly what I need/find validation if this is even possible.

I have a 2d histogram of height on y axis (given by rdata1) and intensity on x axis (given by intensity). The histogram plots fine, but I'd like to scale the colorbar rather than have it normalised.

I have already defined a colourmap, and I simply want to scale it using my plotted data.

I would like to scale the data so that the colorbar (which currently runs from 0-1) scales from 0 to (number of points in bin)/(len(time)). This is so I can find out the probability of a point being in a certain intensity bin at a certain height. I was unsure whether to do this by making a second histogram (which I wouldn't plot) and exporting the max/min values from that to scale the colourbar, or using a number of for loops and lists to append values into bins for each height range and then max/min the number of values in those bins.

Code is attached below:

import numpy as np
import file_reader as fr
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import matplotlib as mpl

time = [0.01649999991059303, 0.02584999985992908]
rdata = [-600.020751953125, -570.04150390625, -540.062255859375, -510.0830078125, -480.1037902832031, -450.1245422363281, -420.1452941894531, -390.1660461425781, -360.1867980957031, -330.2075500488281]
intensity = [[-37.32464981079102, -38.3233528137207], [-37.70231628417969, -38.05134201049805], [-38.27889251708984, -38.82979583740234], [-28.01022720336914, -27.68825912475586], [-8.408446311950684, -8.440451622009277], [-8.749446868896484, -8.750232696533203], [-9.431790351867676, -9.41820240020752], [-10.09048461914062, -10.23848724365234], [-10.84317588806152, -10.84869194030762], [-11.61933135986328, -11.67543029785156]]

range_bins = np.linspace(rdata[0],rdata[-1],(len(rdata)+1))
intensity_bins = np.linspace(-70,30,100)

intensity = np.array(intensity).ravel()
rdata1 = np.repeat(rdata,len(time))

cdict = {'red': ((0.0, 1.0, 1.0),
                 (0.25, 0.0, 0.0),
                 (0.55, 0.35, 0.35),
                 (0.75, 0.75, 0.75),
                 (1.0, 1.0, 1.0)),

       'green': ((0.0, 1.0, 1.0),
                 (0.25, 0.1, 0.1),
                 (0.55, 0.6, 0.6),
                 (0.75, 0.8, 0.8),
                 (1.0, 0.0, 0.0)),

        'blue': ((0.0, 1.0, 1.0),
                 (0.25, 1.0, 1.0),
                 (0.55, 0.2, 0.2),
                 (0.75, 0.1, 0.1),
                 (1.0, 0.0, 0.0))
        }

radar_map = LinearSegmentedColormap('radar_map', cdict)

H, range_bins, intensity_bins = np.histogram2d(rdata1,intensity,bins=(range_bins,intensity_bins))

fig = plt.figure()
X,Y = np.meshgrid(intensity_bins,range_bins)
plt.pcolormesh(X,Y,H, cmap=radar_map)

cax = fig.add_axes([0.95, 0.2, 0.02, 0.6])
cb = mpl.colorbar.ColorbarBase(cax, cmap=radar_map, spacing='proportional')

Any help with this would be massively appreciated. Sorry for the rather lengthy post.

Body:
At the moment, the colorbar is independend of the shown pcolormesh.
If you link the colorbar to the pcolormesh, it will automatically scale to the minimum and maximum level of the plot. Use plt.colorbar(pc), where pc is the return of the pcolormesh.

To normalize the histogram counts you may divide the histogram by whatever quantity you want, e.g.

plt.pcolormesh( X,Y,H/float(len(time)) )

Example:

fig = plt.figure()
X,Y = np.meshgrid(intensity_bins,range_bins)
pc = plt.pcolormesh(X,Y,H/float(len(time)), cmap=radar_map)

cax = fig.add_axes([0.90, 0.2, 0.02, 0.6])
cb = plt.colorbar(pc, cax=cax)


问:
Magento 1.9 throws 500 error when user try to register
I have Magento version 1.9.3.2. When a user wants to register, it generates an Internal Server Error (HTTP error code 500). The user does not receive email, but he is registered.

If I reload the page, it shows the message "Thank you for registering" and account page is open.

I checked logs of Magento and Apache - nothing there.

Anybody have idea how to fix this?

Update.
I switched on display_errors in index.php file. I got message:

[05-Jul-2017 09:09:01 UTC] PHP Fatal error:  Call to a member function getPayment() on null in /home/some/public_html/some/app/code/community/Fooman/EmailAttachments/Model/Core/Email/Template/Mailer.php on line 34

This line 34 is this:
$paymentMethod = $this->getTemplateParams()['order']->getPayment()->getData("method");

So seems there is a block "Fooman" which tries to use instance of the class when it is not initialised.

Anybody know something about this extension Fooman?

Update.
Seems the problem is solved by this code. For registration I check if user has instance of class, if he don't have it I use standard template.

```<code>//here check if have instance of class
            if (isset($this->getTemplateParams()['order']))
            {
                //here 34 string where error occure
                $paymentMethod = $this->getTemplateParams()['order']->getPayment()->getData("method");

                if ($this->getTemplateId() == '1') {
                    switch($paymentMethod) {
                        case 'banktransfer':
                            $templateId = 9;
                            break;

                        case 'paypal_express':
                            $templateId = 8;

                        default:
                            $templateId = $this->getTemplateId();
                            break;
                    }
                } else {

                    $templateId = $this->getTemplateId();
                }
            }
            else {
                $templateId = $this->getTemplateId();
            }
</code>```

答:
If you get the internal server error 500 then you must have to enable display error.

Go to index.php  and replace code

```<code>if (isset($_SERVER['MAGE_IS_DEVELOPER_MODE'])) {
    Mage::setIsDeveloperMode(true);
}
with Mage::setIsDeveloperMode(true);

and use ini_set('display_errors', 1);
</code>```

Use both one by one.

Body:
I have Magento version 1.9.3.2. When a user wants to register, it generates an Internal Server Error (HTTP error code 500). The user does not receive email, but he is registered.

If I reload the page, it shows the message "Thank you for registering" and account page is open.

I checked logs of Magento and Apache - nothing there.

Anybody have idea how to fix this?

Update.
I switched on display_errors in index.php file. I got message:

[05-Jul-2017 09:09:01 UTC] PHP Fatal error:  Call to a member function getPayment() on null in /home/some/public_html/some/app/code/community/Fooman/EmailAttachments/Model/Core/Email/Template/Mailer.php on line 34

This line 34 is this:
$paymentMethod = $this->getTemplateParams()['order']->getPayment()->getData("method");

So seems there is a block "Fooman" which tries to use instance of the class when it is not initialised.

Anybody know something about this extension Fooman?

Update.
Seems the problem is solved by this code. For registration I check if user has instance of class, if he don't have it I use standard template.

//here check if have instance of class
            if (isset($this->getTemplateParams()['order']))
            {
                //here 34 string where error occure
                $paymentMethod = $this->getTemplateParams()['order']->getPayment()->getData("method");

                if ($this->getTemplateId() == '1') {
                    switch($paymentMethod) {
                        case 'banktransfer':
                            $templateId = 9;
                            break;

                        case 'paypal_express':
                            $templateId = 8;

                        default:
                            $templateId = $this->getTemplateId();
                            break;
                    }
                } else {

                    $templateId = $this->getTemplateId();
                }
            }
            else {
                $templateId = $this->getTemplateId();
            }

Body:
If you get the internal server error 500 then you must have to enable display error.

Go to index.php  and replace code

if (isset($_SERVER['MAGE_IS_DEVELOPER_MODE'])) {
    Mage::setIsDeveloperMode(true);
}
with Mage::setIsDeveloperMode(true);

and use ini_set('display_errors', 1);

Use both one by one.


问:
The best suggestion for a structure to store multiple keys and values - dictionaries?
The intention is to create the beginnings of a facebook type program (For teaching purposes) that stores a list of names of individuals along with their bio details.

I have two questions, one follows on from the next:

Question 1: How to get at the list values that are part of a value in a key value pair in a dictionary. For instance, to find out what friends John and Mary have in common, in this case friend1 and friend3

Question 2: The best method to create a structure that stores names,gender,hobbies,and friends? Would this be a dictionary and if so, how could this be defined? If not, what do people suggest?

```<code>#create a dictionary that stores names, and a list of friends
facebook_profile={"John":["friend1","friend2","friend3","friend4"],"Mary":["friend1","friend7","friend3","friend9"]}
print(facebook_profile)
</code>```

Required to store and subsequently print the following sample data:

```<code>Name:John
Gender: Male
Hobbies: Chess
Friends: friend1,friend2,friend3,friend4

Name: Mary
Gender: Female
Hobbies: Chequers
Friends: friend1,friend2,friend3,friend4
</code>```

I am aware the best solution would be a database and to use some sort of file handling to achieve it however, for teaching purposes we are trying to use only lists or dictionaries. These dictionaries/lists could then be written to a file, but the solution(s)/answers I am looking for must ideally be utilising only the list and dictionary structures.

答: Another way is to store in Database with table columns and firends having many-to-many relationship with that table. </p>

Body:
The intention is to create the beginnings of a facebook type program (For teaching purposes) that stores a list of names of individuals along with their bio details.

I have two questions, one follows on from the next:

Question 1: How to get at the list values that are part of a value in a key value pair in a dictionary. For instance, to find out what friends John and Mary have in common, in this case friend1 and friend3

Question 2: The best method to create a structure that stores names,gender,hobbies,and friends? Would this be a dictionary and if so, how could this be defined? If not, what do people suggest?

#create a dictionary that stores names, and a list of friends
facebook_profile={"John":["friend1","friend2","friend3","friend4"],"Mary":["friend1","friend7","friend3","friend9"]}
print(facebook_profile)

Required to store and subsequently print the following sample data:

Name:John
Gender: Male
Hobbies: Chess
Friends: friend1,friend2,friend3,friend4

Name: Mary
Gender: Female
Hobbies: Chequers
Friends: friend1,friend2,friend3,friend4

I am aware the best solution would be a database and to use some sort of file handling to achieve it however, for teaching purposes we are trying to use only lists or dictionaries. These dictionaries/lists could then be written to a file, but the solution(s)/answers I am looking for must ideally be utilising only the list and dictionary structures.


问:
background color transition in few seconds w/o JQuery
https://codepen.io/codeispoetry/pen/dRKKEY

.back {
  margin: 20px;
  padding: 100px;
  background: yellow;
  font-size: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="back">

  Fun place to stay. We got a golf cart to see the rest of the island, but the house is well-equipped and comfortable. Vanessa was kind to pick us up and make golf cart rental arrangements. We were here on our honeymoon, it was perfect for a memorable trip!
  Hosts easily available

</div></code>```

I want that yellow background should change with time to yellow, but I want to do ith through CSS. there is enough solution available on StackOverflow that do it with Jquery, but can we achieve this through CSS so that it works on all the browser.

https://www.w3schools.com/css/css3_animations.asp i tried this, but it roll backs to the original color. How to make th after color permanent.

答:
Use the below updated code. you need to add 'animation-fill-mode: forwards' to stop the animation once its completed.</p>

```<code>.back {
    margin: 20px;
    padding: 100px;
    font-size: 30px;
    background-color: yellow;
    -webkit-animation-name: example;
    -webkit-animation-duration: 4s;
    animation-name: example;
    animation-duration: 4s;
    -webkit-animation-fill-mode: forwards; /* Safari 4.0 - 8.0 */
     animation-fill-mode: forwards;
}
@-webkit-keyframes example {
    from {background-color: yellow;}
    to {background-color: white;}
}

@keyframes example {
    from {background-color: yellow;}
    to {background-color: white;}
}
</code>```

Body:
https://codepen.io/codeispoetry/pen/dRKKEY

.back {
  margin: 20px;
  padding: 100px;
  background: yellow;
  font-size: 30px;
}

  Fun place to stay. We got a golf cart to see the rest of the island, but the house is well-equipped and comfortable. Vanessa was kind to pick us up and make golf cart rental arrangements. We were here on our honeymoon, it was perfect for a memorable trip!
  Hosts easily available

I want that yellow background should change with time to yellow, but I want to do ith through CSS. there is enough solution available on StackOverflow that do it with Jquery, but can we achieve this through CSS so that it works on all the browser.

https://www.w3schools.com/css/css3_animations.asp i tried this, but it roll backs to the original color. How to make th after color permanent.

Body:
Use the below updated code. you need to add 'animation-fill-mode: forwards' to stop the animation once its completed.

.back {
    margin: 20px;
    padding: 100px;
    font-size: 30px;
    background-color: yellow;
    -webkit-animation-name: example;
    -webkit-animation-duration: 4s;
    animation-name: example;
    animation-duration: 4s;
    -webkit-animation-fill-mode: forwards; /* Safari 4.0 - 8.0 */
     animation-fill-mode: forwards;
}
@-webkit-keyframes example {
    from {background-color: yellow;}
    to {background-color: white;}
}

@keyframes example {
    from {background-color: yellow;}
    to {background-color: white;}
}


问:
How do I insert a span in a string?
I have this sample:-

link

CODE HTML:

```<code><p>
  width (10mm)
</p>
</code>```

CODE JS:

```<code>jQuery(document).ready(function(){
    //First bracket detection
});
</code>```

The structure I want to obtain is the following (after document is ready):

```<code><p>
    width <span>(10mm)</span>
</p>
</code>```

I thought I could detect the first parenthesis in the string and then add a span.

Can you give me a simple example please how can I do this?

Thanks in advance!

答:
This will work in both cases:-

spaces/without spaces(example  width (10mm) or  width(10mm)):-

$(document).ready(function(){
  var string = $.trim($('p').text());
  string = string.replace(/\(([^)]+)\)/, "$1");
  $('p').html(string);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>span{
font-size:30px;
color:green;
background:yellow;
}</code>```

  width (10mm)

```

Title: How do I insert a span in a string?

Body:
I have this sample:-

link

CODE HTML:

  width (10mm)

CODE JS:

jQuery(document).ready(function(){
    //First bracket detection
});

The structure I want to obtain is the following (after document is ready):

    width (10mm)

I thought I could detect the first parenthesis in the string and then add a span.

Can you give me a simple example please how can I do this?

Thanks in advance!

Body:
This will work in both cases:-

spaces/without spaces(example  width (10mm) or  width(10mm)):-

$(document).ready(function(){
  var string = $.trim($('p').text());
  string = string.replace(/\(([^)]+)\)/, "<span>$1</span>");
  $('p').html(string);
});

span{
font-size:30px;
color:green;
background:yellow;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  width (10mm)
</p>

ContentLicense: CC BY-SA 4.0


问:
Crystal Reports - The process cannot access the file because it is being used by another process
I am getting a access problem when exporting a crystal report as a pdf stream. Below is the code which runs in a background task in a ASP.net MVC web application:

```<code>using (var memoryStream = new MemoryStream())
using (var stream = reportDoc.ExportToStream(ExportFormatType.PortableDocFormat))
{
       stream.CopyTo(memoryStream);
       data = memoryStream.ToArray();
}
</code>```

Following is the stack trace of exception:

```<code>System.Runtime.InteropServices.COMException (0x80004005): The process cannot access the file because it is being used by another process.

   at CrystalDecisions.ReportAppServer.Controllers.ReportSourceClass.Export(ExportOptions pExportOptions, RequestContext pRequestContext)
   at CrystalDecisions.ReportSource.EromReportSourceBase.ExportToStream(ExportRequestContext reqContext)
   at CrystalDecisions.CrystalReports.Engine.FormatEngine.ExportToStream(ExportRequestContext reqContext)
   at CrystalDecisions.CrystalReports.Engine.ReportDocument.ExportToStream(ExportOptions options)
   at CrystalDecisions.CrystalReports.Engine.ReportDocument.ExportToStream(ExportFormatType formatType)
</code>```

How to fix this problem?

答:
Do you open report file by using reportDocument.Load method. If so try to use OpenReportMethod.OpenReportByTempCopy option, so it looks like this</p>

```<code>reportDocument.Load(file, OpenReportMethod.OpenReportByTempCopy);
</code>```

Body:
I am getting a access problem when exporting a crystal report as a pdf stream. Below is the code which runs in a background task in a ASP.net MVC web application:

using (var memoryStream = new MemoryStream())
using (var stream = reportDoc.ExportToStream(ExportFormatType.PortableDocFormat))
{
       stream.CopyTo(memoryStream);
       data = memoryStream.ToArray();
}

Following is the stack trace of exception:

System.Runtime.InteropServices.COMException (0x80004005): The process cannot access the file because it is being used by another process.

   at CrystalDecisions.ReportAppServer.Controllers.ReportSourceClass.Export(ExportOptions pExportOptions, RequestContext pRequestContext)
   at CrystalDecisions.ReportSource.EromReportSourceBase.ExportToStream(ExportRequestContext reqContext)
   at CrystalDecisions.CrystalReports.Engine.FormatEngine.ExportToStream(ExportRequestContext reqContext)
   at CrystalDecisions.CrystalReports.Engine.ReportDocument.ExportToStream(ExportOptions options)
   at CrystalDecisions.CrystalReports.Engine.ReportDocument.ExportToStream(ExportFormatType formatType)

How to fix this problem?

Body:
Do you open report file by using reportDocument.Load method. If so try to use OpenReportMethod.OpenReportByTempCopy option, so it looks like this

reportDocument.Load(file, OpenReportMethod.OpenReportByTempCopy);


问:
c++ stl vector causing memory overflow?
I am making extensive use of stl vectors to manage memory (de-) allocation of large arrays of data. In particular I am generating perspective projections of anatomical structures from a large number of angles (180 in 2 degree steps), processing and analysing the results. The results are used to define radiation fields for radiotherapy.

It seems that if the arrays exceed a certain size (>3 anatomical structures) that the memory overflows. In particular the error is as follows

terminate called after throwing an instance of 'std::out_of_range'
  what():  vector::_M_range_check

This is the a result of using at, which does bounds checking, rather than the faster [] operator. If I have <=3 structures the error does not occur.

I have tracked the error down to the following block of code

```<code>bool dicomCP::assignBeamlet(int beamletNumber, Beamlet &b1)
{
 //std::cout << "\nInside dicomCP::assignBeamlet (int, Beamlet &)\n";

  if (!this->isSet)
  {
   this->beamlets.at(beamletNumber).setLeftRight(b1.left,b1.right);

   this->isSet=true;

   return true;

  }

  else if (!this->beamlets.at(beamletNumber-1).isOpen())
  {

   return false;

  }

  // left (outside) min(left) and right (outside) max(right) leaves
  else if ((this->beamlets.at(beamletNumber-1).right-b1.left >EPSILON2)&&(b1.right-this->beamlets.at(beamletNumber-1).left>EPSILON2))
  {

   if (this->beamlets.at(beamletNumber).open) return false;

   else if (!this->beamlets.at(beamletNumber).open)
   {
   this->beamlets.at(beamletNumber).setLeftRight(b1.left,b1.right);
   this->beamlets.at(beamletNumber).isAssigned=true;

   this->isSet=true;
   return true;
   }
  }

  else return false;

}
</code>```

Note that if the "this->isSet=true;" lines are commented out the error does not manifest itself regardless of the number of structures :yes it works with 6! The "isSet" boolean value is used to determine which objects have been set, and hence which objects need to be written out to a data file for further processing.

System and sodtware:

gcc (SUSE Linux) 4.4.1 [gcc-4_4-branch revision 150839]
SuSE 11.2 64bit
Intel Celsius with 4 Xeon 2.66GHz CPUs and 4GB RAM
Eclipse CDT (IDE) 64 bit Build 20100218-1602

答:
you are using both this->beamlets.at(beamletNumber-1) and this->beamlets.at(beamletNumber).

this->beamlets.at(beamletNumber-1) suggests you're treating the vector with 1-based indices while this->beamlets.at(beamletNumber) suggests 0-based indices.

with 1-based indices this->beamlets.at(beamletNumber) will certainly give an out-of-range error.

with 0-based indices this->beamlets.at(beamletNumber-1) will certainly give an out-of-range error.

Title: c++ stl vector causing memory overflow?

Body:
I am making extensive use of stl vectors to manage memory (de-) allocation of large arrays of data. In particular I am generating perspective projections of anatomical structures from a large number of angles (180 in 2 degree steps), processing and analysing the results. The results are used to define radiation fields for radiotherapy.

It seems that if the arrays exceed a certain size (>3 anatomical structures) that the memory overflows. In particular the error is as follows

terminate called after throwing an instance of 'std::out_of_range'
  what():  vector::_M_range_check

This is the a result of using at, which does bounds checking, rather than the faster [] operator. If I have <=3 structures the error does not occur.

I have tracked the error down to the following block of code

bool dicomCP::assignBeamlet(int beamletNumber, Beamlet &b1)
{
 //std::cout << "\nInside dicomCP::assignBeamlet (int, Beamlet &)\n";

  if (!this->isSet)
  {
   this->beamlets.at(beamletNumber).setLeftRight(b1.left,b1.right);

   this->isSet=true;

   return true;

  }

  else if (!this->beamlets.at(beamletNumber-1).isOpen())
  {

   return false;

  }

  // left (outside) min(left) and right (outside) max(right) leaves
  else if ((this->beamlets.at(beamletNumber-1).right-b1.left >EPSILON2)&&(b1.right-this->beamlets.at(beamletNumber-1).left>EPSILON2))
  {

   if (this->beamlets.at(beamletNumber).open) return false;

   else if (!this->beamlets.at(beamletNumber).open)
   {
   this->beamlets.at(beamletNumber).setLeftRight(b1.left,b1.right);
   this->beamlets.at(beamletNumber).isAssigned=true;

   this->isSet=true;
   return true;
   }
  }

  else return false;

}

Note that if the "this->isSet=true;" lines are commented out the error does not manifest itself regardless of the number of structures :yes it works with 6! The "isSet" boolean value is used to determine which objects have been set, and hence which objects need to be written out to a data file for further processing.

System and sodtware:

gcc (SUSE Linux) 4.4.1 [gcc-4_4-branch revision 150839]
SuSE 11.2 64bit
Intel Celsius with 4 Xeon 2.66GHz CPUs and 4GB RAM
Eclipse CDT (IDE) 64 bit Build 20100218-1602


答:
var $p = $('p'),
    text = $p.text().trim(),
    replaceWith = text.replace(/\(.+\)/, '$&');

$p.html(replaceWith)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>span {color: red}</code>```

width (10mm)
```

Title: How do I insert a span in a string?

Body:
var $p = $('p'),
    text = $p.text().trim(),
    replaceWith = text.replace(/\(.+\)/, '<span>$&</span>');

$p.html(replaceWith)

span {color: red}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>width (10mm)</p>


问:
Array function with number at position returning zero
I am new to javascript and was trying this code below.

This code was working properly but seems now its only returning -1.

Array.prototype.nthIndexOf = function (element,location) {
    var index = -1;
    for(var i=0; i< this.length; i++) {
        if(element === this[i] && !--location) {
            index = i;
            break;
        }
    }
    return index;
}

var findNumber = prompt("Please enter number to be found");
var positionAt = prompt("Please enter position");

var position = [1, 2, 3, 3, 2, 89, 34, 12].nthIndexOf(findNumber, positionAt);
console.log(position); // position is -1 all the time```

答:
Currently, it is comparing with the string value of prompt(). It always returns a string and you are also making a === strict comparison, including type. Use a parseInt() so that it correctly typecasts.

```<code>Array.prototype.nthIndexOf = function(element, location) {
  var index = -1;
  element = parseInt(element, 10);
  for (var i = 0; i < this.length; i++) {
    if (element === parseInt(this[i]) && !--location) {
      index = i;
      break;
    }
  }
  return index;
}
</code>```

Snippet

Array.prototype.nthIndexOf = function(element, location) {
  var index = -1;
  element = parseInt(element, 10);
  for (var i = 0; i < this.length; i++) {
    if (element === parseInt(this[i]) && !--location) {
      index = i;
      break;
    }
  }
  return index;
}

var findNumber = prompt("Please enter number to be found");
var positionAt = prompt("Please enter position");

var position = [1, 2, 3, 3, 2, 89, 34, 12].nthIndexOf(findNumber, positionAt);
console.log(position); // position is -1 all the time```

Instead of all these, you can use Array.prototype.indexOf!

Body:
Currently, it is comparing with the string value of prompt(). It always returns a string and you are also making a === strict comparison, including type. Use a parseInt() so that it correctly typecasts.

Array.prototype.nthIndexOf = function(element, location) {
  var index = -1;
  element = parseInt(element, 10);
  for (var i = 0; i < this.length; i++) {
    if (element === parseInt(this[i]) && !--location) {
      index = i;
      break;
    }
  }
  return index;
}

Snippet

Array.prototype.nthIndexOf = function(element, location) {
  var index = -1;
  element = parseInt(element, 10);
  for (var i = 0; i < this.length; i++) {
    if (element === parseInt(this[i]) && !--location) {
      index = i;
      break;
    }
  }
  return index;
}

var findNumber = prompt("Please enter number to be found");
var positionAt = prompt("Please enter position");

var position = [1, 2, 3, 3, 2, 89, 34, 12].nthIndexOf(findNumber, positionAt);
console.log(position); // position is -1 all the time

Instead of all these, you can use Array.prototype.indexOf!


问:
Android Internet connectivity check better method
According to the Android developer site, Determining and Monitoring the Connectivity Status, we can check there is an active Internet connection. But this is not working if even only Wi-Fi is connected and not Internet available (it notifies there is an Internet connection).

Now I ping a website and check whether Internet connections are available or not. And this method needs some more processing time. Is there a better method for checking Internet connectivity than this to avoid the time delay in ping the address?

答:
The first problem you should make it clear is what do you mean by whether internet is available?

Not connected to wifi or cellular network;

Connected to a limited wifi: e.g. In a school network, if you connect to school wifi, you can access intranet directly. But you have to log in with school account to access extranet. In this case, if you ping extranet website, you may receive response because some intranet made auto redirect to login page;

Connected to unlimited wifi: you are free to access most websites;

The second problem is what do you want to achieve?

As far as I understand your description, you seems want to test the connection of network and remind user if it fails. So I recommend you just ping your server, which is always fine if you want to exchange data with it.

You wonder whether there is a better way to test connectivity, and the answer is no.

The current TCP/IP network is virtual circuit, packet-switched network, which means there is no a fixed 'path' for the data to run, i.e. not like a telephone, we have a real connection between two users, we can know the connection is lost immediately after circuit is broken. We have to send a packet to the destination, and find no response, then we know, we lose the connection (which is what ping -- ICMP protocol -- does).

In conclusion, we have no better way to test the connectivity to a host other than ping it, that is why heartbeat is used in service management.


问:
Set a range in Excel based on values of corresponding cells
I have 2 columns in Excel, like this:

Col1 Col2

A     1

B     2

C     4

C     1

A     13

B     5

I need to generate 3 ranges in excel containing the values in Col2 , based on the distinct values of Col1.
Thus:
Name Range A will have values 1,13
Name Range B will have values 2,5
Name Range C will have values 1,4

How can I do it?

答:
Enter the following formula in Cell D2

```<code>=IFERROR(INDEX($B$2:$B$17, MATCH(0, IF(D$1=$A$2:$A$17, COUNTIF(D$1:D1, $B$2:$B$17), ""), 0)),"")
</code>```

Drag/Copy down and across as required.

This is an array formula so commit it by pressing Ctrl+Shift+Enter. See image for reference.

EDIT:________________________________

Try this:

```<code>=IFERROR(INDEX($B$2:$B$18, SMALL(IF(D$1=$A$2:$A$18, ROW($A$2:$A$18)-1, ""), ROW(A1))),"")
</code>```

Again this is an array formula.

Body:
Enter the following formula in Cell D2

=IFERROR(INDEX($B$2:$B$17, MATCH(0, IF(D$1=$A$2:$A$17, COUNTIF(D$1:D1, $B$2:$B$17), ""), 0)),"")

Drag/Copy down and across as required.

This is an array formula so commit it by pressing Ctrl+Shift+Enter. See image for reference.

EDIT:________________________________

Try this:

=IFERROR(INDEX($B$2:$B$18, SMALL(IF(D$1=$A$2:$A$18, ROW($A$2:$A$18)-1, ""), ROW(A1))),"")

Again this is an array formula.


问:
Why is the following C++ code printing only the first character?
I am trying to convert a char string to a wchar string.

In more detail: I am trying to convert a char[] to a wchar[] first and then append " 1" to that string and the print it.

```<code>char src[256] = "c:\\user";

wchar_t temp_src[256];
mbtowc(temp_src, src, 256);

wchar_t path[256];

StringCbPrintf(path, 256, _T("%s 1"), temp_src);
wcout << path;
</code>```

But it prints just c

Is this the right way to convert from char to wchar? I have come to know of another way since. But I'd like to know why the above code works the way it does?

答:
mbtowc converts only a single character. Did you mean to use mbstowcs?

Typically you call this function twice; the first to obtain the required buffer size, and the second to actually convert it:

```<code>#include <cstdlib> // for mbstowcs

const char* mbs = "c:\\user";
size_t requiredSize = ::mbstowcs(NULL, mbs, 0);
wchar_t* wcs = new wchar_t[requiredSize + 1];
if(::mbstowcs(wcs, mbs, requiredSize + 1) != (size_t)(-1))
{
    // Do what's needed with the wcs string
}
delete[] wcs;
</code>```

If you rather use mbstowcs_s (because of deprecation warnings), then do this:

```<code>#include <cstdlib> // also for mbstowcs_s

const char* mbs = "c:\\user";
size_t requiredSize = 0;
::mbstowcs_s(&requiredSize, NULL, 0, mbs, 0);
wchar_t* wcs = new wchar_t[requiredSize + 1];
::mbstowcs_s(&requiredSize, wcs, requiredSize + 1, mbs, requiredSize);
if(requiredSize != 0)
{
    // Do what's needed with the wcs string
}
delete[] wcs;
</code>```

Make sure you take care of locale issues via setlocale() or using the versions of mbstowcs() (such as mbstowcs_l() or mbstowcs_s_l()) that takes a locale argument.

Body:
I am trying to convert a char string to a wchar string.

In more detail: I am trying to convert a char[] to a wchar[] first and then append " 1" to that string and the print it.

char src[256] = "c:\\user";

wchar_t temp_src[256];
mbtowc(temp_src, src, 256);

wchar_t path[256];

StringCbPrintf(path, 256, _T("%s 1"), temp_src);
wcout << path;

But it prints just c

Is this the right way to convert from char to wchar? I have come to know of another way since. But I'd like to know why the above code works the way it does?

Body:
mbtowc converts only a single character. Did you mean to use mbstowcs?

Typically you call this function twice; the first to obtain the required buffer size, and the second to actually convert it:

#include <cstdlib> // for mbstowcs

const char* mbs = "c:\\user";
size_t requiredSize = ::mbstowcs(NULL, mbs, 0);
wchar_t* wcs = new wchar_t[requiredSize + 1];
if(::mbstowcs(wcs, mbs, requiredSize + 1) != (size_t)(-1))
{
    // Do what's needed with the wcs string
}
delete[] wcs;

If you rather use mbstowcs_s (because of deprecation warnings), then do this:

#include <cstdlib> // also for mbstowcs_s

const char* mbs = "c:\\user";
size_t requiredSize = 0;
::mbstowcs_s(&requiredSize, NULL, 0, mbs, 0);
wchar_t* wcs = new wchar_t[requiredSize + 1];
::mbstowcs_s(&requiredSize, wcs, requiredSize + 1, mbs, requiredSize);
if(requiredSize != 0)
{
    // Do what's needed with the wcs string
}
delete[] wcs;

Make sure you take care of locale issues via setlocale() or using the versions of mbstowcs() (such as mbstowcs_l() or mbstowcs_s_l()) that takes a locale argument.


问:
Odoo 10 adding field to sale order line
I am trying to code a module to provide a markup cell in each sale order line for quotes (Odoo 10). But I consistently get an error while loading the quote/sale order. Any help is welcomed.

This is the view:

```<code><?xml version="1.0"?>
<odoo>
    <record id="view_order_form_markup model" model="ir.ui.view">
        <field name="name">sale.order.form.markup</field>
        <field name="model">sale.order</field>
        <field name="inherit_id" ref="sale.view_order_form"/>
        <field name="arch" type="xml">
            <xpath expr='//field[@name="order_line"]/form/group/group/field[@name="price_unit"]' position="before">
                <label for="markup" string="Markup"/><field name="markup"/>
                <label for="markup_per" string="Markup (%)"/><field name="markup_per"/>
            </xpath>
            <xpath expr='//field[@name="order_line"]/tree/field[@name="price_unit"]' position="before">
                <label for="markup" string="Markup"/><field name="markup"/>
                <label for="markup_per" string="Markup (%)"/><field name="markup_per"/>
            </xpath>
        </field>
    </record>
</odoo>
</code>```

And the model:

```<code># -*- coding: utf-8 -*-

from odoo import api, fields, models
import odoo.addons.decimal_precision as dp

class SaleOrderLine(models.Model):
    _inherit = "sale.order.line"

    markup = fields.Float(compute='_compute_markup', digits=dp.get_precision('.2f%'), store=False, readonly=True)
    markup_per = fields.Float(compute='_compute_markup_per', digits=dp.get_precision('.2f%'), store=False, readonly=False)

    @api.depends('price_unit', 'purchase_price')
    def _compute_markup(self):
        for record in self:
            if record.price_unit and record.purchase_price:
                record.markup = record.price_unit - record.purchase_price

    @api.depends('price_unit', 'purchase_price')
    def _compute_markup_per(self):
        for record in self:
            if record.purchase_price > 0:
                record.markup_per = 100.0 * (record.price_unit - record.purchase_price) / record.purchase_price

    @api.onchange('markup_per')
    def _onchange_markup_per(self):
            if self.markup_per:
                if self.markup_per > -9999.99 and self.markup_per < 9999.99:
                    self.price_unit = self.purchase_price * (1 + self.markup_per / 100.0)
</code>```

But I am getting this error when I open a quote/sales order:

Uncaught TypeError: Type is not a constructor
  http://localhost:8369/web/content/365-ad86b81/web.assets_backend.js:2119
  Traceback: TypeError: Type is not a constructor
      at for_ (http://localhost:8369/web/content/365-ad86b81/web.assets_backend.js:2119:1208)
      at http://localhost:8369/web/content/365-ad86b81/web.assets_backend.js:2035:312
      at Function..map..collect (http://localhost:8369/web/content/319-32fb078/web.assets_common.js:13:270)
      at _.(anonymous function) [as map] (http://localhost:8369/web/content/319-32fb078/web.assets_common.js:69:526)
      at Class.setup_columns (http://localhost:8369/web/content/365-ad86b81/web.assets_backend.js:2035:261)
      at Class. (http://localhost:8369/web/content/365-ad86b81/web.assets_backend.js:2036:480)
      at http://localhost:8369/web/content/365-ad86b81/web.assets_backend.js:2099:11
      at Object. (http://localhost:8369/web/content/319-32fb078/web.assets_common.js:3202:136)
      at Object. (http://localhost:8369/web/content/319-32fb078/web.assets_common.js:547:681)
      at fire (http://localhost:8369/web/content/319-32fb078/web.assets_common.js:541:299)

答:
Remove  from tree view definition. Use attribute string to change label.

Try below code.

```<code> <record id="view_order_form_markup_model" model="ir.ui.view">
      <field name="name">sale.order.form.markup</field>
      <field name="model">sale.order</field>
      <field name="inherit_id" ref="sale.view_order_form"/>
      <field name="arch" type="xml">
          <xpath expr='//field[@name="order_line"]/form/group/group/field[@name="price_unit"]' position="before">
              <label for="markup" string="Markup"/><field name="markup"/>
              <label for="markup_per" string="Markup (%)"/><field name="markup_per"/>
          </xpath>
          <xpath expr='//field[@name="order_line"]/tree/field[@name="price_unit"]' position="after">
            <field name="markup"/>
            <field name="markup_per" string="Markup (%)"/>
          </xpath>
      </field>
  </record>
</code>```

Hope this will help you.

Title: Odoo 10 adding field to sale order line

Body:
I am trying to code a module to provide a markup cell in each sale order line for quotes (Odoo 10). But I consistently get an error while loading the quote/sale order. Any help is welcomed.

This is the view:

<?xml version="1.0"?>
<odoo>
    <record id="view_order_form_markup model" model="ir.ui.view">
        <field name="name">sale.order.form.markup</field>
        <field name="model">sale.order</field>
        <field name="inherit_id" ref="sale.view_order_form"/>
        <field name="arch" type="xml">
            <xpath expr='//field[@name="order_line"]/form/group/group/field[@name="price_unit"]' position="before">
                <field name="markup"/>
                <field name="markup_per"/>
            </xpath>
            <xpath expr='//field[@name="order_line"]/tree/field[@name="price_unit"]' position="before">
                <field name="markup"/>
                <field name="markup_per"/>
            </xpath>
        </field>
    </record>
</odoo>

And the model:

# -*- coding: utf-8 -*-

from odoo import api, fields, models
import odoo.addons.decimal_precision as dp

class SaleOrderLine(models.Model):
    _inherit = "sale.order.line"

    markup = fields.Float(compute='_compute_markup', digits=dp.get_precision('.2f%'), store=False, readonly=True)
    markup_per = fields.Float(compute='_compute_markup_per', digits=dp.get_precision('.2f%'), store=False, readonly=False)

    @api.depends('price_unit', 'purchase_price')
    def _compute_markup(self):
        for record in self:
            if record.price_unit and record.purchase_price:
                record.markup = record.price_unit - record.purchase_price

    @api.depends('price_unit', 'purchase_price')
    def _compute_markup_per(self):
        for record in self:
            if record.purchase_price > 0:
                record.markup_per = 100.0 * (record.price_unit - record.purchase_price) / record.purchase_price

    @api.onchange('markup_per')
    def _onchange_markup_per(self):
            if self.markup_per:
                if self.markup_per > -9999.99 and self.markup_per < 9999.99:
                    self.price_unit = self.purchase_price * (1 + self.markup_per / 100.0)

But I am getting this error when I open a quote/sales order:

Uncaught TypeError: Type is not a constructor
  http://localhost:8369/web/content/365-ad86b81/web.assets_backend.js:2119
  Traceback: TypeError: Type is not a constructor
      at for_ (http://localhost:8369/web/content/365-ad86b81/web.assets_backend.js:2119:1208)
      at http://localhost:8369/web/content/365-ad86b81/web.assets_backend.js:2035:312
      at Function..map..collect (http://localhost:8369/web/content/319-32fb078/web.assets_common.js:13:270)
      at _.(anonymous function) [as map] (http://localhost:8369/web/content/319-32fb078/web.assets_common.js:69:526)
      at Class.setup_columns (http://localhost:8369/web/content/365-ad86b81/web.assets_backend.js:2035:261)
      at Class. (http://localhost:8369/web/content/365-ad86b81/web.assets_backend.js:2036:480)
      at http://localhost:8369/web/content/365-ad86b81/web.assets_backend.js:2099:11
      at Object. (http://localhost:8369/web/content/319-32fb078/web.assets_common.js:3202:136)
      at Object. (http://localhost:8369/web/content/319-32fb078/web.assets_common.js:547:681)
      at fire (http://localhost:8369/web/content/319-32fb078/web.assets_common.js:541:299)

Body:
Remove <label> from tree view definition. Use attribute string to change label.

Try below code.

 <record id="view_order_form_markup_model" model="ir.ui.view">
      <field name="name">sale.order.form.markup</field>
      <field name="model">sale.order</field>
      <field name="inherit_id" ref="sale.view_order_form"/>
      <field name="arch" type="xml">
          <xpath expr='//field[@name="order_line"]/form/group/group/field[@name="price_unit"]' position="before">
              <label for="markup" string="Markup"/><field name="markup"/>
              <label for="markup_per" string="Markup (%)"/><field name="markup_per"/>
          </xpath>
          <xpath expr='//field[@name="order_line"]/tree/field[@name="price_unit"]' position="after">
            <field name="markup"/>
            <field name="markup_per" string="Markup (%)"/>
          </xpath>
      </field>
  </record>

Hope this will help you.


答:
For Question 1, a set is a good choice for quickly and easily calculating intersections.
For Question 2, a dictionary works well.

For example:

```<code>facebook_profile={
    "John":{"friends":{"friend1","friend2","friend3","friend4"},"Gender": "Male"},
    "Mary":{"friends":{"friend1","friend7","friend3","friend9"},"Gender": "Female"}
}
mutual_friends = facebook_profile["John"]["friends"].intersection(facebook_profile["Mary"]["friends"])
print (mutual_friends)
</code>```

Gives output:

```<code>{'friend1', 'friend3'}
</code>```

Title: The best suggestion for a structure to store multiple keys and values - dictionaries?

Body:
For Question 1, a set is a good choice for quickly and easily calculating intersections.
For Question 2, a dictionary works well.

For example:

facebook_profile={
    "John":{"friends":{"friend1","friend2","friend3","friend4"},"Gender": "Male"},
    "Mary":{"friends":{"friend1","friend7","friend3","friend9"},"Gender": "Female"}
}
mutual_friends = facebook_profile["John"]["friends"].intersection(facebook_profile["Mary"]["friends"])
print (mutual_friends)

Gives output:

{'friend1', 'friend3'}


问:
ng-repeat is Working perfectly with static json But fires exception with dynamic json data
I have a ng-repeat put on a list to display in table.

the script html code is like this :

```<code>`<tr ng-repeat="user in users track by $index" ng-class="{'selected':$index == selectedRow}">
                    <td>
                        {{user.FirstName}}
                    </td>
                    <td>
                        {{user.LastName}}
                    </td>
                    <td>
                        {{user.EmailId}}
                    </td>
                    <td>
                        {{user.ContactNumber}}
                    </td>
                    <td>
                        <button type="button" class="btn btn-warning">
                            <span class="glyphicon glyphicon-pencil"></span>
                        </button>
                        <button type="button" class="btn btn-danger">
                            <span class="glyphicon glyphicon-remove"></span>
                        </button>
                    </td>
                </tr>`
</code>```

and in angular script the routing is defined as bellow:

```<code>var routingApp = angular.module('App', []);
routingApp.controller("MovieController", ['$scope', '$http', function ($scope, $http) {

$scope.edit = false;
$scope.error = false;
$scope.success = false;
//TO DO : Below portion to be replaced with ajax call to get list of movies from DB
var users = [
    { "UserId": 1, "FirstName": "user", "LastName": "1", "EmailId": "user1@gmail.com", "ContactNumber": 1234567890, "UserName": "User1", "Password": "Welcome@1" },
    { "UserId": 2, "FirstName": "user", "LastName": "2", "EmailId": "user2_1993@gmail.com", "ContactNumber": 7894612305, "UserName": "User2", "Password": "Welcome@2" },
    { "UserId": 3, "FirstName": "user", "LastName": "3", "EmailId": "user3@gmail.com", "ContactNumber": 1472583690, "UserName": "User3", "Password": "Welcome@3" },
    { "UserId": 4, "FirstName": "user", "LastName": "4", "EmailId": "user4@gmail.com", "ContactNumber": 7531598520, "UserName": "User4", "Password": "Welcome@4" },
    { "UserId": 5, "FirstName": "User", "LastName": "5", "EmailId": "user5@gmail.com", "ContactNumber": 4785961235, "UserName": "user5", "Password": "Welcome@5" }
];
console.log(users); //debugger;
    $scope.users = users;

}]);
</code>```

This part is working absolutely fine.

but when i replace the static json data ie;

```<code> var users = [
    { "UserId": 1, "FirstName": "user", "LastName": "1", "EmailId": "user1@gmail.com", "ContactNumber": 1234567890, "UserName": "User1", "Password": "Welcome@1" },
    { "UserId": 2, "FirstName": "user", "LastName": "2", "EmailId": "user2_1993@gmail.com", "ContactNumber": 7894612305, "UserName": "User2", "Password": "Welcome@2" },
    { "UserId": 3, "FirstName": "user", "LastName": "3", "EmailId": "user3@gmail.com", "ContactNumber": 1472583690, "UserName": "User3", "Password": "Welcome@3" },
    { "UserId": 4, "FirstName": "user", "LastName": "4", "EmailId": "user4@gmail.com", "ContactNumber": 7531598520, "UserName": "User4", "Password": "Welcome@4" },
    { "UserId": 5, "FirstName": "User", "LastName": "5", "EmailId": "user5@gmail.com", "ContactNumber": 4785961235, "UserName": "user5", "Password": "Welcome@5" }
];
</code>```

with

```<code>$http.get("http://localhost:82/api/User/GetAllUsers")
.then(function (response) {
    dt = JSON.stringify(response.data);
    $scope.users = dt;
    //console.log(dt);
    //console.log(JSON.parse(dt));
})
</code>```

it will through this exception :

```<code>`[ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: user in users, Duplicate key: string:", Duplicate value`
</code>```

But the output of the api is exactly same as static json, in fact i have copied json from api output itself.

Even i have tried removing  track by $index but No luck.
are there any solutions to this issue?

答:
try with below code</p>

```<code> $http.get("http://localhost:82/api/User/GetAllUsers")
.then(function (response) {
dt = JSON.stringify(response.data);
$scope.users = response.data;

})
</code>```

Body:
I have a ng-repeat put on a list to display in table.

the script html code is like this :

`

                        {{user.FirstName}}

                        {{user.LastName}}

                        {{user.EmailId}}

                        {{user.ContactNumber}}

                        <button type="button" class="btn btn-warning">

                        </button>
                        <button type="button" class="btn btn-danger">

                        </button>

`

and in angular script the routing is defined as bellow:

var routingApp = angular.module('App', []);
routingApp.controller("MovieController", ['$scope', '$http', function ($scope, $http) {

$scope.edit = false;
$scope.error = false;
$scope.success = false;
//TO DO : Below portion to be replaced with ajax call to get list of movies from DB
var users = [
    { "UserId": 1, "FirstName": "user", "LastName": "1", "EmailId": "user1@gmail.com", "ContactNumber": 1234567890, "UserName": "User1", "Password": "Welcome@1" },
    { "UserId": 2, "FirstName": "user", "LastName": "2", "EmailId": "user2_1993@gmail.com", "ContactNumber": 7894612305, "UserName": "User2", "Password": "Welcome@2" },
    { "UserId": 3, "FirstName": "user", "LastName": "3", "EmailId": "user3@gmail.com", "ContactNumber": 1472583690, "UserName": "User3", "Password": "Welcome@3" },
    { "UserId": 4, "FirstName": "user", "LastName": "4", "EmailId": "user4@gmail.com", "ContactNumber": 7531598520, "UserName": "User4", "Password": "Welcome@4" },
    { "UserId": 5, "FirstName": "User", "LastName": "5", "EmailId": "user5@gmail.com", "ContactNumber": 4785961235, "UserName": "user5", "Password": "Welcome@5" }
];
console.log(users); //debugger;
    $scope.users = users;

}]);

This part is working absolutely fine.

but when i replace the static json data ie;

 var users = [
    { "UserId": 1, "FirstName": "user", "LastName": "1", "EmailId": "user1@gmail.com", "ContactNumber": 1234567890, "UserName": "User1", "Password": "Welcome@1" },
    { "UserId": 2, "FirstName": "user", "LastName": "2", "EmailId": "user2_1993@gmail.com", "ContactNumber": 7894612305, "UserName": "User2", "Password": "Welcome@2" },
    { "UserId": 3, "FirstName": "user", "LastName": "3", "EmailId": "user3@gmail.com", "ContactNumber": 1472583690, "UserName": "User3", "Password": "Welcome@3" },
    { "UserId": 4, "FirstName": "user", "LastName": "4", "EmailId": "user4@gmail.com", "ContactNumber": 7531598520, "UserName": "User4", "Password": "Welcome@4" },
    { "UserId": 5, "FirstName": "User", "LastName": "5", "EmailId": "user5@gmail.com", "ContactNumber": 4785961235, "UserName": "user5", "Password": "Welcome@5" }
];

with

$http.get("http://localhost:82/api/User/GetAllUsers")
.then(function (response) {
    dt = JSON.stringify(response.data);
    $scope.users = dt;
    //console.log(dt);
    //console.log(JSON.parse(dt));
})

it will through this exception :

`[ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: user in users, Duplicate key: string:", Duplicate value`

But the output of the api is exactly same as static json, in fact i have copied json from api output itself.

Even i have tried removing  track by $index but No luck.
are there any solutions to this issue?

Body:
try with below code

 $http.get("http://localhost:82/api/User/GetAllUsers")
.then(function (response) {
dt = JSON.stringify(response.data);
$scope.users = response.data;

})


问:
unable to select top 10 records per group in sparksql
Hi I am new to spark sql. I have a data frame like this.

```<code>  ---+----------+----+----+----+------------------------+
 |tag id|timestamp|listner| orgid |org2id|RSSI
 +---+----------+----+----+----+------------------------+
 |  4|1496745912| 362|   4|   3|                    0.60|
 |  4|1496745924|1901|   4|   3|                    0.60|
 |  4|1496746030|1901|   4|   3|                    0.60|
 |  4|1496746110| 718|   4|   3|                    0.30|
 |  2|1496746128| 718|   4|   3|                    0.60|
 |  2|1496746188|1901|   4|   3|                    0.10|
</code>```

I want to select for each listner top 10 timestamp values in spark sql.

I tried the following query.It throws errors.

```<code>  val avg = sqlContext.sql("select top 10 * from avg_table") // throws error.

  val avg = sqlContext.sql("select rssi,timestamp,tagid from avg_table order by desc limit 10")  // it prints only 10 records.
</code>```

I want to select for each listner I need to take top 10 timestamp values. Any help will be appreciated.

答:
Doesn't this work?

```<code>select rssi, timestamp, tagid
from avg_table
order by timestamp desc
limit 10;
</code>```

EDIT:

Oh, I get it.  You want row_number():

```<code>select rssi, timestamp, tagid
from (select a.*,
             row_number() over (partition by listner order by timestamp desc) as seqnum
      from avg_table
     ) a
where seqnum <= 10
order by a.timestamp desc;
</code>```

Body:
Hi I am new to spark sql. I have a data frame like this.

  ---+----------+----+----+----+------------------------+
 |tag id|timestamp|listner| orgid |org2id|RSSI
 +---+----------+----+----+----+------------------------+
 |  4|1496745912| 362|   4|   3|                    0.60|
 |  4|1496745924|1901|   4|   3|                    0.60|
 |  4|1496746030|1901|   4|   3|                    0.60|
 |  4|1496746110| 718|   4|   3|                    0.30|
 |  2|1496746128| 718|   4|   3|                    0.60|
 |  2|1496746188|1901|   4|   3|                    0.10|

I want to select for each listner top 10 timestamp values in spark sql.

I tried the following query.It throws errors.

  val avg = sqlContext.sql("select top 10 * from avg_table") // throws error.

  val avg = sqlContext.sql("select rssi,timestamp,tagid from avg_table order by desc limit 10")  // it prints only 10 records.

I want to select for each listner I need to take top 10 timestamp values. Any help will be appreciated.

Body:
Doesn't this work?

select rssi, timestamp, tagid
from avg_table
order by timestamp desc
limit 10;

EDIT:

Oh, I get it.  You want row_number():

select rssi, timestamp, tagid
from (select a.*,
             row_number() over (partition by listner order by timestamp desc) as seqnum
      from avg_table
     ) a
where seqnum <= 10
order by a.timestamp desc;


问:
Xamarin App crashes calling HTTPS
I created a simple Xamarin.Forms App to check HTTPS using https://jsonplaceholder.typicode.com/.

But the App crashes using HTTPS.

```<code> public RestService() {
      client = new HttpClient();
      client.MaxResponseContentBufferSize = 256000;
    }

public async Task<List<Item>> RefreshDataAsync() {
  string url = "http://jsonplaceholder.typicode.com/posts";
  // Crash using this URL
  //string url = "https://jsonplaceholder.typicode.com/posts";
  var uri = new Uri(string.Format(url, string.Empty));
  List<Item> Items = new List<Item>();

  var content = await client.GetStringAsync(uri);
    Items = JsonConvert.DeserializeObject<List<Item>>(content);

  return Items;
}
}
</code>```

Is it a problem with the website or httpClient or do I do somethin wrong ?

Thats the Exception

```<code>{System.Net.Http.HttpRequestException: An error occurred while sending the request ---> System.Net.WebException: Error: SecureChannelFailure (The authentication or decryption has failed.) ---> System.IO.IOException: The authentication or decryption has failed. ---> System.IO.IOException: The authentication or decryption has failed. ---> Mono.Security.Protocol.Tls.TlsException: The authentication or decryption has failed.
  at Mono.Security.Protocol.Tls.RecordProtocol.EndReceiveRecord (System.IAsyncResult asyncResult) [0x00037] in <d2bf9ddce2b945f79db1e7c4354bafea>:0
  at Mono.Security.Protocol.Tls.SslClientStream.SafeEndReceiveRecord (System.IAsyncResult ar, System.Boolean ignoreEmpty) [0x00000] in <d2bf9ddce2b945f79db1e7c4354bafea>:0
  at Mono.Security.Protocol.Tls.SslClientStream.NegotiateAsyncWorker (System.IAsyncResult result) [0x00071] in <d2bf9ddce2b945f79db1e7c4354bafea>:0
   --- End of inner exception stack trace ---
  at Mono.Security.Protocol.Tls.SslClientStream.EndNegotiateHandshake (System.IAsyncResult result) [0x00032] in <d2bf9ddce2b945f79db1e7c4354bafea>:0
  at Mono.Security.Protocol.Tls.SslStreamBase.AsyncHandshakeCallback (System.IAsyncResult asyncResult) [0x0000c] in <d2bf9ddce2b945f79db1e7c4354bafea>:0
   --- End of inner exception stack trace ---
  at Mono.Security.Protocol.Tls.SslStreamBase.EndRead (System.IAsyncResult asyncResult) [0x0004b] in <d2bf9ddce2b945f79db1e7c4354bafea>:0
  at Mono.Net.Security.Private.LegacySslStream.EndAuthenticateAsClient (System.IAsyncResult asyncResult) [0x0000e] in <a547bd0d78184f26ab08d022f013c1e1>:0
  at Mono.Net.Security.Private.LegacySslStream.AuthenticateAsClient (System.String targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, System.Boolean checkCertificateRevocation) [0x0000e] in <a547bd0d78184f26ab08d022f013c1e1>:0
  at Mono.Net.Security.MonoTlsStream.CreateStream (System.Byte[] buffer) [0x0007b] in <a547bd0d78184f26ab08d022f013c1e1>:0
  at System.Net.WebConnection.CreateStream (System.Net.HttpWebRequest request) [0x00073] in <a547bd0d78184f26ab08d022f013c1e1>:0
   --- End of inner exception stack trace ---
  at System.Net.HttpWebRequest.EndGetResponse (System.IAsyncResult asyncResult) [0x00058] in <a547bd0d78184f26ab08d022f013c1e1>:0
  at System.Threading.Tasks.TaskFactory`1[TResult].FromAsyncCoreLogic (System.IAsyncResult iar, System.Func`2[T,TResult] endFunction, System.Action`1[T] endAction, System.Threading.Tasks.Task`1[TResult] promise, System.Boolean requiresSynchronization) [0x0000f] in <3fd174ff54b146228c505f23cf75ce71>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Net.Http.HttpClientHandler+<SendAsync>d__63.MoveNext () [0x003e6] in <b696532a7c264e5e866cb15a1b40a4a4>:0
   --- End of inner exception stack trace ---
  at System.Net.Http.HttpClientHandler+<SendAsync>d__63.MoveNext () [0x00449] in <b696532a7c264e5e866cb15a1b40a4a4>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Net.Http.HttpClient+<SendAsyncWorker>d__49.MoveNext () [0x000ca] in <b696532a7c264e5e866cb15a1b40a4a4>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Net.Http.HttpClient+<GetStringAsync>d__55.MoveNext () [0x0007d] in <b696532a7c264e5e866cb15a1b40a4a4>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
  at getWeather.RestService+<RefreshDataAsync>d__2.MoveNext () [0x0006e] in C:\Users\afelde\documents\visual studio 2017\Projects\getWeather\getWeather\getWeather\RestService.cs:30 }
</code>```

答:
That Post on Xamarin.Forum also solve the Issue without installing any Nuget Packages :

As @SvetlomirKalitsov describes, the two settings below take care of
  the issue:

HttpClient implementation -> AndroidClientHandler SSL/TLS
  implementation -> Native TLS 1Here is where I made the mistake: There
  are two pretty similar options: Native TLS 1.2+ which is the correct
  one, and Default (Native TLS 1.2+). This second one (Default) will
  fail. Make sure to select the non-default one; in other words, make
  sure to force that option instead of relying on the Default.

A bit of background info: XA_HTTP_CLIENT_HANDLER_TYPE environment
  variable on Xamarin.Android

Thanks @SvetlomirKalitsov

Title: Xamarin App crashes calling HTTPS

Body:
I created a simple Xamarin.Forms App to check HTTPS using https://jsonplaceholder.typicode.com/.

But the App crashes using HTTPS.

 public RestService() {
      client = new HttpClient();
      client.MaxResponseContentBufferSize = 256000;
    }

public async Task<List<Item>> RefreshDataAsync() {
  string url = "http://jsonplaceholder.typicode.com/posts";
  // Crash using this URL
  //string url = "https://jsonplaceholder.typicode.com/posts";
  var uri = new Uri(string.Format(url, string.Empty));
  List<Item> Items = new List<Item>();

  var content = await client.GetStringAsync(uri);
    Items = JsonConvert.DeserializeObject<List<Item>>(content);

  return Items;
}
}

Is it a problem with the website or httpClient or do I do somethin wrong ?

Thats the Exception

{System.Net.Http.HttpRequestException: An error occurred while sending the request ---> System.Net.WebException: Error: SecureChannelFailure (The authentication or decryption has failed.) ---> System.IO.IOException: The authentication or decryption has failed. ---> System.IO.IOException: The authentication or decryption has failed. ---> Mono.Security.Protocol.Tls.TlsException: The authentication or decryption has failed.
  at Mono.Security.Protocol.Tls.RecordProtocol.EndReceiveRecord (System.IAsyncResult asyncResult) [0x00037] in <d2bf9ddce2b945f79db1e7c4354bafea>:0
  at Mono.Security.Protocol.Tls.SslClientStream.SafeEndReceiveRecord (System.IAsyncResult ar, System.Boolean ignoreEmpty) [0x00000] in <d2bf9ddce2b945f79db1e7c4354bafea>:0
  at Mono.Security.Protocol.Tls.SslClientStream.NegotiateAsyncWorker (System.IAsyncResult result) [0x00071] in <d2bf9ddce2b945f79db1e7c4354bafea>:0
   --- End of inner exception stack trace ---
  at Mono.Security.Protocol.Tls.SslClientStream.EndNegotiateHandshake (System.IAsyncResult result) [0x00032] in <d2bf9ddce2b945f79db1e7c4354bafea>:0
  at Mono.Security.Protocol.Tls.SslStreamBase.AsyncHandshakeCallback (System.IAsyncResult asyncResult) [0x0000c] in <d2bf9ddce2b945f79db1e7c4354bafea>:0
   --- End of inner exception stack trace ---
  at Mono.Security.Protocol.Tls.SslStreamBase.EndRead (System.IAsyncResult asyncResult) [0x0004b] in <d2bf9ddce2b945f79db1e7c4354bafea>:0
  at Mono.Net.Security.Private.LegacySslStream.EndAuthenticateAsClient (System.IAsyncResult asyncResult) [0x0000e] in <a547bd0d78184f26ab08d022f013c1e1>:0
  at Mono.Net.Security.Private.LegacySslStream.AuthenticateAsClient (System.String targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, System.Boolean checkCertificateRevocation) [0x0000e] in <a547bd0d78184f26ab08d022f013c1e1>:0
  at Mono.Net.Security.MonoTlsStream.CreateStream (System.Byte[] buffer) [0x0007b] in <a547bd0d78184f26ab08d022f013c1e1>:0
  at System.Net.WebConnection.CreateStream (System.Net.HttpWebRequest request) [0x00073] in <a547bd0d78184f26ab08d022f013c1e1>:0
   --- End of inner exception stack trace ---
  at System.Net.HttpWebRequest.EndGetResponse (System.IAsyncResult asyncResult) [0x00058] in <a547bd0d78184f26ab08d022f013c1e1>:0
  at System.Threading.Tasks.TaskFactory`1[TResult].FromAsyncCoreLogic (System.IAsyncResult iar, System.Func`2[T,TResult] endFunction, System.Action`1[T] endAction, System.Threading.Tasks.Task`1[TResult] promise, System.Boolean requiresSynchronization) [0x0000f] in <3fd174ff54b146228c505f23cf75ce71>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Net.Http.HttpClientHandler+<SendAsync>d__63.MoveNext () [0x003e6] in <b696532a7c264e5e866cb15a1b40a4a4>:0
   --- End of inner exception stack trace ---
  at System.Net.Http.HttpClientHandler+<SendAsync>d__63.MoveNext () [0x00449] in <b696532a7c264e5e866cb15a1b40a4a4>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Net.Http.HttpClient+<SendAsyncWorker>d__49.MoveNext () [0x000ca] in <b696532a7c264e5e866cb15a1b40a4a4>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Net.Http.HttpClient+<GetStringAsync>d__55.MoveNext () [0x0007d] in <b696532a7c264e5e866cb15a1b40a4a4>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
  at getWeather.RestService+<RefreshDataAsync>d__2.MoveNext () [0x0006e] in C:\Users\afelde\documents\visual studio 2017\Projects\getWeather\getWeather\getWeather\RestService.cs:30 }


问:
How to open app from last opened activity even after its removed from recent task
My app has two activity one is sign in and second is main,I login from sign in activity and then I go to main activity, but when I remove my app from recent tasks and reopen it, it reopens from the sign in activity.

How to make it so that it reopens from the last closed activity i.e main in this case ?

答: After you have Logged In, Use a shared Preference to save that action and on the launcher activity just check the value stored for the same shared preference to check if you had logged in successfully last time or not.</p>