问:
Detect .Net 4.7 with Wix Installer 3.11
any ideas on how to handle .Net 4.7 in Wix?
The documentation only shows support for 462, unless I'm missing something.
http://wixtoolset.org/documentation/manual/v3/customactions/wixnetfxextension.html
I found this: http://dblock.github.io/dotnetinstaller/ But I have never use it.
Any advice is appreciated!

Tnx!

答:
The following fragment (modified from 4.6.2) should work when you add <PackageGroupRef Id="NetFx47Redist"/> in your bundle's Chain. This requires the offline installer (downloaded from the NetFx47RedistLink) to be present in the relative source path ..\Redist\NETFX47 folder for bundle compilation. You also need to add the NetFxExtension in your bundle's references and add `xmlns:netfx='http://schemas.microsoft.com/wix/NetFxExtension' in the bundle wxs.

```<code><Fragment>
    <?define NetFx47MinRelease = 460798 ?>
    <?define NetFx47WebLink = http://download.microsoft.com/download/A/E/A/AEAE0F3F-96E9-4711-AADA-5E35EF902306/NDP47-KB3186500-Web.exe ?>
    <?define NetFx47RedistLink = http://download.microsoft.com/download/D/D/3/DD35CC25-6E9C-484B-A746-C5BE0C923290/NDP47-KB3186497-x86-x64-AllOS-ENU.exe ?>
    <?define NetFx47EulaLink = http://referencesource.microsoft.com/license.html ?>

    <WixVariable Id="WixMbaPrereqPackageId" Value="NetFx47Redist" />
    <WixVariable Id="WixMbaPrereqLicenseUrl" Value="$(var.NetFx47EulaLink)" Overridable="yes" />
    <WixVariable Id="NetFx47RedistDetectCondition" Value="NETFRAMEWORK45 >= $(var.NetFx47MinRelease)" Overridable="yes" />
    <WixVariable Id="NetFx47RedistInstallCondition" Value="" Overridable="yes" />
    <WixVariable Id="NetFx47RedistPackageDirectory" Value="Redist\NETFX47\" Overridable="yes" />

    <PackageGroup Id="NetFx47Redist">
        <ExePackage
            DisplayName="Microsoft .NET Framework 4.7"
            InstallCommand="/q /norestart /ChainingPackage "[WixBundleName]" /log "[NetFx47FullLog].html""
            RepairCommand="/q /norestart /repair /ChainingPackage "[WixBundleName]" /log "[NetFx47FullLog].html""
            UninstallCommand="/uninstall /q /norestart /ChainingPackage "[WixBundleName]" /log "[NetFx47FullLog].html""
            PerMachine="yes"
            DetectCondition="!(wix.NetFx47RedistDetectCondition)"
            InstallCondition="!(wix.NetFx47RedistInstallCondition)"
            Id="NetFx47Redist"
            Vital="yes"
            Permanent="yes"
            Protocol="netfx4"
            DownloadUrl="$(var.NetFx47RedistLink)"
            LogPathVariable="NetFx47FullLog"
            Compressed="no"
            SourceFile="..\Redist\NETFX47\NDP47-KB3186497-x86-x64-AllOS-ENU.exe"
            Name="!(wix.NetFx47RedistPackageDirectory)NDP47-KB3186497-x86-x64-AllOS-ENU.exe"
        >
        </ExePackage>
    </PackageGroup>
</Fragment>
</code>```

You also need to add the following RegistrySearch which uses the Util extension, add it to the references and xmlns:util='http://schemas.microsoft.com/wix/UtilExtension' in the bundle.

```<code>        <util:RegistrySearch
            Id="NETFRAMEWORK45"
            Variable="NETFRAMEWORK45"
            Root="HKLM"
            Key="SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full"
            Value="Release"
            Result="value"
        />
</code>```

Title: Detect .Net 4.7 with Wix Installer 3.11

Body:
The following fragment (modified from 4.6.2) should work when you add <PackageGroupRef Id="NetFx47Redist"/> in your bundle's Chain. This requires the offline installer (downloaded from the NetFx47RedistLink) to be present in the relative source path ..\Redist\NETFX47 folder for bundle compilation. You also need to add the NetFxExtension in your bundle's references and add `xmlns:netfx='http://schemas.microsoft.com/wix/NetFxExtension' in the bundle wxs.

<Fragment>
    <?define NetFx47MinRelease = 460798 ?>
    <?define NetFx47WebLink = http://download.microsoft.com/download/A/E/A/AEAE0F3F-96E9-4711-AADA-5E35EF902306/NDP47-KB3186500-Web.exe ?>
    <?define NetFx47RedistLink = http://download.microsoft.com/download/D/D/3/DD35CC25-6E9C-484B-A746-C5BE0C923290/NDP47-KB3186497-x86-x64-AllOS-ENU.exe ?>
    <?define NetFx47EulaLink = http://referencesource.microsoft.com/license.html ?>

    <WixVariable Id="WixMbaPrereqPackageId" Value="NetFx47Redist" />
    <WixVariable Id="WixMbaPrereqLicenseUrl" Value="$(var.NetFx47EulaLink)" Overridable="yes" />
    <WixVariable Id="NetFx47RedistDetectCondition" Value="NETFRAMEWORK45 &gt;= $(var.NetFx47MinRelease)" Overridable="yes" />
    <WixVariable Id="NetFx47RedistInstallCondition" Value="" Overridable="yes" />
    <WixVariable Id="NetFx47RedistPackageDirectory" Value="Redist\NETFX47\" Overridable="yes" />

    <PackageGroup Id="NetFx47Redist">
        <ExePackage
            DisplayName="Microsoft .NET Framework 4.7"
            InstallCommand="/q /norestart /ChainingPackage &quot;[WixBundleName]&quot; /log &quot;[NetFx47FullLog].html&quot;"
            RepairCommand="/q /norestart /repair /ChainingPackage &quot;[WixBundleName]&quot; /log &quot;[NetFx47FullLog].html&quot;"
            UninstallCommand="/uninstall /q /norestart /ChainingPackage &quot;[WixBundleName]&quot; /log &quot;[NetFx47FullLog].html&quot;"
            PerMachine="yes"
            DetectCondition="!(wix.NetFx47RedistDetectCondition)"
            InstallCondition="!(wix.NetFx47RedistInstallCondition)"
            Id="NetFx47Redist"
            Vital="yes"
            Permanent="yes"
            Protocol="netfx4"
            DownloadUrl="$(var.NetFx47RedistLink)"
            LogPathVariable="NetFx47FullLog"
            Compressed="no"
            SourceFile="..\Redist\NETFX47\NDP47-KB3186497-x86-x64-AllOS-ENU.exe"
            Name="!(wix.NetFx47RedistPackageDirectory)NDP47-KB3186497-x86-x64-AllOS-ENU.exe"
        >
        </ExePackage>
    </PackageGroup>
</Fragment>

You also need to add the following RegistrySearch which uses the Util extension, add it to the references and xmlns:util='http://schemas.microsoft.com/wix/UtilExtension' in the bundle.

        <util:RegistrySearch
            Id="NETFRAMEWORK45"
            Variable="NETFRAMEWORK45"
            Root="HKLM"
            Key="SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full"
            Value="Release"
            Result="value"
        />


来源: stackexchange

问:
Dynamically creating asp.net with c# pages
I am struggling with finding clear answers to dynamically creating the same page over and over.  The questions and samples I have found seem to be all over the board on this topic.  I have studied the life cycle and still seem to not have a clear answer as to where code should go.

I have a master page and a content page.  All the content in the content area needs to be dynamically created (text boxes, ddl's, page tabs, buttons/onclick etc.).

After a user fills in data and clicks a submit button, I need to read the values off the form and rebuild the page completely again (not add/remove controls to current content).

My question is then.
Where do I put my code to build the page?
Will this area allow me to use IsPostBack so I can rebuild content with Request.Form values?
Will my buttons _Click events work?
Are there any working samples out there you could direct me to?

Thank you very much for the feedback...

答: What you need is a web user control, see ASP.NET User Controls</p>

ContentLicense: CC BY-SA 2.5


问:
error: control reaches end of non-void function:(
I know this has been asked before but still I couldn't find a fix. The program is supposed to sum all even digits in a number using recursion. Here's the code that produces the error control reaches end of non-void function:

```<code>#include<stdio.h>

int sum_even_d(unsigned long n);

int main()
{
    unsigned long n;
    int x;
    printf("Enter n : \n");
    scanf("%lu",&n);
    x=sum_even_d(n);
    printf("%d\n",x);
    return 0;

}

int sum_even_d(unsigned long n)
{
    if(n==0) return 0;
    if(n%2==0)
        return (sum_even_d(n/10)+n%10);//*error here*//
}
</code>```

If I add one line though, the program works perfectly. I don't understand what made the difference:

```<code>#include<stdio.h>

int sum_even_d(unsigned long n);

int main()
{
    unsigned long n;
    int x;
    printf("Enter n : \n");
    scanf("%lu",&n);
    x=sum_even_d(n);
    printf("%d\n",x);
    return 0;

    }

int sum_even_d(unsigned long n)
{
    if(n==0) return 0;
    if(n%2==0)
        return (sum_even_d(n/10)+n%10);
    else return (sum_even_d(n/10));//*added this*//
}
</code>```

答: In the first example, any odd number will cause the program to fall off the bottom of the function without a return.  The declared type, int, requires a return value.  When you added an else clause with a return value, you covered the remaining case with a value.

ContentLicense: CC BY-SA 3.0

Body:
I know this has been asked before but still I couldn't find a fix. The program is supposed to sum all even digits in a number using recursion. Here's the code that produces the error control reaches end of non-void function:

#include<stdio.h>

int sum_even_d(unsigned long n);

int main()
{
    unsigned long n;
    int x;
    printf("Enter n : \n");
    scanf("%lu",&n);
    x=sum_even_d(n);
    printf("%d\n",x);
    return 0;

}

int sum_even_d(unsigned long n)
{
    if(n==0) return 0;
    if(n%2==0)
        return (sum_even_d(n/10)+n%10);//*error here*//
}

If I add one line though, the program works perfectly. I don't understand what made the difference:

#include<stdio.h>

int sum_even_d(unsigned long n);

int main()
{
    unsigned long n;
    int x;
    printf("Enter n : \n");
    scanf("%lu",&n);
    x=sum_even_d(n);
    printf("%d\n",x);
    return 0;

    }

int sum_even_d(unsigned long n)
{
    if(n==0) return 0;
    if(n%2==0)
        return (sum_even_d(n/10)+n%10);
    else return (sum_even_d(n/10));//*added this*//
}


问:
How to achieve desired results in multidimensional array? C#
I am trying to achieve the output by using multidimensional array which I can get by using KeyValuePair.

Input:

```<code>var foodPair = new Dictionary<string, string>
{
    {"Pizza", "Italian"},
    {"Curry", "Indian"},
    {"Masala", "Indian"}
};

var teamPreference = new Dictionary<string, string>
{
    {"Jose", "Italian" },
    {"John", "Indian" },
    {"Sarah", "Thai" },
    {"Mary", "*" }
};

* means give everything
If selected food type is not available than give nothing. i.e Thai
</code>```

Output:

```<code>Jose, Pizza
John, Curry
John, Masala
Mary, Pizza
Mary, Curry
Mary, Masala
</code>```

Working Result by using KeyValuePair<string, string>:

https://dotnetfiddle.net/hNdlfy

I want to achieve same result by using string[,] but I don't know how to insert in dimensional array. Basically I am trying to learn how multidimensional arrays works by doing this kind of example.

答:
I used Extension method to achieve the desired result.

```<code>public static string[,] FoodPreferenceWithDimensionalArray()
{
    var foodPair = new Dictionary<string, string>
    {
        {"Pizza", "Italian"},
        {"Curry", "Indian"},
        {"Masala", "Indian"}
    };

    var teamPreference = new Dictionary<string, string>
    {
        {"Jose", "Italian" },
        {"John", "Indian" },
        {"Sarah", "Thai" },
        {"Mary", "*" }
    };

    var results = new List<KeyValuePair<string, string>>();
    foreach (var teamMember in teamPreference)
    {
        switch (teamMember.Key)
        {
            case "Jose":
                var italianDish = foodPair.FirstOrDefault(x => x.Value == "Italian").Key;
                results.Add(new KeyValuePair<string, string>(teamMember.Key, italianDish));
                break;

            case "John":
                var indianDish = foodPair.Where(x => x.Value == "Indian");
                if (indianDish.Any())
                {
                    results.AddRange(indianDish.Select(dish => new KeyValuePair<string, string>(teamMember.Key, dish.Key)));
                }
                break;

            case "Sarah":
                var thaiDish = foodPair.FirstOrDefault(x => x.Value == "Thai").Key;
                if (!string.IsNullOrEmpty(thaiDish))
                {
                    results.Add(new KeyValuePair<string, string>(teamMember.Key, thaiDish));
                }
                break;

            case "Mary":
                if (teamMember.Value == "*")
                {
                    var everything = foodPair.Keys.ToList();
                    if (everything.Any())
                    {
                        results.AddRange(everything.Select(food => new KeyValuePair<string, string>(teamMember.Key, food)));
                    }
                }
                break;
        }
    }

    var resultIn2DArray = results.To2DArray();
    return resultIn2DArray;
}

// Created extension to convert List to String[,]
public static class Extension
{
    public static string[,] To2DArray<T>(this List<T> list)
    {
        if (list.Count == 0)
        {
            throw new ArgumentException("The list must have non-zero dimensions.");
        }

        var result = new string[list.Count, list.Count];
        for (var i = 0; i < list.Count; i++)
        {
           // This is set to 0 since I know the output but will work on this to make it dynamic.
            result[0, i] = list[i].ToString();
        }

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

Thank you all for your input.

Body:
I am trying to achieve the output by using multidimensional array which I can get by using KeyValuePair.

Input:

var foodPair = new Dictionary<string, string>
{
    {"Pizza", "Italian"},
    {"Curry", "Indian"},
    {"Masala", "Indian"}
};

var teamPreference = new Dictionary<string, string>
{
    {"Jose", "Italian" },
    {"John", "Indian" },
    {"Sarah", "Thai" },
    {"Mary", "*" }
};

* means give everything
If selected food type is not available than give nothing. i.e Thai

Output:

Jose, Pizza
John, Curry
John, Masala
Mary, Pizza
Mary, Curry
Mary, Masala

Working Result by using KeyValuePair<string, string>:

https://dotnetfiddle.net/hNdlfy

I want to achieve same result by using string[,] but I don't know how to insert in dimensional array. Basically I am trying to learn how multidimensional arrays works by doing this kind of example.

Body:
I used Extension method to achieve the desired result.

public static string[,] FoodPreferenceWithDimensionalArray()
{
    var foodPair = new Dictionary<string, string>
    {
        {"Pizza", "Italian"},
        {"Curry", "Indian"},
        {"Masala", "Indian"}
    };

    var teamPreference = new Dictionary<string, string>
    {
        {"Jose", "Italian" },
        {"John", "Indian" },
        {"Sarah", "Thai" },
        {"Mary", "*" }
    };

    var results = new List<KeyValuePair<string, string>>();
    foreach (var teamMember in teamPreference)
    {
        switch (teamMember.Key)
        {
            case "Jose":
                var italianDish = foodPair.FirstOrDefault(x => x.Value == "Italian").Key;
                results.Add(new KeyValuePair<string, string>(teamMember.Key, italianDish));
                break;

            case "John":
                var indianDish = foodPair.Where(x => x.Value == "Indian");
                if (indianDish.Any())
                {
                    results.AddRange(indianDish.Select(dish => new KeyValuePair<string, string>(teamMember.Key, dish.Key)));
                }
                break;

            case "Sarah":
                var thaiDish = foodPair.FirstOrDefault(x => x.Value == "Thai").Key;
                if (!string.IsNullOrEmpty(thaiDish))
                {
                    results.Add(new KeyValuePair<string, string>(teamMember.Key, thaiDish));
                }
                break;

            case "Mary":
                if (teamMember.Value == "*")
                {
                    var everything = foodPair.Keys.ToList();
                    if (everything.Any())
                    {
                        results.AddRange(everything.Select(food => new KeyValuePair<string, string>(teamMember.Key, food)));
                    }
                }
                break;
        }
    }

    var resultIn2DArray = results.To2DArray();
    return resultIn2DArray;
}

// Created extension to convert List to String[,]
public static class Extension
{
    public static string[,] To2DArray<T>(this List<T> list)
    {
        if (list.Count == 0)
        {
            throw new ArgumentException("The list must have non-zero dimensions.");
        }

        var result = new string[list.Count, list.Count];
        for (var i = 0; i < list.Count; i++)
        {
           // This is set to 0 since I know the output but will work on this to make it dynamic.
            result[0, i] = list[i].ToString();
        }

        return result;
    }
}

Thank you all for your input.


问:
Drupal 8 Libraries - CSS in head - JS in body
I'm slowly understanding the concept of Durpal 8's Libraries.

How would I add a library's CSS to the head of the document, while adding a library's JS to just before the closing body tag?

答:
If you follow the standard process of adding the libraries in Drupal 8, you should achieve this by default.

Please check this link for details
adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme


问:
Invalid Date in Firefox using .toLocaleString() as well as moment.js
I have a script that I am attempting to convert a UTC date/time to local timezone. It all seems to be working well in Chrome and IE/Edge, but shows "invalid date" in Firefox. There are several other questions out there on stack but none seem to address my specific need.

My script does this...

Gets a date that is a specific format put out by Fabrik in Joomla. (I have little control over this format)

it looks like this:

```<code>2017-07-02 20:57
</code>```

And then I create a new date as UTC and convert that to a Local timezone.

toLocalString method:

```<code>$(document).ready(function() {
        $('.plg-date > .fabrikElement > div').not('.fabrikSubElementContainer').each(function() {
            if($(this).text().length > 0) {
                var newdate = new Date($(this).text() + " UTC");
                var options = {
                    year: 'numeric',
                    month: 'numeric',
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit',
                    timeZoneName: 'short'
                }
                $(this).text(newdate.toLocaleString('en-US', options));
            }
        })
    });
</code>```

moment.js method:

```<code>$(document).ready(function() {
    $('.plg-date > .fabrikElement > div').not('.fabrikSubElementContainer').each(function() {
        if($(this).text().length > 0) {
            var date = new Date($(this).text() + " UTC");
            var newdate = moment(date).format('ddd MMM DD YYYY h:mm A')
            $(this).text(newdate);
        }
    })
});
</code>```

both methods result in invalid date in firefox. suggestions?

答:
Your format strings don't match what either API needs. You are currently passing the text (2017-07-02 20:57) with UTC appended to the end (i.e. 2017-07-02 20:57 UTC). In a javascript console:

```<code>new Date("2017-07-02 20:57");
Date 2017-07-02T19:57:00.000Z
new Date("2017-07-02 20:57 UTC")
Invalid Date
</code>```

It should work if you drop the UTC component. Notice, though, that javascript is turning 20:57 into 19:57. This is because of daylight savings, which might occur on a client's computer. Whether this affects your app depends on where the timestamps are coming from.

As for the moment example you gave, your format string should be YYYY-MM-DD HH:mm for your input string.

Body:
I have a script that I am attempting to convert a UTC date/time to local timezone. It all seems to be working well in Chrome and IE/Edge, but shows "invalid date" in Firefox. There are several other questions out there on stack but none seem to address my specific need.

My script does this...

Gets a date that is a specific format put out by Fabrik in Joomla. (I have little control over this format)

it looks like this:

2017-07-02 20:57

And then I create a new date as UTC and convert that to a Local timezone.

toLocalString method:

$(document).ready(function() {
        $('.plg-date > .fabrikElement > div').not('.fabrikSubElementContainer').each(function() {
            if($(this).text().length > 0) {
                var newdate = new Date($(this).text() + " UTC");
                var options = {
                    year: 'numeric',
                    month: 'numeric',
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit',
                    timeZoneName: 'short'
                }
                $(this).text(newdate.toLocaleString('en-US', options));
            }
        })
    });

moment.js method:

$(document).ready(function() {
    $('.plg-date > .fabrikElement > div').not('.fabrikSubElementContainer').each(function() {
        if($(this).text().length > 0) {
            var date = new Date($(this).text() + " UTC");
            var newdate = moment(date).format('ddd MMM DD YYYY h:mm A')
            $(this).text(newdate);
        }
    })
});

both methods result in invalid date in firefox. suggestions?

Body:
Your format strings don't match what either API needs. You are currently passing the text (2017-07-02 20:57) with UTC appended to the end (i.e. 2017-07-02 20:57 UTC). In a javascript console:

new Date("2017-07-02 20:57");
Date 2017-07-02T19:57:00.000Z
new Date("2017-07-02 20:57 UTC")
Invalid Date

It should work if you drop the UTC component. Notice, though, that javascript is turning 20:57 into 19:57. This is because of daylight savings, which might occur on a client's computer. Whether this affects your app depends on where the timestamps are coming from.

As for the moment example you gave, your format string should be YYYY-MM-DD HH:mm for your input string.


问:
Create chain in lodash with custom functions
Is there way to get my own custom function in a chain of lodash. So for example like this:</p>

```<code>var l = [1,2,3]
var add = function(a, b){return a+b}

var r =_.chain(l).find(function(a){return a>1}).add(5).value()

=>r = 7
</code>```

答:
Another option is to just drop chaining and leverage function composition through _.flow.

From the DOCS:

[Flow] Creates a function that returns the result of invoking the given
  functions with the this binding of the created function, where each
  successive invocation is supplied the return value of the previous.

This means that every function inside Flow will receive as input the output of the previous one. In practice this means we are not limited to using only Lodash API methods, but we can mix and match whatever function we fancy, as long as the next one is able to handle that return value.

```<code>var l = [1,2,3]
var add = _.curry((a, b) => a + b);

_.flow(
  _.find(a => a > 1),
  add(5),
)(l);

// => 7
</code>```

NB - This example is using the Functional version of Lodash, if you don't want or can't use that one you can still achieve the same result, check my other answer to another question about Lodash.

Body:
Is there way to get my own custom function in a chain of lodash. So for example like this:

var l = [1,2,3]
var add = function(a, b){return a+b}

var r =_.chain(l).find(function(a){return a>1}).add(5).value()

=>r = 7

Body:
Another option is to just drop chaining and leverage function composition through _.flow.

From the DOCS:

[Flow] Creates a function that returns the result of invoking the given
  functions with the this binding of the created function, where each
  successive invocation is supplied the return value of the previous.

This means that every function inside Flow will receive as input the output of the previous one. In practice this means we are not limited to using only Lodash API methods, but we can mix and match whatever function we fancy, as long as the next one is able to handle that return value.

var l = [1,2,3]
var add = _.curry((a, b) => a + b);

_.flow(
  _.find(a => a > 1),
  add(5),
)(l);

// => 7

NB - This example is using the Functional version of Lodash, if you don't want or can't use that one you can still achieve the same result, check my other answer to another question about Lodash.


问:
Extract base url from full url
Any quick way to extract base url from full url? for e.g., if i have http://test.example.com/abcd/test.html - i want only http://test.example.com. </p>

<p>I can always do string parsing - but wanted to know if there is something in Uri where I can get it directly.  </p>

答:
What about:</p>

```<code>import java.net.URL;
import java.net.MalformedURLException;

try
{
  URL url = new URL("http://test.example.com/abcd/test.html");
  String baseUrl = url.getProtocol() + "://" + url.getHost();
}
catch (MalformedURLException e)
{
  // do something
}
</code>```

Title: Extract base url from full url

Body:
Any quick way to extract base url from full url? for e.g., if i have http://test.example.com/abcd/test.html - i want only http://test.example.com.

I can always do string parsing - but wanted to know if there is something in Uri where I can get it directly.

Body:
What about:

import java.net.URL;
import java.net.MalformedURLException;

try
{
  URL url = new URL("http://test.example.com/abcd/test.html");
  String baseUrl = url.getProtocol() + "://" + url.getHost();
}
catch (MalformedURLException e)
{
  // do something
}


问:
adding a timestamp filter to a range
I am already able to create a scan with a Range.exact(row, cf) and to read a table with it. But I want now to add a timestamp filter to it so I can filter for example "showing only rows that was created after ...".

I know there is a way to add a long to Range.exact, but that doesn't fit my case since I don't want an exact date.

I read about the TimestampFilter class, but it seems that it only filters with timestamps.

How can I create a Range that scan Rows, cf AND Timestamps ?

答:
You can apply a range and a timestamp filter to the scanner by using both method calls, Scanner.setRange(...) and Scanner.addScanIterator(...), before iterating over the entries in the scanner.

Here is an example of adding a timestamp filter to a scanner.

Title: adding a timestamp filter to a range


问:
I can´t import packages after install with pip
I am trying to install packages with pip in Rodeo in Windows with:

```<code>import pip

pip.main(["install","gdal"])
</code>```

It looks like it works, as console doesn´t give back me any errors. But when I try to import the package

```<code>>>> import gdal as asdf
ImportError: No module named 'gdal'
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-205-98f806a7d911> in <module>()
----> 1 import gdal as asdf
ImportError: No module named 'gdal'
</code>```

It also happens with other packages. Any ideas? I think something is bad with the path... how can I tell pip where to install?

Sorry, I am new with python...

答:
Is not clear for me what is gdal.
You installed ggplot, does the import ggplot command work?

Body:
I am trying to install packages with pip in Rodeo in Windows with:

import pip

pip.main(["install","gdal"])

It looks like it works, as console doesn´t give back me any errors. But when I try to import the package

>>> import gdal as asdf
ImportError: No module named 'gdal'
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-205-98f806a7d911> in <module>()
----> 1 import gdal as asdf
ImportError: No module named 'gdal'

It also happens with other packages. Any ideas? I think something is bad with the path... how can I tell pip where to install?

Sorry, I am new with python...


问:
fabric.js to show mirror image of canvas text
i am using fabric.js to write text on canva .later on click of button i want to show mirror image of text . is there any property in fabric.js which i can use to rotate text on canvas.

Please check , http://jsfiddle.net/BTh6A/9/

```<code>document.getElementById( 'btn' ).addEventListener( 'click', function (e) {
    var obj = canvas.getActiveObject();

    if ( !obj ) return;

    //here comes code to show mirror image

    obj.set( 'fill', '#FF0000' );
    canvas.renderAll();
});
</code>```

答:
```<code>function flipX() {
    var obj = canvas.getActiveObject();
    if (obj) {
        obj.set('flipX', !obj.flipX);
        canvas.renderAll();
    }
}

function flipY() {
    var obj = canvas.getActiveObject();
    if (obj) {
        obj.set('flipY', !obj.flipY);
        canvas.renderAll();
    }
}
</code>```

Body:
i am using fabric.js to write text on canva .later on click of button i want to show mirror image of text . is there any property in fabric.js which i can use to rotate text on canvas.

Please check , http://jsfiddle.net/BTh6A/9/

document.getElementById( 'btn' ).addEventListener( 'click', function (e) {
    var obj = canvas.getActiveObject();

    if ( !obj ) return;

    //here comes code to show mirror image

    obj.set( 'fill', '#FF0000' );
    canvas.renderAll();
});


问:
python removing whitespace from string in a list
I have a list of lists. I want to remove the leading and trailing spaces from them. The strip() method returns a copy of the string without leading and trailing spaces. Calling that method alone does not make the change. With this implementation, I am getting an 'array index out of bounds error'. It seems to me like there would be "an x" for exactly every list within the list (0-len(networks)-1) and "a y" for every string within those lists (0-len(networks[x]) aka i and j should map exactly to legal, indexes and not go out of bounds?

```<code>i = 0
j = 0
for x in networks:
    for y in x:
    networks[i][j] = y.strip()
        j = j + 1
     i = i + 1
</code>```

答:
A much cleaner version of cleaning list could be implemented using recursion. This will allow you to have a infinite amount of list inside of list all while keeping a very low complexity to your code.

Side note: This also puts in place safety checks to avoid data type issues with strip. This allows your list to contain ints, floats, and much more.

```<code>    def clean_list(list_item):
        if isinstance(list_item, list):
            for index in range(len(list_item)):
                if isinstance(list_item[index], list):
                    list_item[index] = clean_list(list_item[index])
                if not isinstance(list_item[index], (int, tuple, float, list)):
                    list_item[index] = list_item[index].strip()

        return list_item
</code>```

Then just call the function with your list. All of the values will be cleaned inside of the list of list.

clean_list(networks)

Body:
I have a list of lists. I want to remove the leading and trailing spaces from them. The strip() method returns a copy of the string without leading and trailing spaces. Calling that method alone does not make the change. With this implementation, I am getting an 'array index out of bounds error'. It seems to me like there would be "an x" for exactly every list within the list (0-len(networks)-1) and "a y" for every string within those lists (0-len(networks[x]) aka i and j should map exactly to legal, indexes and not go out of bounds?

i = 0
j = 0
for x in networks:
    for y in x:
    networks[i][j] = y.strip()
        j = j + 1
     i = i + 1

Body:
A much cleaner version of cleaning list could be implemented using recursion. This will allow you to have a infinite amount of list inside of list all while keeping a very low complexity to your code.

Side note: This also puts in place safety checks to avoid data type issues with strip. This allows your list to contain ints, floats, and much more.

    def clean_list(list_item):
        if isinstance(list_item, list):
            for index in range(len(list_item)):
                if isinstance(list_item[index], list):
                    list_item[index] = clean_list(list_item[index])
                if not isinstance(list_item[index], (int, tuple, float, list)):
                    list_item[index] = list_item[index].strip()

        return list_item

Then just call the function with your list. All of the values will be cleaned inside of the list of list.

clean_list(networks)


问:
Dynamically setting CSS values using ASP.NET
I'm working on a site where the images and other resources will be located on a separate domain from the main content of the site. We will use something like 'www.example.com' for the main site, and then 'images.example.com' for all extra resources for styles, etc.

When developing the site I will keep all of these resources on local dev. machines. The challenge here is keeping CSS references consistent between the production server and development environments.

What I was thinking of doing was creating a web.config key that would store the URL of the images server. Then, when switching from development to production I could just change the web.config value and everything would be done.

Is there any way to add a value to a CSS file, dynamically or otherwise, from some place in a config or C# class? Or am I going about this the wrong way?

Also, I'm limited to using .NET 2.0 if that makes a difference.

UPDATE

To expand on this a little more, I know I can use a web.config setting for server controls' URLs. Those are already generated dynamically. What I'm more interested in is what options I have for modifying (or doing "something") to static CSS files that will allow me to change URLs for things such as background image resources that would be referenced in CSS. Is there anything I can do besides find/replacing the values using my IDE? Perhaps something that can be done automatically with a deployment script?

答: I would create a server control for my CSS that registered the css script block on page load. You could very easily change all paths at that point programmatically.</p>

OwnerDisplayName: DanHerbert

LastEditorDisplayName: DanHerbert

OwnerDisplayName: Matt Briggs


答: Try creating the controls in the page's PreInit method.  "IsPostBack" should work and the click event handlers should work as well.</p>

Title: Dynamically creating asp.net with c# pages

Body:
I am struggling with finding clear answers to dynamically creating the same page over and over.  The questions and samples I have found seem to be all over the board on this topic.  I have studied the life cycle and still seem to not have a clear answer as to where code should go.

I have a master page and a content page.  All the content in the content area needs to be dynamically created (text boxes, ddl's, page tabs, buttons/onclick etc.).

After a user fills in data and clicks a submit button, I need to read the values off the form and rebuild the page completely again (not add/remove controls to current content).

My question is then.
Where do I put my code to build the page?
Will this area allow me to use IsPostBack so I can rebuild content with Request.Form values?
Will my buttons _Click events work?
Are there any working samples out there you could direct me to?

Thank you very much for the feedback...


问:
Retrieving the backcolor in C#
I'm a absolute beginner. Just started to play with C#.
I want to switch the backcolor of a textBox.
If it is red, I want to change it into yellow.

Why is if (textBox1.backcolor = Color.Red) giving an error ?

答:
using '=' is for assigning a value, use '==' to check if two things are equal

```<code>if (textBox1.backcolor == Color.Red)
{
    ...
}
</code>```

What is the error you are getting?

Title: Retrieving the backcolor in C#

Body:
using '=' is for assigning a value, use '==' to check if two things are equal

if (textBox1.backcolor == Color.Red)
{
    ...
}

What is the error you are getting?


问:
Attempt to invoke virtual method RecyclerView$LayoutManager.onRestoreInstanceState(android.os.Parcelable)' on a null object reference
```<code> I am getting error when i rotate screen
</code>```

java.lang.RuntimeException: Unable to resume activity {com.example.naveen.bakingapp/com.example.naveen.bakingapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView$LayoutManager.onRestoreInstanceState(android.os.Parcelable)' on a null object reference
                                                                                at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3121)
                                                                                at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3152)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2495)
                                                                                at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4098)
                                                                                at android.app.ActivityThread.-wrap15(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1360)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5443)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
                                                                               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView$LayoutManager.onRestoreInstanceState(android.os.Parcelable)' on a null object reference

```<code>public class MainActivity extends AppCompatActivity {
   // @BindView(R.id.recyclerview) RecyclerView recyclerView;
    ArrayList<Receipe>receipeArrayList;
    RecyclerView recyclerView;`enter code here`
    Parcelable mListInstanceState;`enter code here`
    LinearLayoutManager layoutManager;
    private static Bundle mBundleRecyclerViewState;
    private final String KEY_RECYCLER_STATE = "recycler_state";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       // ButterKnife.bind(this);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        receipeArrayList=new ArrayList<>();
        recyclerView=(RecyclerView)findViewById(R.id.recyclerview);

new GetAllReceipe().execute();
    }
    public class GetAllReceipe extends AsyncTask<String,Integer,String>
    {   String response;
        ProgressDialog dialog;
        ContentValues receipeValuesArr;
        int progressStatus = 0;
        boolean running;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            running = true;
            dialog = new ProgressDialog(MainActivity.this);
            dialog.setMessage("Loading, please wait");
            dialog.setTitle("Connecting server");
            dialog.show();
            dialog.setCancelable(false);
            dialog.setProgress(progressStatus);
            dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    running = false;
                }
            });
        }
        @Override
        protected String doInBackground(String... params) {
            URL url ;
            HttpURLConnection connection ;
            try {
                url = new URL("https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json");
                connection = (HttpURLConnection) url.openConnection();
                BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder buffer = new StringBuilder();
                String temp;
                while ((temp=br.readLine())!=null)
                {
                    buffer.append(temp);
                }
                response=buffer.toString();

                int i = 5;
                while (running & progressStatus < 5) {
                    try {
                        progressStatus++;
                        publishProgress(progressStatus);
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    if (i-- == 0) {
                        running = false;
                    }
                    publishProgress(i);

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return response;
        }
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            dialog.setProgress(progressStatus);
        }
        @Override
        protected void onPostExecute(String response) {
            //Log.i("result",response.toString());
            if (dialog!=null&&dialog.isShowing()){dialog.dismiss();}
            try {
               // JSONObject jsonObject=new JSONObject(response);
                JSONArray jsonArray=new JSONArray(response);
                for (int i=0;i<jsonArray.length();i++)
                {
                    JSONObject object=jsonArray.getJSONObject(i);
                    receipeValuesArr = new ContentValues();
                    Receipe receipe=new Receipe();
                    receipe.setReceipe_name(object.getString("name"));
                    receipe.setId(object.getInt("id"));
                    receipeArrayList.add(receipe);
                    receipeValuesArr.put(ReceipeContract.ReceipeEntry.COLUMN_RECEIPE_ID,object.getInt("id"));
                    receipeValuesArr.put(ReceipeContract.ReceipeEntry.COLUMN_RECEIPE_NAME, object.getString("name"));
                    getContentResolver().insert(ReceipeContract.ReceipeEntry.CONTENT_URI,receipeValuesArr);
                }
               //final RecyclerView.LayoutManager lmanager=new LinearLayoutManager(MainActivity.this,LinearLayoutManager.VERTICAL,true);
                layoutManager = new LinearLayoutManager(MainActivity.this);

                layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

                recyclerView.setLayoutManager(layoutManager);
                recyclerView.setAdapter(new ReceipeAdapter(receipeArrayList,MainActivity.this));
                recyclerView.setItemAnimator(new DefaultItemAnimator());

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putParcelable("list_state",layoutManager.onSaveInstanceState());

    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

if (savedInstanceState!=null)
{
    mListInstanceState = savedInstanceState.getParcelable("list_state");

}

   /*
        assert mListInstanceState != null;
        //System.out.println(recyclerView.getLayoutManager().toString());
        if (recyclerView.getLayoutManager()!=null){
            recyclerView.getLayoutManager().onRestoreInstanceState(mListInstanceState);

        }
            else {
            System.out.println("layoutmanager is  null");
        }*/
    }
   /* @Override
    protected void onResume() {
        super.onResume();

        if (mListInstanceState != null) {
            layoutManager.onRestoreInstanceState(mListInstanceState);
        }
    }*/

    @Override
    protected void onPause()
    {
        super.onPause();

        // save RecyclerView state
        mBundleRecyclerViewState = new Bundle();
        Parcelable listState = recyclerView.getLayoutManager().onSaveInstanceState();
        mBundleRecyclerViewState.putParcelable(KEY_RECYCLER_STATE, listState);
    }

    @Override
    protected void onResume()
    {
        super.onResume();

        // restore RecyclerView state
        if (mBundleRecyclerViewState != null) {
            Parcelable listState = mBundleRecyclerViewState.getParcelable(KEY_RECYCLER_STATE);
            recyclerView.getLayoutManager().onRestoreInstanceState(listState);
        }
    }
}
</code>```

答:
Its happening, because after rotation your view is null, and you try to call method on this nullable view.

1) Safety code. (not recommended because you fix only crash, but not a problem)

Try change this:

```<code>if (mBundleRecyclerViewState != null) {
            Parcelable listState = mBundleRecyclerViewState.getParcelable(KEY_RECYCLER_STATE);
            recyclerView.getLayoutManager().onRestoreInstanceState(listState);
        }
</code>```

To this (safety code):

```<code>    if (mBundleRecyclerViewState != null && recyclerView != null) {
        Parcelable listState = mBundleRecyclerViewState.getParcelable(KEY_RECYCLER_STATE);
        if (recyclerView.getLayoutManager() != null) {
            recyclerView.getLayoutManager().onRestoreInstanceState(listState);
        }
    }
</code>```

2) Save and restore variable after rotating
Android: Save variables and settings on rotation

Or in this case you may to add this code in activity:

```<code>@Override
  protected void onResume() {
    super.onResume();
    recyclerView=(RecyclerView)findViewById(R.id.recyclerview);
  }
</code>```

Body:
 I am getting error when i rotate screen

java.lang.RuntimeException: Unable to resume activity {com.example.naveen.bakingapp/com.example.naveen.bakingapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView$LayoutManager.onRestoreInstanceState(android.os.Parcelable)' on a null object reference
                                                                                at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3121)
                                                                                at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3152)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2495)
                                                                                at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4098)
                                                                                at android.app.ActivityThread.-wrap15(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1360)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5443)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
                                                                               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView$LayoutManager.onRestoreInstanceState(android.os.Parcelable)' on a null object reference

public class MainActivity extends AppCompatActivity {
   // @BindView(R.id.recyclerview) RecyclerView recyclerView;
    ArrayList<Receipe>receipeArrayList;
    RecyclerView recyclerView;`enter code here`
    Parcelable mListInstanceState;`enter code here`
    LinearLayoutManager layoutManager;
    private static Bundle mBundleRecyclerViewState;
    private final String KEY_RECYCLER_STATE = "recycler_state";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       // ButterKnife.bind(this);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        receipeArrayList=new ArrayList<>();
        recyclerView=(RecyclerView)findViewById(R.id.recyclerview);

new GetAllReceipe().execute();
    }
    public class GetAllReceipe extends AsyncTask<String,Integer,String>
    {   String response;
        ProgressDialog dialog;
        ContentValues receipeValuesArr;
        int progressStatus = 0;
        boolean running;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            running = true;
            dialog = new ProgressDialog(MainActivity.this);
            dialog.setMessage("Loading, please wait");
            dialog.setTitle("Connecting server");
            dialog.show();
            dialog.setCancelable(false);
            dialog.setProgress(progressStatus);
            dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    running = false;
                }
            });
        }
        @Override
        protected String doInBackground(String... params) {
            URL url ;
            HttpURLConnection connection ;
            try {
                url = new URL("https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json");
                connection = (HttpURLConnection) url.openConnection();
                BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder buffer = new StringBuilder();
                String temp;
                while ((temp=br.readLine())!=null)
                {
                    buffer.append(temp);
                }
                response=buffer.toString();

                int i = 5;
                while (running & progressStatus < 5) {
                    try {
                        progressStatus++;
                        publishProgress(progressStatus);
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    if (i-- == 0) {
                        running = false;
                    }
                    publishProgress(i);

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return response;
        }
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            dialog.setProgress(progressStatus);
        }
        @Override
        protected void onPostExecute(String response) {
            //Log.i("result",response.toString());
            if (dialog!=null&&dialog.isShowing()){dialog.dismiss();}
            try {
               // JSONObject jsonObject=new JSONObject(response);
                JSONArray jsonArray=new JSONArray(response);
                for (int i=0;i<jsonArray.length();i++)
                {
                    JSONObject object=jsonArray.getJSONObject(i);
                    receipeValuesArr = new ContentValues();
                    Receipe receipe=new Receipe();
                    receipe.setReceipe_name(object.getString("name"));
                    receipe.setId(object.getInt("id"));
                    receipeArrayList.add(receipe);
                    receipeValuesArr.put(ReceipeContract.ReceipeEntry.COLUMN_RECEIPE_ID,object.getInt("id"));
                    receipeValuesArr.put(ReceipeContract.ReceipeEntry.COLUMN_RECEIPE_NAME, object.getString("name"));
                    getContentResolver().insert(ReceipeContract.ReceipeEntry.CONTENT_URI,receipeValuesArr);
                }
               //final RecyclerView.LayoutManager lmanager=new LinearLayoutManager(MainActivity.this,LinearLayoutManager.VERTICAL,true);
                layoutManager = new LinearLayoutManager(MainActivity.this);

                layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

                recyclerView.setLayoutManager(layoutManager);
                recyclerView.setAdapter(new ReceipeAdapter(receipeArrayList,MainActivity.this));
                recyclerView.setItemAnimator(new DefaultItemAnimator());

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putParcelable("list_state",layoutManager.onSaveInstanceState());

    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

if (savedInstanceState!=null)
{
    mListInstanceState = savedInstanceState.getParcelable("list_state");

}

   /*
        assert mListInstanceState != null;
        //System.out.println(recyclerView.getLayoutManager().toString());
        if (recyclerView.getLayoutManager()!=null){
            recyclerView.getLayoutManager().onRestoreInstanceState(mListInstanceState);

        }
            else {
            System.out.println("layoutmanager is  null");
        }*/
    }
   /* @Override
    protected void onResume() {
        super.onResume();

        if (mListInstanceState != null) {
            layoutManager.onRestoreInstanceState(mListInstanceState);
        }
    }*/

    @Override
    protected void onPause()
    {
        super.onPause();

        // save RecyclerView state
        mBundleRecyclerViewState = new Bundle();
        Parcelable listState = recyclerView.getLayoutManager().onSaveInstanceState();
        mBundleRecyclerViewState.putParcelable(KEY_RECYCLER_STATE, listState);
    }

    @Override
    protected void onResume()
    {
        super.onResume();

        // restore RecyclerView state
        if (mBundleRecyclerViewState != null) {
            Parcelable listState = mBundleRecyclerViewState.getParcelable(KEY_RECYCLER_STATE);
            recyclerView.getLayoutManager().onRestoreInstanceState(listState);
        }
    }
}

Body:
Its happening, because after rotation your view is null, and you try to call method on this nullable view.

1) Safety code. (not recommended because you fix only crash, but not a problem)

Try change this:

if (mBundleRecyclerViewState != null) {
            Parcelable listState = mBundleRecyclerViewState.getParcelable(KEY_RECYCLER_STATE);
            recyclerView.getLayoutManager().onRestoreInstanceState(listState);
        }

To this (safety code):

    if (mBundleRecyclerViewState != null && recyclerView != null) {
        Parcelable listState = mBundleRecyclerViewState.getParcelable(KEY_RECYCLER_STATE);
        if (recyclerView.getLayoutManager() != null) {
            recyclerView.getLayoutManager().onRestoreInstanceState(listState);
        }
    }

2) Save and restore variable after rotating
Android: Save variables and settings on rotation

Or in this case you may to add this code in activity:

@Override
  protected void onResume() {
    super.onResume();
    recyclerView=(RecyclerView)findViewById(R.id.recyclerview);
  }


问:
Is it possible to get output of a NRQL query in new relic using a jenkins job?
I'm looking to automate the process of collecting data from New Relic Insights and sharing it over a  mail accepting start and end time for a particular nrql query. There is a New Relic Insights plugin for jenkins that is available but not sure if such a task is possible using that? Any suggestions? </p>

答:
There is a REST API for Insights that will let you senda NRQL query and retrieve the results in JSON format. You might take a look at that.

https://docs.newrelic.com/docs/insights/insights-api/get-data/query-insights-event-data-api


问:
MarkLogic generic language support
As per the documentation:
The generic language support only stems words to themselves, queries in these languages will not include variations of words based on their meanings in the results.

```<code>xdmp:document-insert("/lang/test.xml", <el xml:lang="fr">chats</el>)
</code>```

Considering I do not have a license for french language, will the word
"chats" be stemmed to "chat" in the term list ? or will it be indexed as chats, i.e. without any variations ?

答:
No license for French means no stemming for French.

I'm actually kind of confused by the question.  If it did work without the license, then what would the license get you?

Title: MarkLogic generic language support

Body:
As per the documentation:
The generic language support only stems words to themselves, queries in these languages will not include variations of words based on their meanings in the results.

xdmp:document-insert("/lang/test.xml", <el xml:lang="fr">chats</el>)

Considering I do not have a license for french language, will the word
"chats" be stemmed to "chat" in the term list ? or will it be indexed as chats, i.e. without any variations ?


问:
Can't override server certificate validation in an Azure Web App

Overview

I seem to have a variant of the problem listed in this post. However, the answers there don't really help me, and my situation is different.

I'm working for a large corporate, who have decided to trust themselves as a root certificate authority. I've developed a web application, that needs to link to an API hosted in a VM in Azure.

My Approach

As I can't install the certificate in the trusted store, I was trying to do this by code. I'm using ASP.NET Web API v2, and I've added the following code to the startup section:

```<code>    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
        var options = CorsOptions.AllowAll;
        app.UseCors(options);

        // Override certificate check
        ServicePointManager.ServerCertificateValidationCallback =   MyRemoteCertificateValidationCallback;
    }
</code>```

My callback looks like this:

```<code>public bool MyRemoteCertificateValidationCallback(
        object sender,
        X509Certificate certificate,
        X509Chain chain,
        SslPolicyErrors sslPolicyErrors)
    {
        switch (sslPolicyErrors)
        {
            case SslPolicyErrors.RemoteCertificateChainErrors:
                return IsTheCertificateOriginAcceptable(chain);
            case SslPolicyErrors.None:
                return true;
            default:
                return false;
        }
    }
</code>```

The certificate origin acceptable function is checking to see if the problem was due to an Unknown Root, and then to see if the unkown root is an extra one the code knows about (because I can't add trusted roots to the Azure Web App - if I had a VM installing the certificate would be the way to go).

If not, it throws a web exception:

```<code>bool IsTheCertificateOriginAcceptable(X509Chain chain)
{
   // checks to see if the initail problem is an untrusted root,
   // and to extract the origin certificate
   if (certificate.IssuerName.Name == expectedIsserName)
   {
       return true;
   }
   else
   {
       throw new WebException($"Certificate origin unacceptable Actual Issue Name '{certificate.IssuerName.Name}', expected issuer name '{expectedIssuerName}'");
   }
</code>```

The plan is to find the issuer name from the VM, and then put that into the code - this is exploratory code, to work out how to get the connection done.

Running locally

I then set myself up with IIS with two websites. One running this code, and one on a differnt port, with the default self-signed certificate running a trivial mock of the API I am trying to call.

When I do that, if I don't use the above code, I get the same error I get on Azure:

```<code>The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()
</code>```

If I do use the code, I get the following message

```<code>Certificate origin unacceptable Actual Issue Name 'CN=localhost', expected issuer name ''
</code>```

In the Azure Web App

When I deploy the above code to Azure, I always get the certificate trust error, which suggests that the callback isn't getting called.

I can't check the SSL settings of the remote server easily, as it isn't connected to the internet (I've connected my azure web app to the VNET the VM is hosted on).

So given all that, how can I connect, other than suggesting that the remote server gets a proper certificate from a known and trusted RCA?

答:
It turns out that the behaviour of the framework was not what I expected.

The situation I had was a self-signed root certficate, and a child certificate of that self-signed certificate. In this case, I had expected one certificate to be marked as UntrustedRoot.

However, the behaviour of the framework in this case it to only give the leaf certificate, so the chain is length 1. The chain then gets classified as PartialChain.

My logic was looking for an UntrustedRoot, not a PartialChain, so although the callback was called, I was returning lacking permission earlier.

So my logic was wrong - which I confirmed by setting the callback to always return true. I then set two self-signed certificates up and used a second website on localhost - which replicated the error and allowed me to see where my logic error was.

Thanks to those who commented, I should have checked the callback being set true resolved the issue before posting.

Body:
Overview

I seem to have a variant of the problem listed in this post. However, the answers there don't really help me, and my situation is different.

I'm working for a large corporate, who have decided to trust themselves as a root certificate authority. I've developed a web application, that needs to link to an API hosted in a VM in Azure.

My Approach

As I can't install the certificate in the trusted store, I was trying to do this by code. I'm using ASP.NET Web API v2, and I've added the following code to the startup section:

    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
        var options = CorsOptions.AllowAll;
        app.UseCors(options);

        // Override certificate check
        ServicePointManager.ServerCertificateValidationCallback =   MyRemoteCertificateValidationCallback;
    }

My callback looks like this:

public bool MyRemoteCertificateValidationCallback(
        object sender,
        X509Certificate certificate,
        X509Chain chain,
        SslPolicyErrors sslPolicyErrors)
    {
        switch (sslPolicyErrors)
        {
            case SslPolicyErrors.RemoteCertificateChainErrors:
                return IsTheCertificateOriginAcceptable(chain);
            case SslPolicyErrors.None:
                return true;
            default:
                return false;
        }
    }

The certificate origin acceptable function is checking to see if the problem was due to an Unknown Root, and then to see if the unkown root is an extra one the code knows about (because I can't add trusted roots to the Azure Web App - if I had a VM installing the certificate would be the way to go).

If not, it throws a web exception:

bool IsTheCertificateOriginAcceptable(X509Chain chain)
{
   // checks to see if the initail problem is an untrusted root,
   // and to extract the origin certificate
   if (certificate.IssuerName.Name == expectedIsserName)
   {
       return true;
   }
   else
   {
       throw new WebException($"Certificate origin unacceptable Actual Issue Name '{certificate.IssuerName.Name}', expected issuer name '{expectedIssuerName}'");
   }

The plan is to find the issuer name from the VM, and then put that into the code - this is exploratory code, to work out how to get the connection done.

Running locally

I then set myself up with IIS with two websites. One running this code, and one on a differnt port, with the default self-signed certificate running a trivial mock of the API I am trying to call.

When I do that, if I don't use the above code, I get the same error I get on Azure:

The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()

If I do use the code, I get the following message

Certificate origin unacceptable Actual Issue Name 'CN=localhost', expected issuer name ''

In the Azure Web App

When I deploy the above code to Azure, I always get the certificate trust error, which suggests that the callback isn't getting called.

I can't check the SSL settings of the remote server easily, as it isn't connected to the internet (I've connected my azure web app to the VNET the VM is hosted on).

So given all that, how can I connect, other than suggesting that the remote server gets a proper certificate from a known and trusted RCA?


问:
Strange Behavior with DeletedDatabaseRecord
I would like to use logical deletion in a custom screen and I have added the following to my DAC:

```<code>        #region DeletedDatabaseRecord
        public abstract class deletedDatabaseRecord : PX.Data.IBqlField
        {
        }
        protected bool? _DeletedDatabaseRecord;
        [PXDBBool()]
        [PXDefault(false)]
        public virtual bool? DeletedDatabaseRecord
        {
            get
            {
                return this._DeletedDatabaseRecord;
            }
            set
            {
                this._DeletedDatabaseRecord = value;
            }
        }
        #endregion
</code>```

The above DAC is used in a grid (in a master/detail screen). When I click on the grid delete and then save, the row gets marked as deleted in the database.
However, when I refresh the screen, the deleted rows appear again. It seems that the data view is not taking into DeletedDatabaseRecord value. I confirmed that this was set to 1 in the database.

My data view is as follows:

```<code>public PXSelect<DCRule, Where<DCRule.ruleHeaderID, Equal<Current<DCRuleHeader.ruleHeaderID>>>, OrderBy<Asc<DCRule.sequence>>> Rules;
</code>```

Shouldn't the data view, automatically filter out deleted records (where DeletedDatabaseRecord  = 1)? or should I handle something else in the code logic.

UPDATE 1

I have removed the DeletedDatabaseRecord  from the DAC as the Design Guidelines state that they should not be included. However, I am still having the exact same issue.

UPDATE 2

I also noticed that the SQL statement is not filtering out the deleted records, and it is also not returning it as a column.

答:
One should never declare DAC fields for the following columns:

CompanyID

CompanyMask

DeletedDatabaseRecord

When you make some to Acumatica database schema, it's always a good practice to restart IIS or recycle the app pool hosting your Acumatica website, so Acumatica can re-sync the updated DB schema during domain restart as it does not track database schema changes at runtime.

Body:
I would like to use logical deletion in a custom screen and I have added the following to my DAC:

        #region DeletedDatabaseRecord
        public abstract class deletedDatabaseRecord : PX.Data.IBqlField
        {
        }
        protected bool? _DeletedDatabaseRecord;
        [PXDBBool()]
        [PXDefault(false)]
        public virtual bool? DeletedDatabaseRecord
        {
            get
            {
                return this._DeletedDatabaseRecord;
            }
            set
            {
                this._DeletedDatabaseRecord = value;
            }
        }
        #endregion

The above DAC is used in a grid (in a master/detail screen). When I click on the grid delete and then save, the row gets marked as deleted in the database.
However, when I refresh the screen, the deleted rows appear again. It seems that the data view is not taking into DeletedDatabaseRecord value. I confirmed that this was set to 1 in the database.

My data view is as follows:

public PXSelect<DCRule, Where<DCRule.ruleHeaderID, Equal<Current<DCRuleHeader.ruleHeaderID>>>, OrderBy<Asc<DCRule.sequence>>> Rules;

Shouldn't the data view, automatically filter out deleted records (where DeletedDatabaseRecord  = 1)? or should I handle something else in the code logic.

UPDATE 1

I have removed the DeletedDatabaseRecord  from the DAC as the Design Guidelines state that they should not be included. However, I am still having the exact same issue.

UPDATE 2

I also noticed that the SQL statement is not filtering out the deleted records, and it is also not returning it as a column.


问:
What is sharding and why is it important?
I think I understand sharding to be putting back your sliced up data (the shards) into an easy to deal with aggregate that makes sense in the context.  Is this correct?

Update: I guess I am struggling here.  In my opinion the application tier should have no business determining where data should be stored.  At best it should be shard client of some sort.  Both responses answered the what but not the why is it important aspect.  What implications does it have outside of the obvious performance gains?  Are these gains sufficient to offset the MVC violation?  Is sharding mostly important in very large scale applications or does it apply to smaller scale ones?

答:
Sharding was originally coined by google engineers and you can see it used pretty heavily when writing applications on Google App Engine. Since there are hard limitations on the amount of resource your queries can use and because queries themselves have strict limitations, sharding is not only encouraged but almost enforced by the architecture.

Another place sharding can be used is to reduce contention on data entities. It is especially important when building scalable systems to watch out for those piece of data that are written often because they are always the bottleneck. A good solution is to shard off that specific entity and write to multile copies, then read the total. An example of this "sharded counter wrt GAE: http://code.google.com/appengine/articles/sharding_counters.html


问:
Matrix Inverse in TensorFlow
I have a problem related to calculating matrix inverse in TensorFlow python interface version 1.1.0 on Linux. What I'm now trying to do is that, I have an input vector as tensorflow.float64, say S and a value V. I augment the vector S to be polynomial fashion in the form  and want to do a regression on V. I choose to compute the linear regression myself instead of using the infrastructure from tensorflow, where the regression is conducted as . The problem occurs at the  step, where the inverse multiply the original matrix does not give an identity. However, if I feed the  as a constant matrix containing the same value as the preprocessed input, the result is really the inverse of itself.

The code below is a runnable version with parameter control=True turns on the constant input matrix version where the inverse behaves correctly. Three matrices are output by running the program, the original matrix, the "inverse" by tf.matrix_inverse, and the multiplication of the "inverse" with the original matrix aiming to recover an identify. control=False gives the same original matrix as control=True run, however, the recovered "identity" is not correct with control=False. I suspect something wrong with the data flow during preprocessing. However, limited by my experience with TensorFlow, I cannot spot it. Would you mind a help why the tf.matrix_inverse does not work as expected?

```<code>import tensorflow as tf
import pprint

def matrixInverse( control=False ):
    '''Compute inverse of a matrix.

Parameters
----------
control : bool
    whether to use control group or not.
    '''
    X = tf.constant( [ [100. , 100., 100., 100.],
         [ 101.75497118 ,  92.84824314 ,  95.09528336 , 103.24955959],
         [ 92.33287485 ,  95.86868862 ,  84.70664178 , 107.9505686 ],
         [ 85.86109085 ,  99.05621029 ,  94.24396596 , 119.60257907] ], dtype=tf.float64 )

    # extract input X
    s = tf.slice( X, [ 2, 0 ], [ 1, 4 ])
    s = tf.squeeze(s)
    s1 = tf.multiply( tf.ones( 4, dtype=tf.float64 ), s )
    s2 = tf.multiply( s, s )
    s3 = tf.multiply( tf.multiply( s, s ), s )

    A = tf.concat( [ tf.ones( 4, dtype=tf.float64 ), s1, s2, s3 ], 0 )
    A = tf.reshape( A, [ 4, 4 ] )

    # filter only the first element in the selected row
    itm = tf.constant( [ True, False, False, False ], dtype=tf.bool )

    A = tf.boolean_mask( tf.transpose(A), itm )

    if control:
        ATA = tf.constant([[  1.00000000e+00,   9.23328748e+01,   8.52535978e+03,   7.87170977e+05],
                     [  9.23328748e+01,   8.52535978e+03,   7.87170977e+05,   7.26817593e+07],
                     [  8.52535978e+03,   7.87170977e+05,   7.26817593e+07,   6.71091579e+09],
                     [  7.87170977e+05,   7.26817593e+07,   6.71091579e+09,   6.19638148e+11]], dtype = tf.float64)
    else:
        ATA = tf.matmul( tf.transpose( A ), A )

    inverseATA = tf.matrix_inverse( ATA )

    sess = tf.Session()
    pprint.pprint( sess.run( [ ATA, inverseATA, tf.matmul( ATA, inverseATA ) ] ) )
</code>```

答:
You are trying to invert a matrix that is not invertible. So even though it is surprising that copy-pasting the result produces something that looks OK, I would not draw a conclusion as to why a method is better than another at doing something that can't be done.

I would try to reformulate your problem to ensure applying mathematical operations on their domain.

Title: Matrix Inverse in TensorFlow

Body:
I have a problem related to calculating matrix inverse in TensorFlow python interface version 1.1.0 on Linux. What I'm now trying to do is that, I have an input vector as tensorflow.float64, say S and a value V. I augment the vector S to be polynomial fashion in the form  and want to do a regression on V. I choose to compute the linear regression myself instead of using the infrastructure from tensorflow, where the regression is conducted as . The problem occurs at the  step, where the inverse multiply the original matrix does not give an identity. However, if I feed the  as a constant matrix containing the same value as the preprocessed input, the result is really the inverse of itself.

The code below is a runnable version with parameter control=True turns on the constant input matrix version where the inverse behaves correctly. Three matrices are output by running the program, the original matrix, the "inverse" by tf.matrix_inverse, and the multiplication of the "inverse" with the original matrix aiming to recover an identify. control=False gives the same original matrix as control=True run, however, the recovered "identity" is not correct with control=False. I suspect something wrong with the data flow during preprocessing. However, limited by my experience with TensorFlow, I cannot spot it. Would you mind a help why the tf.matrix_inverse does not work as expected?

import tensorflow as tf
import pprint

def matrixInverse( control=False ):
    '''Compute inverse of a matrix.

Parameters
----------
control : bool
    whether to use control group or not.
    '''
    X = tf.constant( [ [100. , 100., 100., 100.],
         [ 101.75497118 ,  92.84824314 ,  95.09528336 , 103.24955959],
         [ 92.33287485 ,  95.86868862 ,  84.70664178 , 107.9505686 ],
         [ 85.86109085 ,  99.05621029 ,  94.24396596 , 119.60257907] ], dtype=tf.float64 )

    # extract input X
    s = tf.slice( X, [ 2, 0 ], [ 1, 4 ])
    s = tf.squeeze(s)
    s1 = tf.multiply( tf.ones( 4, dtype=tf.float64 ), s )
    s2 = tf.multiply( s, s )
    s3 = tf.multiply( tf.multiply( s, s ), s )

    A = tf.concat( [ tf.ones( 4, dtype=tf.float64 ), s1, s2, s3 ], 0 )
    A = tf.reshape( A, [ 4, 4 ] )

    # filter only the first element in the selected row
    itm = tf.constant( [ True, False, False, False ], dtype=tf.bool )

    A = tf.boolean_mask( tf.transpose(A), itm )

    if control:
        ATA = tf.constant([[  1.00000000e+00,   9.23328748e+01,   8.52535978e+03,   7.87170977e+05],
                     [  9.23328748e+01,   8.52535978e+03,   7.87170977e+05,   7.26817593e+07],
                     [  8.52535978e+03,   7.87170977e+05,   7.26817593e+07,   6.71091579e+09],
                     [  7.87170977e+05,   7.26817593e+07,   6.71091579e+09,   6.19638148e+11]], dtype = tf.float64)
    else:
        ATA = tf.matmul( tf.transpose( A ), A )

    inverseATA = tf.matrix_inverse( ATA )

    sess = tf.Session()
    pprint.pprint( sess.run( [ ATA, inverseATA, tf.matmul( ATA, inverseATA ) ] ) )


答:
Here is a base R solution using mapply.</p>

```<code>df <- data.frame(Name = c("A", "A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "B", "B"),
                 year = c(2012, 2012, 2013, 2014, 2015, 2016, 2017, 2012, 2013, 2013, 2014, 2015, 2016),
                 value = c(22, 99, 12, 1, 23, 40, 12, 12, 33, 40, NA, 20, 20),
                 stringsAsFactors = FALSE)

max.vals <- mapply(function(x, y){
                     vals <- df[df$year %in% c(x-2,x-1) & df$Name == y,"value"]
                     max.val <- ifelse(length(vals) > 0, max(vals, na.rm = TRUE), NA)
                     max.val <- list(y,x,max.val)
                     names(max.val) <- c("Name","year","max_value")
                     return(max.val)
                   },
                  unique(df[,c("Name","year")])$year,
                  unique(df[,c("Name","year")])$Name
                 )

max.vals <- as.data.frame(t(max.vals),stringsAsFactors = FALSE)

df <- merge(df, max.vals)
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to get previous two years max value in R

Body:
Hi I have data frame as

How to create column max_value with max from last 2 years max value

dt <-
structure(list(Name = c("A", "A", "A", "A", "A", "A", "A", "B",
"B", "B", "B", "B", "B"), year = c(2012L, 2012L, 2013L, 2014L,
2015L, 2016L, 2017L, 2012L, 2013L, 2013L, 2014L, 2015L, 2016L
), value = c(22L, 99L, 12L, 1L, 23L, 40L, 12L, 12L, 33L, 40L,
NA, 20L, 20L), max_value = c(NA, NA, 99L, 99L, 12L, 23L, 40L,
NA, 12L, 12L, 40L, 40L, 20L)), .Names = c("Name", "year", "value",
"max_value"), row.names = c(NA, -13L), class = c("data.table",
"data.frame"))

Name   year   value   *max_value*
A      2012    22        NA
A      2012    99        NA
A      2013    12        99
A      2014    01        99
A      2015    23        12
A      2016    40        23
A      2017    12        40
B      2012    12        NA
B      2013    33        12
B      2013    40        12
B      2014    NA        40
B      2015    20        40
B      2016    20        20

Thanks in advance

Body:
Here is a base R solution using mapply.

df <- data.frame(Name = c("A", "A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "B", "B"),
                 year = c(2012, 2012, 2013, 2014, 2015, 2016, 2017, 2012, 2013, 2013, 2014, 2015, 2016),
                 value = c(22, 99, 12, 1, 23, 40, 12, 12, 33, 40, NA, 20, 20),
                 stringsAsFactors = FALSE)

max.vals <- mapply(function(x, y){
                     vals <- df[df$year %in% c(x-2,x-1) & df$Name == y,"value"]
                     max.val <- ifelse(length(vals) > 0, max(vals, na.rm = TRUE), NA)
                     max.val <- list(y,x,max.val)
                     names(max.val) <- c("Name","year","max_value")
                     return(max.val)
                   },
                  unique(df[,c("Name","year")])$year,
                  unique(df[,c("Name","year")])$Name
                 )

max.vals <- as.data.frame(t(max.vals),stringsAsFactors = FALSE)

df <- merge(df, max.vals)


问:
Proper way to reset a GIF animation with display:none on Chrome
Title is self-explanatory, but I'll provide a step-by-step view on the matter. Hopefully I'm not the first one to have noticed this (apparently) bug on Webkit/Chrome.

I want to reset a GIF animation. All of the examples I've seen so far either simply set the src of the image to itself or set it to an empty string followed by the original src again.

Take a look at this JSFiddle for reference. The GIF resets perfectly fine on IE, Firefox and Chrome.

The issue which I have is when the image has display:none on Google Chrome only.

Check this JSFiddle.  The GIF resets fine on IE and Firefox before being displayed in the page, but Chrome simply refuses to reset its animation!

What I've tried so far:

Setting the src to itself as in Fiddle, doesn't work in Chrome.

Setting the src to an empty string and restoring it to the default, doesn't work either.

Putting an wrapper around the image, emptying the container through .html('') and putting the image back inside of it, doesn't work either.

Changing the display of the image through .show() or .fadeIn() right before setting the src doesn't work either.

The only workaround which I've found so far is keeping the image with its default display and manipulating it through .animate()ing and .css()ing the opacity, height and visibility when necessary to simulate a display:none behaviour.

The main reason (context) of this question is that I wanted to reset an ajax loader GIF right before fading it in the page.

So my question is, is there a proper way to reset a GIF image's animation (which avoids Chrome's display:none "bug") or is it actually a bug?

(ps. You may change the GIF in the fiddles for a more appropriate/longer animation gif for testing)

答:
It's been several years and I've decided to revisit this since we have a number of new options at our disposal.

The issue with my previous answer is that it forces a re-download of the GIF every single time you want to re-start it. While that's fine for small files, it's still an overhead that's best avoided if possible.

With that in mind, I've got a new solution that uses AJAX to download the GIF once, and then converts it into a data URL (via a FileReader) and uses that as the source with a random query string attached.

This way, the browser only ever downloads the image once, and can even cache it properly, and the "reset" pulls from that pre-downloaded resource.

The only catch, of course, is that you have to make sure it's properly loaded before you can use it.

Demo: http://adamhaskell.net/misc/numbers/numbers.html

Relevant code:

```<code>var url = "something.gif"; // fallback until the FileReader is done
function setup() {
    var xhr = new XMLHttpRequest();
    xhr.open("GET",url,true);
    xhr.responseType = "blob";
    xhr.onreadystatechange = function() {
        if( this.readyState == 4) {
            var fr = new FileReader();
            fr.onload = function() {
                url = this.result; // overwrite URL with the data one
            };
            fr.readAsDataURL(this.response);
        }
    };
    xhr.send();
}
function getGIF() {
    return url+"?x="+Math.random();
}
</code>```

Body:
It's been several years and I've decided to revisit this since we have a number of new options at our disposal.

The issue with my previous answer is that it forces a re-download of the GIF every single time you want to re-start it. While that's fine for small files, it's still an overhead that's best avoided if possible.

With that in mind, I've got a new solution that uses AJAX to download the GIF once, and then converts it into a data URL (via a FileReader) and uses that as the source with a random query string attached.

This way, the browser only ever downloads the image once, and can even cache it properly, and the "reset" pulls from that pre-downloaded resource.

The only catch, of course, is that you have to make sure it's properly loaded before you can use it.

Demo: http://adamhaskell.net/misc/numbers/numbers.html

Relevant code:

var url = "something.gif"; // fallback until the FileReader is done
function setup() {
    var xhr = new XMLHttpRequest();
    xhr.open("GET",url,true);
    xhr.responseType = "blob";
    xhr.onreadystatechange = function() {
        if( this.readyState == 4) {
            var fr = new FileReader();
            fr.onload = function() {
                url = this.result; // overwrite URL with the data one
            };
            fr.readAsDataURL(this.response);
        }
    };
    xhr.send();
}
function getGIF() {
    return url+"?x="+Math.random();
}


问:
error: control reaches end of non-void function:(
I know this has been asked before but still I couldn't find a fix. The program is supposed to sum all even digits in a number using recursion. Here's the code that produces the error control reaches end of non-void function:

```<code>#include<stdio.h>

int sum_even_d(unsigned long n);

int main()
{
    unsigned long n;
    int x;
    printf("Enter n : \n");
    scanf("%lu",&n);
    x=sum_even_d(n);
    printf("%d\n",x);
    return 0;

}

int sum_even_d(unsigned long n)
{
    if(n==0) return 0;
    if(n%2==0)
        return (sum_even_d(n/10)+n%10);//*error here*//
}
</code>```

If I add one line though, the program works perfectly. I don't understand what made the difference:

```<code>#include<stdio.h>

int sum_even_d(unsigned long n);

int main()
{
    unsigned long n;
    int x;
    printf("Enter n : \n");
    scanf("%lu",&n);
    x=sum_even_d(n);
    printf("%d\n",x);
    return 0;

    }

int sum_even_d(unsigned long n)
{
    if(n==0) return 0;
    if(n%2==0)
        return (sum_even_d(n/10)+n%10);
    else return (sum_even_d(n/10));//*added this*//
}
</code>```

答: In the first snippet when n is odd, the function sum_even_d won't reach any return statement. But since the function is defined a non-void, it must return a value. This is what the compiler is telling you. In the second snippet your else statement is taking care of this code path.

Body:
I know this has been asked before but still I couldn't find a fix. The program is supposed to sum all even digits in a number using recursion. Here's the code that produces the error control reaches end of non-void function:

#include<stdio.h>

int sum_even_d(unsigned long n);

int main()
{
    unsigned long n;
    int x;
    printf("Enter n : \n");
    scanf("%lu",&n);
    x=sum_even_d(n);
    printf("%d\n",x);
    return 0;

}

int sum_even_d(unsigned long n)
{
    if(n==0) return 0;
    if(n%2==0)
        return (sum_even_d(n/10)+n%10);//*error here*//
}

If I add one line though, the program works perfectly. I don't understand what made the difference:

#include<stdio.h>

int sum_even_d(unsigned long n);

int main()
{
    unsigned long n;
    int x;
    printf("Enter n : \n");
    scanf("%lu",&n);
    x=sum_even_d(n);
    printf("%d\n",x);
    return 0;

    }

int sum_even_d(unsigned long n)
{
    if(n==0) return 0;
    if(n%2==0)
        return (sum_even_d(n/10)+n%10);
    else return (sum_even_d(n/10));//*added this*//
}


问:
How to store encrypted documents for multiple users
An online system (front end written in PHP but that's not too relevant) needs to store text in a MySQL database encrypted so that local sysadmins cannot view the data, also so that the data cannot be viewed in the event that the database is stolen. There are multiple users on the system who must have access to the data, they login/authenticate via a standard setup, i.e. username and hashed password in the same db.

As the stored data needs to be decrypted by the system for display to an authenticated user, but local sysadmins must have no way of decrypting the same data, the obvious method would be to have a secret key that is used to encrypt/decrypt the stored data using a symmetrical cipher. The problem (really the question I am asking for advice on) is how/where to store this key?

The authenticated users should not have direct access to the key, so it needs to be stored within the system somehow and used by the software to decrypt the stored files on demand, but also local sysadmins must not be able to learn this key or they could use it to decrypt the stored data.

So one way would be to store the key in the database encrypted, but in order for the system to decrypt and use the key on a per user basis, it would have to be encrypted against something unique to the authenticated user, e.g. their password. Ok, so far so good, but there's a problem...

What if the key needs to be changed? The person changing the key would either have to know everyone's password so they could encrypt the new key against every users account (impractical), or they would have to give the new key to each user and ask them to re-enter it (not an option).

Also, is it good idea, from a security point of view, to have this key effectively stored n times (where n is the number of users) in the database, encrypted with different keys (users password)? i.e. does this expose the key more by giving potential hackers multiple examples of the same encrypted data?

Is there a better way?

答:
Thanks to jonrsharpe for pointing me at Tom Leak's post: https://security.stackexchange.com/a/71915

We will base our system on this method as follows:

Document is stored in a table encrypted using a symmetrical cipher.

The secret key for the above symmetrical cipher is stored in a separate table, once for every user that has access to the document, encrypted using an asymmetrical cipher with the user's public key.

The user's private key is stored in another table encrypted using a symmetrical cipher, the key to which is the user's password.

This means access to the document can be revoked by simply deleting that user's entry in the document key table; If the document is modified the system just needs to delete all the entries for the document in the key table then add them back encrypting with each users public key; additional users can be given access just by adding an entry to the document key table encrypting using the user's public key; user's that have access to the document can decrypt the document's secret key using their private key, which in turn is decrypted using their own password.

Just what we needed!


问:
Php in cmd unable to load ALL dinamic libraries
When i use php in cmd Windows console i got the following error:

C:\wamp64\bin\php\php5.6.25>php
      PHP Warning:  PHP Startup: Unable to load dynamic library 'c:/wamp/bin/php/php5.6.25/ext/php_bz2.dll' - No se puede encontrar el m¾dulo especificado.
       in Unknown on line 0
     [...]

And continues whit ALL the dll libraries. I Chek the rute and its ok. And when my wamp start a page whit php i dont get this error

For example i got the error when i type:

```<code>cd C:\wamp64\www\ServicioApp\scripts
php script_notificaciones.php
</code>```

I run php --ini and search in the file, and i got:

```<code>extension_dir ="c:/wamp/bin/php/php5.6.25/ext/"
</code>```

答:
My guess is that WAMP (its Apache config) looks for php.ini in different location than command line invoked script - run php --ini in console to find it. You will need to check and fix (or disable) extension paths there.

Search for line with extension_dir - it should point to ext folder with extensions (dlls). You may need to switch to backslashes there:

```<code>extension_dir = "c:\wamp\bin\php\php5.6.25\ext"
</code>```

Body:
When i use php in cmd Windows console i got the following error:

C:\wamp64\bin\php\php5.6.25>php
      PHP Warning:  PHP Startup: Unable to load dynamic library 'c:/wamp/bin/php/php5.6.25/ext/php_bz2.dll' - No se puede encontrar el m¾dulo especificado.
       in Unknown on line 0
     [...]

And continues whit ALL the dll libraries. I Chek the rute and its ok. And when my wamp start a page whit php i dont get this error

For example i got the error when i type:

cd C:\wamp64\www\ServicioApp\scripts
php script_notificaciones.php

I run php --ini and search in the file, and i got:

extension_dir ="c:/wamp/bin/php/php5.6.25/ext/"

Body:
My guess is that WAMP (its Apache config) looks for php.ini in different location than command line invoked script - run php --ini in console to find it. You will need to check and fix (or disable) extension paths there.

Search for line with extension_dir - it should point to ext folder with extensions (dlls). You may need to switch to backslashes there:

extension_dir = "c:\wamp\bin\php\php5.6.25\ext"


答:
(textBox1.backcolor = Color.Red) is trying to set textBox1.backcolor to Color.Red.

What you want is (textBox1.backcolor == Color.Red) because that is the conditional operator.

Title: Retrieving the backcolor in C#

Body:
I'm a absolute beginner. Just started to play with C#.
I want to switch the backcolor of a textBox.
If it is red, I want to change it into yellow.

Why is if (textBox1.backcolor = Color.Red) giving an error ?


问:
Sklearn kNN usage with a user defined metric (again)
Someone posted a similar question here but I couldn't get my job done

see

Sklearn kNN usage with a user defined metric

I want to define my user_metric and use it in KNN.

I have a signature problem it seems but I don't understand it. thanks

```<code>gamma=2

def mydist2 (x,y):
    z=(x-y)
    return (z[0]^2+gamma*z[1]^2)
neigh = KNeighborsClassifier(n_neighbors=3,metric=mydist2)

neigh.fit(traindata,train_labels)
neigh.score(testdata,test_labels)
</code>```

def mydist2 (x,y):ValueError                                Traceback
(most recent call last) <ipython-input-81-f934c7b5c9b3> in <module>()

→ 1 neigh.fit(traindata,train_labels)

   2 neigh.score(testdata,test_labels)

C:\Users\Fagui\Anaconda2\lib\site-packages\sklearn\neighbors\base.pyc

in fit(self, X, y)

801             self._y = self._y.ravel()

802

803         return self._fit(X)

804

805

C:\Users\Fagui\Anaconda2\lib\site-packages\sklearn\neighbors\base.pyc

in fit(self, X)

256             self.tree = BallTree(X, self.leaf_size,

257                                   metric=self.effective_metric,

--> 258                                   **self.effective_metric_params)

259         elif self._fit_method == 'kd_tree':

260             self._tree = KDTree(X, self.leaf_size,

    sklearn/neighbors/binary_tree.pxi in sklearn.neighbors.ball_tree.BinaryTree.init
(sklearn\neighbors\ball_tree.c:8381)()

    sklearn/neighbors/dist_metrics.pyx in sklearn.neighbors.dist_metrics.DistanceMetric.get_metric

(sklearn\neighbors\dist_metrics.c:4032)()

    sklearn/neighbors/dist_metrics.pyx in sklearn.neighbors.dist_metrics.PyFuncDistance.init

(sklearn\neighbors\dist_metrics.c:10628)()

    ValueError: func must be a callable taking two arrays

as a bonus question, I'd like to pass gamma as an argument

thanks very much

答:
Define a metric in Cython, build the module to create the library and call it from your main code.

Sklearn is optimized and use cython and several process to run as fast as possible. Writing pure python code especially when it is called several times will slow your code. I recommend that you write your custom metric using cython. You have a tutorial that you can follow right here

Body:
Someone posted a similar question here but I couldn't get my job done

see

Sklearn kNN usage with a user defined metric

I want to define my user_metric and use it in KNN.

I have a signature problem it seems but I don't understand it. thanks

gamma=2

def mydist2 (x,y):
    z=(x-y)
    return (z[0]^2+gamma*z[1]^2)
neigh = KNeighborsClassifier(n_neighbors=3,metric=mydist2)

neigh.fit(traindata,train_labels)
neigh.score(testdata,test_labels)

def mydist2 (x,y):ValueError                                Traceback
(most recent call last) <ipython-input-81-f934c7b5c9b3> in <module>()

→ 1 neigh.fit(traindata,train_labels)

   2 neigh.score(testdata,test_labels)

C:\Users\Fagui\Anaconda2\lib\site-packages\sklearn\neighbors\base.pyc

in fit(self, X, y)

801             self._y = self._y.ravel()

802

803         return self._fit(X)

804

805

C:\Users\Fagui\Anaconda2\lib\site-packages\sklearn\neighbors\base.pyc

in fit(self, X)

256             self.tree = BallTree(X, self.leaf_size,

257                                   metric=self.effective_metric,

--> 258                                   **self.effective_metric_params)

259         elif self._fit_method == 'kd_tree':

260             self._tree = KDTree(X, self.leaf_size,

    sklearn/neighbors/binary_tree.pxi in sklearn.neighbors.ball_tree.BinaryTree.init
(sklearn\neighbors\ball_tree.c:8381)()

    sklearn/neighbors/dist_metrics.pyx in sklearn.neighbors.dist_metrics.DistanceMetric.get_metric

(sklearn\neighbors\dist_metrics.c:4032)()

    sklearn/neighbors/dist_metrics.pyx in sklearn.neighbors.dist_metrics.PyFuncDistance.init

(sklearn\neighbors\dist_metrics.c:10628)()

    ValueError: func must be a callable taking two arrays

as a bonus question, I'd like to pass gamma as an argument

thanks very much


答:
If statements check booleans, you are using the wrong operator. </p>

```<code>if (textBox1.backcolor == Color.Red)
{
    textBox1.backcolor = Color.Yellow;
}
</code>```

Title: Retrieving the backcolor in C#

Body:
If statements check booleans, you are using the wrong operator.

if (textBox1.backcolor == Color.Red)
{
    textBox1.backcolor = Color.Yellow;
}


问:
angular-cli server - how to proxy API requests to another server?
With the angular-cli ng serve local dev server, it's serving all the static files from my project directory.

How can I proxy my AJAX calls to a different server?

答:
Here is another working example (@angular/cli 1.0.4):

proxy.conf.json :

```<code>{
  "/api/*" : {
    "target": "http://localhost:8181",
    "secure": false,
    "logLevel": "debug"
  },
  "/login.html" : {
    "target": "http://localhost:8181/login.html",
    "secure": false,
    "logLevel": "debug"
  }
}
</code>```

run with :

```<code>ng serve --proxy-config proxy.conf.json
</code>```

Body:
Here is another working example (@angular/cli 1.0.4):

proxy.conf.json :

{
  "/api/*" : {
    "target": "http://localhost:8181",
    "secure": false,
    "logLevel": "debug"
  },
  "/login.html" : {
    "target": "http://localhost:8181/login.html",
    "secure": false,
    "logLevel": "debug"
  }
}

run with :

ng serve --proxy-config proxy.conf.json