问:
Replacing < with < using XSLT
I have an incoming XML where i am having < instead of < can we replace all the incoming < with < tag using XSLT. Can somebody let me know how can we achieve that.

Input:

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <soapenv:Body>
        <ns1:pr xmlns:ns1="http://example.com">
            <ns1:dis>
                <TP memberID="121897679001" FirstName="Tom" LastName="regen" auId="42424234">
                    <TPV>
                        <KAN>
                            <sur sType="POI" cDate="09022017" MDate="09022017" eDate="05182003">
                                <question id="9" desc="afa">
                                    <ans id="0" desc="des">09172017</ans>
                                </question>
                            </sur>
                        </KAN>
                    </TPV>
                </TP>
            </ns1:dis>
        </ns1:pr>
    </soapenv:Body>
</soapenv:Envelope>
</code>```

Expected Output:

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <soapenv:Body>
        <ns1:pr xmlns:ns1="http://example.com">
            <ns1:dis>
                <TP memberID="121897679001" FirstName="Tom" LastName="regen" auId="42424234">
                    <TPV>
                        <KAN>
                            <sur sType="POI" cDate="09022017" MDate="09022017" eDate="05182003">
                                <question id="9" desc="afa">
                                    <ans id="0" desc="des">09172017</ans>
                                </question>
                            </sur>
                        </KAN>
                    </TPV>
                </TP>
            </ns1:dis>
        </ns1:pr>
    </soapenv:Body>
</soapenv:Envelope>
</code>```

答:
Your xml is not valid because </ans> is not started with <ans>, I don't believe you can apply XSLT on it.

If your language is Java, you can use replaceAll like:

```<code>inputXml = inputXml.replaceAll( "<", "<" );
</code>```

Title: Replacing < with < using XSLT

Body:
I have an incoming XML where i am having < instead of < can we replace all the incoming < with < tag using XSLT. Can somebody let me know how can we achieve that.

Input:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <soapenv:Body>
        <ns1:pr xmlns:ns1="http://example.com">
            <ns1:dis>
                <TP memberID="121897679001" FirstName="Tom" LastName="regen" auId="42424234">
                    <TPV>
                        <KAN>
                            <sur sType="POI" cDate="09022017" MDate="09022017" eDate="05182003">
                                <question id="9" desc="afa">
                                    <ans id="0" desc="des">09172017</ans>
                                </question>
                            </sur>
                        </KAN>
                    </TPV>
                </TP>
            </ns1:dis>
        </ns1:pr>
    </soapenv:Body>
</soapenv:Envelope>

Expected Output:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <soapenv:Body>
        <ns1:pr xmlns:ns1="http://example.com">
            <ns1:dis>
                <TP memberID="121897679001" FirstName="Tom" LastName="regen" auId="42424234">
                    <TPV>
                        <KAN>
                            <sur sType="POI" cDate="09022017" MDate="09022017" eDate="05182003">
                                <question id="9" desc="afa">
                                    <ans id="0" desc="des">09172017</ans>
                                </question>
                            </sur>
                        </KAN>
                    </TPV>
                </TP>
            </ns1:dis>
        </ns1:pr>
    </soapenv:Body>
</soapenv:Envelope>

Body:
Your xml is not valid because </ans> is not started with <ans>, I don't believe you can apply XSLT on it.

If your language is Java, you can use replaceAll like:

inputXml = inputXml.replaceAll( "&lt;", "<" );


来源: stackexchange

问:
Benchmark on different String dictionaries shows that the normal one is faster, and I don't know why
I'm doing some benchmark on several string dictionaries, because I wanted to find out how performs the different configurations, and I got surprised that the normal Dictionary<String,String> is the faster. Probably because I'm missing some concept or I'm doing something wrong, but these are the results I got:

```<code>Collection:             2147482 items.
Random Keys:            1000 keys.

Normal dictionary
        Add 1000 items:         573ms.
        Get 1000 keys:          0ms.

Normal Dictionary with OrdinalIgnoreCase comparer
        Add 1000 items:         642ms.
        Get 1000 keys:          0ms.

Normal Dictionary with InvariantCultureIgnoreCase comparer
        Add 1000 items:         1661ms.
        Get 1000 keys:          0ms.

Sorted dictionary
        Add 1000 items:         11996ms.
        Get 1000 keys:          5ms.

Sorted dictionary with OrdinalIgnoreCase comparer
        Add 1000 items:         11097ms.
        Get 1000 keys:          5ms.

Sorted dictionary with InvariantCultureIgnoreCase comparer
        Add 1000 items:         9814ms.
        Get 1000 keys:          5ms.
</code>```

An this is the code I'm using to test it:

```<code>    static void Main(string[] args)
    {
        String[] col = GenerateCollectionUnsorted(Int32.MaxValue / 1000).ToArray();
        Int32 len = col.Length;
        Console.WriteLine("Collection:\t\t" + len.ToString() + " items.");

        String[] randomKeys = GetRandomKeys(col, 1000);
        Console.WriteLine("Random Keys:\t\t" + randomKeys.Length.ToString() + " keys.");

        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine();
        Console.WriteLine("Normal dictionary");
        TestDic(col, randomKeys, new Dictionary<String, String>());
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine();
        Console.WriteLine("Normal Dictionary with OrdinalIgnoreCase comparer");
        TestDic(col, randomKeys, new Dictionary<String, String>(StringComparer.OrdinalIgnoreCase));
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine();
        Console.WriteLine("Normal Dictionary with InvariantCultureIgnoreCase comparer");
        TestDic(col, randomKeys, new Dictionary<String, String>(StringComparer.InvariantCultureIgnoreCase));
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine();
        Console.WriteLine("Sorted dictionary");
        TestDic(col,randomKeys, new SortedDictionary<String,String>());
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine();
        Console.WriteLine("Sorted dictionary with OrdinalIgnoreCase comparer");
        TestDic(col, randomKeys, new SortedDictionary<String, String>(StringComparer.OrdinalIgnoreCase));
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine();
        Console.WriteLine("Sorted dictionary with InvariantCultureIgnoreCase comparer");
        TestDic(col, randomKeys, new SortedDictionary<String, String>(StringComparer.InvariantCultureIgnoreCase));
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine("\nEnd");
        Console.ReadKey(true);
    }

    static void TestDic(String[] col, String[] randomKeys, IDictionary<String,String> dic)
    {
        Stopwatch crono = new Stopwatch();

        crono.Start();
        foreach (String s in col)
            dic.Add(s, s);
        crono.Stop();

        Console.WriteLine("\tAdd "+randomKeys.Length.ToString()+" items:\t\t" + crono.ElapsedMilliseconds.ToString() + "ms.");

        crono.Reset();
        crono.Start();
        String sv;
        foreach (var rk in randomKeys)
        {
            sv = dic[rk];
            sv.ToString();
        }
        crono.Stop();
        Console.WriteLine("\tGet " + randomKeys.Length.ToString() + " keys:\t\t" + crono.ElapsedMilliseconds.ToString() + "ms.");
    }

    static String[] GetRandomKeys(String[] col, Int32 count)
    {
        Random ran = new Random(DateTime.Now.Millisecond);

        List<Int32> indexSelection = new List<int>();
        List<String> selection = new List<string>();

        Int32 len = col.Length;

        while (indexSelection.Count < count)
        {
            Int32 value = ran.Next(0, len - 1);
            if (!indexSelection.Contains(value))
            {
                indexSelection.Add(value);
                selection.Add(col[value]);
            }
        }
        return selection.ToArray();
    }

    static IEnumerable<String> GenerateCollection(Int32 count)
    {
        for (int i = 0; i < count; i++)
        {
            yield return i.ToString("X").PadLeft(5, '0');
        }
    }

    static IEnumerable<String> GenerateCollectionUnsorted(Int32 amount)
    {
        for (int i = 0; i < amount / 2; i++)
        {
            yield return i.ToString("X").PadLeft(5, '0');
            yield return (amount-i).ToString("X").PadLeft(5, '0');
        }
    }
</code>```

Any idea why is this happening?

EDIT 1: It was my understanding that sorted dictionary would be slower adding items, and faster getting them because the collection is sorted. And also that comparing strings with a OrdinalIgnoreCase or InvariantCultureIgnoreCase should be faster that a normal comparision, so the seek should be faster. But maybe my understanding is completely wrong :D

Thanks in advance.

EDIT 2: As curiosity, I've made some test on String comparisons:

```<code>Collection:             2147482 items.
Random Keys:            1000 keys.

CurrentCulture
        LookUp:         158209ms.

CurrentCultureIgnoreCase
        LookUp:         160710ms.

InvariantCulture
        LookUp:         132765ms.

InvariantCultureIgnoreCase
        LookUp:         133409ms.

Ordinal
        LookUp:         36115ms.

OrdinalIgnoreCase
        LookUp:         36329ms.
</code>```

答:
I'm failing to see why you would be surprised at the results.

"normal"/unsorted would obviously be faster than a sorted dictionary as the sorted one would have to perform extra operations.

The two "normal" ones that have extra options both require extra processing as well.

ContentLicense: CC BY-SA 4.0

Body:
I'm doing some benchmark on several string dictionaries, because I wanted to find out how performs the different configurations, and I got surprised that the normal Dictionary<String,String> is the faster. Probably because I'm missing some concept or I'm doing something wrong, but these are the results I got:

Collection:             2147482 items.
Random Keys:            1000 keys.

Normal dictionary
        Add 1000 items:         573ms.
        Get 1000 keys:          0ms.

Normal Dictionary with OrdinalIgnoreCase comparer
        Add 1000 items:         642ms.
        Get 1000 keys:          0ms.

Normal Dictionary with InvariantCultureIgnoreCase comparer
        Add 1000 items:         1661ms.
        Get 1000 keys:          0ms.

Sorted dictionary
        Add 1000 items:         11996ms.
        Get 1000 keys:          5ms.

Sorted dictionary with OrdinalIgnoreCase comparer
        Add 1000 items:         11097ms.
        Get 1000 keys:          5ms.

Sorted dictionary with InvariantCultureIgnoreCase comparer
        Add 1000 items:         9814ms.
        Get 1000 keys:          5ms.

An this is the code I'm using to test it:

    static void Main(string[] args)
    {
        String[] col = GenerateCollectionUnsorted(Int32.MaxValue / 1000).ToArray();
        Int32 len = col.Length;
        Console.WriteLine("Collection:\t\t" + len.ToString() + " items.");

        String[] randomKeys = GetRandomKeys(col, 1000);
        Console.WriteLine("Random Keys:\t\t" + randomKeys.Length.ToString() + " keys.");

        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine();
        Console.WriteLine("Normal dictionary");
        TestDic(col, randomKeys, new Dictionary<String, String>());
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine();
        Console.WriteLine("Normal Dictionary with OrdinalIgnoreCase comparer");
        TestDic(col, randomKeys, new Dictionary<String, String>(StringComparer.OrdinalIgnoreCase));
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine();
        Console.WriteLine("Normal Dictionary with InvariantCultureIgnoreCase comparer");
        TestDic(col, randomKeys, new Dictionary<String, String>(StringComparer.InvariantCultureIgnoreCase));
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine();
        Console.WriteLine("Sorted dictionary");
        TestDic(col,randomKeys, new SortedDictionary<String,String>());
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine();
        Console.WriteLine("Sorted dictionary with OrdinalIgnoreCase comparer");
        TestDic(col, randomKeys, new SortedDictionary<String, String>(StringComparer.OrdinalIgnoreCase));
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine();
        Console.WriteLine("Sorted dictionary with InvariantCultureIgnoreCase comparer");
        TestDic(col, randomKeys, new SortedDictionary<String, String>(StringComparer.InvariantCultureIgnoreCase));
        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine("\nEnd");
        Console.ReadKey(true);
    }

    static void TestDic(String[] col, String[] randomKeys, IDictionary<String,String> dic)
    {
        Stopwatch crono = new Stopwatch();

        crono.Start();
        foreach (String s in col)
            dic.Add(s, s);
        crono.Stop();

        Console.WriteLine("\tAdd "+randomKeys.Length.ToString()+" items:\t\t" + crono.ElapsedMilliseconds.ToString() + "ms.");

        crono.Reset();
        crono.Start();
        String sv;
        foreach (var rk in randomKeys)
        {
            sv = dic[rk];
            sv.ToString();
        }
        crono.Stop();
        Console.WriteLine("\tGet " + randomKeys.Length.ToString() + " keys:\t\t" + crono.ElapsedMilliseconds.ToString() + "ms.");
    }

    static String[] GetRandomKeys(String[] col, Int32 count)
    {
        Random ran = new Random(DateTime.Now.Millisecond);

        List<Int32> indexSelection = new List<int>();
        List<String> selection = new List<string>();

        Int32 len = col.Length;

        while (indexSelection.Count < count)
        {
            Int32 value = ran.Next(0, len - 1);
            if (!indexSelection.Contains(value))
            {
                indexSelection.Add(value);
                selection.Add(col[value]);
            }
        }
        return selection.ToArray();
    }

    static IEnumerable<String> GenerateCollection(Int32 count)
    {
        for (int i = 0; i < count; i++)
        {
            yield return i.ToString("X").PadLeft(5, '0');
        }
    }

    static IEnumerable<String> GenerateCollectionUnsorted(Int32 amount)
    {
        for (int i = 0; i < amount / 2; i++)
        {
            yield return i.ToString("X").PadLeft(5, '0');
            yield return (amount-i).ToString("X").PadLeft(5, '0');
        }
    }

Any idea why is this happening?

EDIT 1: It was my understanding that sorted dictionary would be slower adding items, and faster getting them because the collection is sorted. And also that comparing strings with a OrdinalIgnoreCase or InvariantCultureIgnoreCase should be faster that a normal comparision, so the seek should be faster. But maybe my understanding is completely wrong :D

Thanks in advance.

EDIT 2: As curiosity, I've made some test on String comparisons:

Collection:             2147482 items.
Random Keys:            1000 keys.

CurrentCulture
        LookUp:         158209ms.

CurrentCultureIgnoreCase
        LookUp:         160710ms.

InvariantCulture
        LookUp:         132765ms.

InvariantCultureIgnoreCase
        LookUp:         133409ms.

Ordinal
        LookUp:         36115ms.

OrdinalIgnoreCase
        LookUp:         36329ms.

ContentLicense: CC BY-SA 2.5


答:
Assuming the contents of that ns1:dis element is a properly escaped XML fragment (your snippet is not, because the </ans> would need to be </ans>) you can as of today use XSLT 3.0 and the parse-xml-fragment function (https://www.w3.org/TR/xpath-functions-31/#func-parse-xml-fragment) as follows:

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:math="http://www.w3.org/2005/xpath-functions/math"
    exclude-result-prefixes="xs math"
    version="3.0">

    <xsl:mode on-no-match="shallow-copy"/>

    <xsl:template match="dis" xpath-default-namespace="http://example.com">
        <xsl:copy>
            <xsl:copy-of select="parse-xml-fragment(.)"/>
        </xsl:copy>
    </xsl:template>

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

Should work with Saxon 9.8 (all editions) or 9.7 (PE or EE) and with current releases of Altova XMLSpy/Raptor as with any other XSLT 3.0 implementations.

ContentLicense: CC BY-SA 3.0

Title: Replacing < with < using XSLT

Body:
Assuming the contents of that ns1:dis element is a properly escaped XML fragment (your snippet is not, because the </ans> would need to be &lt;/ans>) you can as of today use XSLT 3.0 and the parse-xml-fragment function (https://www.w3.org/TR/xpath-functions-31/#func-parse-xml-fragment) as follows:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:math="http://www.w3.org/2005/xpath-functions/math"
    exclude-result-prefixes="xs math"
    version="3.0">

    <xsl:mode on-no-match="shallow-copy"/>

    <xsl:template match="dis" xpath-default-namespace="http://example.com">
        <xsl:copy>
            <xsl:copy-of select="parse-xml-fragment(.)"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

Should work with Saxon 9.8 (all editions) or 9.7 (PE or EE) and with current releases of Altova XMLSpy/Raptor as with any other XSLT 3.0 implementations.


问:
Error "Maximum Characters Exceeded in SQL Statement EDIT: Issue Displaying Table
Thank you for helping. I am brand new to SQL programming (as in, this is my first assignment) and I completely don't understand why this is not working.
My goal is just to make this into a simple table. I was asked to use the SWL interpreter from sqlcourse.com, and when I put in the program I get the error "Maximum characters exceeded in SQL statement." Each time I check my statement I'm missing where the error is. Help please?

My Statement:

```<code>create table Marchetta1
(CustomerNum number(15), CustomerName char(15),
 Street varchar(15), City char(15),
 State char(2), Zip number(5), Balance number (8,2),
 CreditLimit number (8,2), RepNum varchar (5));

insert into Marchetta1
(CustomerNum, CustomerName, Street, City,
State, Zip, Balance, CreditLimit, RepNum)
values ('123', 'Bob Smith', '8215 Cherry St', 'Grove', 'FL', '33331', '500.23', '1000', 'FP123');

insert into Marchetta1 (CustomerNum, CustomerName, Street,
City, State, Zip, Balance, CreditLimit, RepNum)
values ('456', 'Lucy James', '4711 Ohio St', 'Chicago', 'IL', '60644',
'7000.44', '5000.80', 'FP123');

insert into Marchetta1 (CustomerNum, CustomerName, Street,
City, State, Zip, Balance, CreditLimit, RepNum)
values ('789', 'John Jones', '925 Main St', 'Grove', 'FL', '33385', '87.50', '2000.72', 'FP123');
</code>```

EDIT: The fixes seemed to work and the commands are executed...but I have no way to check since my table is not displaying. How do I do that?

Thanks.

答: Just a note, while inserting 'number' values into the table, they're usually entered without inverted commas. For e.g. values (123, 'Bob Smith'....)</p>

Body:
Thank you for helping. I am brand new to SQL programming (as in, this is my first assignment) and I completely don't understand why this is not working.
My goal is just to make this into a simple table. I was asked to use the SWL interpreter from sqlcourse.com, and when I put in the program I get the error "Maximum characters exceeded in SQL statement." Each time I check my statement I'm missing where the error is. Help please?

My Statement:

create table Marchetta1
(CustomerNum number(15), CustomerName char(15),
 Street varchar(15), City char(15),
 State char(2), Zip number(5), Balance number (8,2),
 CreditLimit number (8,2), RepNum varchar (5));

insert into Marchetta1
(CustomerNum, CustomerName, Street, City,
State, Zip, Balance, CreditLimit, RepNum)
values ('123', 'Bob Smith', '8215 Cherry St', 'Grove', 'FL', '33331', '500.23', '1000', 'FP123');

insert into Marchetta1 (CustomerNum, CustomerName, Street,
City, State, Zip, Balance, CreditLimit, RepNum)
values ('456', 'Lucy James', '4711 Ohio St', 'Chicago', 'IL', '60644',
'7000.44', '5000.80', 'FP123');

insert into Marchetta1 (CustomerNum, CustomerName, Street,
City, State, Zip, Balance, CreditLimit, RepNum)
values ('789', 'John Jones', '925 Main St', 'Grove', 'FL', '33385', '87.50', '2000.72', 'FP123');

EDIT: The fixes seemed to work and the commands are executed...but I have no way to check since my table is not displaying. How do I do that?

Thanks.


问:
Calculate age in years and months by adding period class objects together with lubridate in R
My data has a variable for baseline age, and a follow up variable with number of months since baseline observation. Both are numeric vectors with whole numbers only.  I want to calculate age at follow up. When I parse these variables to period objects using lubridate and add them together I get results like 5 years 14 months. Ideally - I'd like this to be 6 years 2 months.

Example

```<code>library(dplyr)
library(lubridate)
library(magrittr)

set.seed(080617)
df <-
  tibble(year = sample(20),
     month = sample(20))

df %<>%
  mutate(year = years(year)) %>%
  mutate(month = months(month)) %>%
  mutate(age = (year + month))
df
</code>```

I have tried using df$age <- as.period(df$age, units = "years") to no avail.

Any suggestions?

答:
This should get you the result you're looking for. I changed the column names to year.col and month.col, to make it easier to follow the logic</p>

```<code>library(dplyr)
library(lubridate)
library(magrittr)

set.seed(080617)
df <-
  tibble(year.col = sample(20),
         month.col = sample(20))

df %<>%
  mutate(year.col = years(year.col)) %>%
  mutate(month.col = months(month.col)) %>%
  mutate(age = year.col + years(month(month.col) %/% 12) + months(month(month.col) %% 12))
</code>```

Body:
My data has a variable for baseline age, and a follow up variable with number of months since baseline observation. Both are numeric vectors with whole numbers only.  I want to calculate age at follow up. When I parse these variables to period objects using lubridate and add them together I get results like 5 years 14 months. Ideally - I'd like this to be 6 years 2 months.

Example

library(dplyr)
library(lubridate)
library(magrittr)

set.seed(080617)
df <-
  tibble(year = sample(20),
     month = sample(20))

df %<>%
  mutate(year = years(year)) %>%
  mutate(month = months(month)) %>%
  mutate(age = (year + month))
df

I have tried using df$age <- as.period(df$age, units = "years") to no avail.

Any suggestions?

Body:
This should get you the result you're looking for. I changed the column names to year.col and month.col, to make it easier to follow the logic

library(dplyr)
library(lubridate)
library(magrittr)

set.seed(080617)
df <-
  tibble(year.col = sample(20),
         month.col = sample(20))

df %<>%
  mutate(year.col = years(year.col)) %>%
  mutate(month.col = months(month.col)) %>%
  mutate(age = year.col + years(month(month.col) %/% 12) + months(month(month.col) %% 12))


问:
pd.DataFrame.from_csv error related to infer_datetime_format
I'm trying to read a CSV file into a pandas dataframe. It contains a mixture of numbers, strings, and dates. I tried:

```<code>trades_df = pd.DataFrame.from_csv('trades.csv')
</code>```

and got the error:

```<code>---------------------------------------------------------------------------
ParserError                               Traceback (most recent call last)
<ipython-input-10-af86bdcdc851> in <module>()
      1 # read a database from CSV and load it into a pandas dataframe
----> 2 trades_df = pd.DataFrame.from_csv('trades.csv', infer_datetime_format=True)
      3 trades_df.head()

~/anaconda/envs/env3_insight/lib/python3.6/site-packages/pandas/core/frame.py in from_csv(cls, path, header, sep, index_col, parse_dates, encoding, tupleize_cols, infer_datetime_format)
   1249                           parse_dates=parse_dates, index_col=index_col,
   1250                           encoding=encoding, tupleize_cols=tupleize_cols,
-> 1251                           infer_datetime_format=infer_datetime_format)
   1252
   1253     def to_sparse(self, fill_value=None, kind='block'):

~/anaconda/envs/env3_insight/lib/python3.6/site-packages/pandas/io/parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, escapechar, comment, encoding, dialect, tupleize_cols, error_bad_lines, warn_bad_lines, skipfooter, skip_footer, doublequote, delim_whitespace, as_recarray, compact_ints, use_unsigned, low_memory, buffer_lines, memory_map, float_precision)
    653                     skip_blank_lines=skip_blank_lines)
    654
--> 655         return _read(filepath_or_buffer, kwds)
    656
    657     parser_f.__name__ = name

~/anaconda/envs/env3_insight/lib/python3.6/site-packages/pandas/io/parsers.py in _read(filepath_or_buffer, kwds)
    409
    410     try:
--> 411         data = parser.read(nrows)
    412     finally:
    413         parser.close()

~/anaconda/envs/env3_insight/lib/python3.6/site-packages/pandas/io/parsers.py in read(self, nrows)
   1003                 raise ValueError('skipfooter not supported for iteration')
   1004
-> 1005         ret = self._engine.read(nrows)
   1006
   1007         if self.options.get('as_recarray'):

~/anaconda/envs/env3_insight/lib/python3.6/site-packages/pandas/io/parsers.py in read(self, nrows)
   1746     def read(self, nrows=None):
   1747         try:
-> 1748             data = self._reader.read(nrows)
   1749         except StopIteration:
   1750             if self._first_chunk:

pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader.read (pandas/_libs/parsers.c:10862)()

pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._read_low_memory (pandas/_libs/parsers.c:11138)()

pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._read_rows (pandas/_libs/parsers.c:11884)()

pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._tokenize_rows (pandas/_libs/parsers.c:11755)()

pandas/_libs/parsers.pyx in pandas._libs.parsers.raise_parser_error (pandas/_libs/parsers.c:28765)()

ParserError: Error tokenizing data. C error: Expected 49 fields in line 1110195, saw 65
</code>```

I think pandas isn't happy because of the date format in the CSV file. I tried different encoding, infer_datetime_format=True, dtype=str, dtype=object. No luck :( Any ideas?

答:
Okay, I ended up figuring out. These were my 2 approaches:

Create everything as a string then change type later.

```<code>mystuff = pandas.read_csv(trades.csv, dtype=str)
</code>```

Then I changed the type with:

```<code>mystuff['col_a'] = mystuff[['col_b']].apply(pd.to_numeric)
mystuff['col_c'] = mystuff['col_c'].apply(pd.to_datetime, format='%Y%m%d', errors='coerce')
</code>```

Assign what type of data each column is from the start.

```<code>pandas.read_csv(path,dtype={'col_a':str,'col_b':int, 'col_c':datetime...})
</code>```

Body:
I'm trying to read a CSV file into a pandas dataframe. It contains a mixture of numbers, strings, and dates. I tried:

trades_df = pd.DataFrame.from_csv('trades.csv')

and got the error:

---------------------------------------------------------------------------
ParserError                               Traceback (most recent call last)
<ipython-input-10-af86bdcdc851> in <module>()
      1 # read a database from CSV and load it into a pandas dataframe
----> 2 trades_df = pd.DataFrame.from_csv('trades.csv', infer_datetime_format=True)
      3 trades_df.head()

~/anaconda/envs/env3_insight/lib/python3.6/site-packages/pandas/core/frame.py in from_csv(cls, path, header, sep, index_col, parse_dates, encoding, tupleize_cols, infer_datetime_format)
   1249                           parse_dates=parse_dates, index_col=index_col,
   1250                           encoding=encoding, tupleize_cols=tupleize_cols,
-> 1251                           infer_datetime_format=infer_datetime_format)
   1252
   1253     def to_sparse(self, fill_value=None, kind='block'):

~/anaconda/envs/env3_insight/lib/python3.6/site-packages/pandas/io/parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, escapechar, comment, encoding, dialect, tupleize_cols, error_bad_lines, warn_bad_lines, skipfooter, skip_footer, doublequote, delim_whitespace, as_recarray, compact_ints, use_unsigned, low_memory, buffer_lines, memory_map, float_precision)
    653                     skip_blank_lines=skip_blank_lines)
    654
--> 655         return _read(filepath_or_buffer, kwds)
    656
    657     parser_f.__name__ = name

~/anaconda/envs/env3_insight/lib/python3.6/site-packages/pandas/io/parsers.py in _read(filepath_or_buffer, kwds)
    409
    410     try:
--> 411         data = parser.read(nrows)
    412     finally:
    413         parser.close()

~/anaconda/envs/env3_insight/lib/python3.6/site-packages/pandas/io/parsers.py in read(self, nrows)
   1003                 raise ValueError('skipfooter not supported for iteration')
   1004
-> 1005         ret = self._engine.read(nrows)
   1006
   1007         if self.options.get('as_recarray'):

~/anaconda/envs/env3_insight/lib/python3.6/site-packages/pandas/io/parsers.py in read(self, nrows)
   1746     def read(self, nrows=None):
   1747         try:
-> 1748             data = self._reader.read(nrows)
   1749         except StopIteration:
   1750             if self._first_chunk:

pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader.read (pandas/_libs/parsers.c:10862)()

pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._read_low_memory (pandas/_libs/parsers.c:11138)()

pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._read_rows (pandas/_libs/parsers.c:11884)()

pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._tokenize_rows (pandas/_libs/parsers.c:11755)()

pandas/_libs/parsers.pyx in pandas._libs.parsers.raise_parser_error (pandas/_libs/parsers.c:28765)()

ParserError: Error tokenizing data. C error: Expected 49 fields in line 1110195, saw 65

I think pandas isn't happy because of the date format in the CSV file. I tried different encoding, infer_datetime_format=True, dtype=str, dtype=object. No luck :( Any ideas?

Body:
Okay, I ended up figuring out. These were my 2 approaches:

Create everything as a string then change type later.

mystuff = pandas.read_csv(trades.csv, dtype=str)

Then I changed the type with:

mystuff['col_a'] = mystuff[['col_b']].apply(pd.to_numeric)
mystuff['col_c'] = mystuff['col_c'].apply(pd.to_datetime, format='%Y%m%d', errors='coerce')

Assign what type of data each column is from the start.

pandas.read_csv(path,dtype={'col_a':str,'col_b':int, 'col_c':datetime...})


问:
Keeping log files under a certain size
I have an application that is running on a stand-alone panel PC in a kiosk (C#/WPF). It performs some typical logging operations to a text file. The PC has some limited amount of disk space to store these logs as they grow.

What I need to do is be able to specify the maximum size that a log file is allowed to be. If, when attempting to write to the log, the max size is exceeded, new data will be written to the end of the log and the oldest data will be purged from the beginning.

Getting the file size is no problem, but are there any typical file manipulation techniques to keep a file under a certain size?

答:
I wouldn't use this for a file meant to be over say 1 Meg and it's not terribly efficient, but it works good if you need to solve a pesky problem of when you need a log file that you can't conveniently maintain. Make sure the log file exists before you use this though... or you could add code for it as well as checking the location exists, etc.</p>

```<code>// This is how to call it
private void buttonLog_Click(object sender, EventArgs e)
{
    c_Log.writeToFile(textBoxMessages.Text, "../../log.log", 1);
}

public static class c_Log
{
    static int iMaxLogLength = 15000; // Probably should be bigger, say 200,000
    static int iTrimmedLogLength = -1000; // minimum of how much of the old log to leave

    static public void writeToFile(string strNewLogMessage, string strFile, int iLogLevel)
    {
        try
        {
            FileInfo fi = new FileInfo(strFile);

            Byte[] bytesSavedFromEndOfOldLog = null;

            if (fi.Length > iMaxLogLength) // if the log file length is already too long
            {
                using (BinaryReader br = new BinaryReader(File.Open(strFile, FileMode.Open)))
                {
                    // Seek to our required position of what you want saved.
                    br.BaseStream.Seek(iTrimmedLogLength, SeekOrigin.End);

                    // Read what you want to save and hang onto it.
                    bytesSavedFromEndOfOldLog = br.ReadBytes((-1 * iTrimmedLogLength));
                }
            }

            byte[] newLine = System.Text.ASCIIEncoding.ASCII.GetBytes(Environment.NewLine);

            FileStream fs = null;
            // If the log file is less than the max length, just open it at the end to write there
            if (fi.Length < iMaxLogLength)
                fs = new FileStream(strFile, FileMode.Append, FileAccess.Write, FileShare.Read);
            else // If the log file is more than the max length, just open it empty
                fs = new FileStream(strFile, FileMode.Create, FileAccess.Write, FileShare.Read);

            using (fs)
            {
                // If you are trimming the file length, write what you saved.
                if (bytesSavedFromEndOfOldLog != null)
                {
                    Byte[] lineBreak = Encoding.ASCII.GetBytes("### " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " *** *** *** Old Log Start Position *** *** *** *** ###");
                    fs.Write(newLine, 0, newLine.Length);
                    fs.Write(newLine, 0, newLine.Length);
                    fs.Write(lineBreak, 0, lineBreak.Length);
                    fs.Write(newLine, 0, newLine.Length);
                    fs.Write(bytesSavedFromEndOfOldLog, 0, bytesSavedFromEndOfOldLog.Length);
                    fs.Write(newLine, 0, newLine.Length);
                }
                Byte[] sendBytes = Encoding.ASCII.GetBytes(strNewLogMessage);
                // Append your last log message.
                fs.Write(sendBytes, 0, sendBytes.Length);
                fs.Write(newLine, 0, newLine.Length);
            }
        }
        catch (Exception ex)
        {
            ; // Nothing to do...
              //writeEvent("writeToFile() Failed to write to logfile : " + ex.Message + "...", 5);
        }
    }
}
</code>```

Title: Keeping log files under a certain size

Body:
I wouldn't use this for a file meant to be over say 1 Meg and it's not terribly efficient, but it works good if you need to solve a pesky problem of when you need a log file that you can't conveniently maintain. Make sure the log file exists before you use this though... or you could add code for it as well as checking the location exists, etc.

// This is how to call it
private void buttonLog_Click(object sender, EventArgs e)
{
    c_Log.writeToFile(textBoxMessages.Text, "../../log.log", 1);
}

public static class c_Log
{
    static int iMaxLogLength = 15000; // Probably should be bigger, say 200,000
    static int iTrimmedLogLength = -1000; // minimum of how much of the old log to leave

    static public void writeToFile(string strNewLogMessage, string strFile, int iLogLevel)
    {
        try
        {
            FileInfo fi = new FileInfo(strFile);

            Byte[] bytesSavedFromEndOfOldLog = null;

            if (fi.Length > iMaxLogLength) // if the log file length is already too long
            {
                using (BinaryReader br = new BinaryReader(File.Open(strFile, FileMode.Open)))
                {
                    // Seek to our required position of what you want saved.
                    br.BaseStream.Seek(iTrimmedLogLength, SeekOrigin.End);

                    // Read what you want to save and hang onto it.
                    bytesSavedFromEndOfOldLog = br.ReadBytes((-1 * iTrimmedLogLength));
                }
            }

            byte[] newLine = System.Text.ASCIIEncoding.ASCII.GetBytes(Environment.NewLine);

            FileStream fs = null;
            // If the log file is less than the max length, just open it at the end to write there
            if (fi.Length < iMaxLogLength)
                fs = new FileStream(strFile, FileMode.Append, FileAccess.Write, FileShare.Read);
            else // If the log file is more than the max length, just open it empty
                fs = new FileStream(strFile, FileMode.Create, FileAccess.Write, FileShare.Read);

            using (fs)
            {
                // If you are trimming the file length, write what you saved.
                if (bytesSavedFromEndOfOldLog != null)
                {
                    Byte[] lineBreak = Encoding.ASCII.GetBytes("### " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " *** *** *** Old Log Start Position *** *** *** *** ###");
                    fs.Write(newLine, 0, newLine.Length);
                    fs.Write(newLine, 0, newLine.Length);
                    fs.Write(lineBreak, 0, lineBreak.Length);
                    fs.Write(newLine, 0, newLine.Length);
                    fs.Write(bytesSavedFromEndOfOldLog, 0, bytesSavedFromEndOfOldLog.Length);
                    fs.Write(newLine, 0, newLine.Length);
                }
                Byte[] sendBytes = Encoding.ASCII.GetBytes(strNewLogMessage);
                // Append your last log message.
                fs.Write(sendBytes, 0, sendBytes.Length);
                fs.Write(newLine, 0, newLine.Length);
            }
        }
        catch (Exception ex)
        {
            ; // Nothing to do...
              //writeEvent("writeToFile() Failed to write to logfile : " + ex.Message + "...", 5);
        }
    }
}


问:
firebase -> date order reverse
I am currently making an app using Firebase.

It is one of those bulletin boards that can be seen anywhere on the web.

But there was one problem.

This is a matter of date sorting.

I want to look at the recent date first, but I always see only the data I created first.

```<code>postRef.orderByChild('createData').startAt(reverseDate).limitToFirst(1).on('child_added',(data)=>{
    console.log(data.val().name + data.val().createData);
})
</code>```

result - >hello1496941142093

My firebase tree

My code is the same as above.

How can I check my recent posts first?

How Do I order reverse of firebase database?

答:
The Firebase Database will always return results in ascending order. There is no way to reverse them.

There are two common workaround for this:

Let the database do the filtering, but then reverse the results client-side.

Add an inverted value to the database, and use that for querying.

These options have been covered quite a few times before. So instead of repeating, I'll give a list of previous answers:

Display posts in descending posted order

Sort firebase data in descending order using negative timestamp

firebase sort reverse order

Is it possible to reverse a Firebase list?

many more from this list: https://www.google.com/search?q=site:stackoverflow.com+firebase+reverse%20sort%20javascript

Title: firebase -> date order reverse

Body:
I am currently making an app using Firebase.

It is one of those bulletin boards that can be seen anywhere on the web.

But there was one problem.

This is a matter of date sorting.

I want to look at the recent date first, but I always see only the data I created first.

postRef.orderByChild('createData').startAt(reverseDate).limitToFirst(1).on('child_added',(data)=>{
    console.log(data.val().name + data.val().createData);
})

result - >hello1496941142093

My firebase tree

My code is the same as above.

How can I check my recent posts first?

How Do I order reverse of firebase database?


问:
How to disable copy paste option from UITextField programmatically
I am making a registration alertview that has a UITextField in it where the user can enter their registration number. everything is pretty much their, however I would like to remove the copy paste function from the textfield programmatically since their is no InterfaceBuilder version of the textfield I have no idea how to do this..

here Is my UIalertview thus far...

```<code>- (void)pleaseRegisterDevice {

    UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Please Register Device!" message:@"this gets covered" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
    regTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 45.0, 260.0, 25.0)];
    [regTextField setBackgroundColor:[UIColor whiteColor]];
    regTextField.textAlignment = UITextAlignmentCenter;
    [myAlertView addSubview:regTextField];
    [myAlertView show];
    [myAlertView release];

}
</code>```

答:
If disabled text selection works for you, try this.</p>

```<code>class NoMoreSelectionTextField: UITextField {

    override func caretRect(for position: UITextPosition) -> CGRect {
        return CGRect.zero
    }

    override var selectedTextRange: UITextRange? {
        get { return nil }
        set { return }
    }
}
</code>```

Body:
I am making a registration alertview that has a UITextField in it where the user can enter their registration number. everything is pretty much their, however I would like to remove the copy paste function from the textfield programmatically since their is no InterfaceBuilder version of the textfield I have no idea how to do this..

here Is my UIalertview thus far...

- (void)pleaseRegisterDevice {

    UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Please Register Device!" message:@"this gets covered" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
    regTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 45.0, 260.0, 25.0)];
    [regTextField setBackgroundColor:[UIColor whiteColor]];
    regTextField.textAlignment = UITextAlignmentCenter;
    [myAlertView addSubview:regTextField];
    [myAlertView show];
    [myAlertView release];

}

Body:
If disabled text selection works for you, try this.

class NoMoreSelectionTextField: UITextField {

    override func caretRect(for position: UITextPosition) -> CGRect {
        return CGRect.zero
    }

    override var selectedTextRange: UITextRange? {
        get { return nil }
        set { return }
    }
}


问:
How to catch/throw exception using PowerMockito
I am writing  JUnit test case for a method which doesn't throw exception but this method invokes parse() method which throws ParseException and I need to catch it. I have created one test case where I am passing invalid date format and during debugging it goes in the parse method and then to the catch block but how can I explicitly throw ParseException in a test case and then compare the String in the log. Hope I am clear.

Method under test.

```<code>public static String convertUTC( String strDate, String inputFormat, String outputFormat ) {
    String displayDateString = null;

    try {
        DateFormat inFormat = new SimpleDateFormat( inputFormat );
        inFormat.setTimeZone( TimeZone.getTimeZone( "UTC" ) );
        Date date = inFormat.parse( strDate );

        DateFormat outFormat = new SimpleDateFormat( outputFormat );
        outFormat.setTimeZone( TimeZone.getDefault() );

        displayDateString = formatDate(date, outputFormat);
    } catch ( ParseException pe ) {
        log.error( "DateUtil.convertUTC :Parse exception while parsing,"+strDate+" using format :"+inputFormat) ;
    }

    return displayDateString;
}
</code>```

JUnit

```<code>@Test
public void testConvertUTCParseException() {
    String incomingDate = "2012-08-15T22:56:02.038Z";
    String inputFormat = "MM/dd/yy hh:mm a z";
    String outputFormat = "MM/dd/yy hh:mm a z";

    assertEquals( null, DateUtils.convertUTC( incomingDate, inputFormat, outputFormat ) );
}
</code>```

Apart from the above test case I want to explicitly throw ParseException using PowerMockito and do the assert in the log to compare the text. The reason I cannot do it is because converUTC doesn't throw ParseException.

I assume this throws exception but how can I compare the text in the log?

```<code>@SuppressWarnings("unchecked")
@Test
public void testCaughtParseException() throws Exception {
    PowerMockito.mockStatic( DateUtils.class );
    PowerMockito.when( DateUtils.convertUTC( Mockito.any( String.class ), Mockito.any( String.class ), Mockito.any( String.class ) ) ).thenThrow( ParseException.class );
}
</code>```

Thanks.

答:
Honestly speaking your test case

```<code>public void testCaughtParseException() throws Exception
</code>```

doesn't make much sense here, as we are already have a try and catch here.
If you throws a parseException from the method then it makes sense to write a test case like this.
In your situation what I would like to do is check if the log.error is getting called in case of incorrect date.

So, I suggest you to use verify of the Mockito.
That would be good enough for your test case.

Body:
I am writing  JUnit test case for a method which doesn't throw exception but this method invokes parse() method which throws ParseException and I need to catch it. I have created one test case where I am passing invalid date format and during debugging it goes in the parse method and then to the catch block but how can I explicitly throw ParseException in a test case and then compare the String in the log. Hope I am clear.

Method under test.

public static String convertUTC( String strDate, String inputFormat, String outputFormat ) {
    String displayDateString = null;

    try {
        DateFormat inFormat = new SimpleDateFormat( inputFormat );
        inFormat.setTimeZone( TimeZone.getTimeZone( "UTC" ) );
        Date date = inFormat.parse( strDate );

        DateFormat outFormat = new SimpleDateFormat( outputFormat );
        outFormat.setTimeZone( TimeZone.getDefault() );

        displayDateString = formatDate(date, outputFormat);
    } catch ( ParseException pe ) {
        log.error( "DateUtil.convertUTC :Parse exception while parsing,"+strDate+" using format :"+inputFormat) ;
    }

    return displayDateString;
}

JUnit

@Test
public void testConvertUTCParseException() {
    String incomingDate = "2012-08-15T22:56:02.038Z";
    String inputFormat = "MM/dd/yy hh:mm a z";
    String outputFormat = "MM/dd/yy hh:mm a z";

    assertEquals( null, DateUtils.convertUTC( incomingDate, inputFormat, outputFormat ) );
}

Apart from the above test case I want to explicitly throw ParseException using PowerMockito and do the assert in the log to compare the text. The reason I cannot do it is because converUTC doesn't throw ParseException.

I assume this throws exception but how can I compare the text in the log?

@SuppressWarnings("unchecked")
@Test
public void testCaughtParseException() throws Exception {
    PowerMockito.mockStatic( DateUtils.class );
    PowerMockito.when( DateUtils.convertUTC( Mockito.any( String.class ), Mockito.any( String.class ), Mockito.any( String.class ) ) ).thenThrow( ParseException.class );
}

Thanks.

Body:
Honestly speaking your test case

public void testCaughtParseException() throws Exception

doesn't make much sense here, as we are already have a try and catch here.
If you throws a parseException from the method then it makes sense to write a test case like this.
In your situation what I would like to do is check if the log.error is getting called in case of incorrect date.

So, I suggest you to use verify of the Mockito.
That would be good enough for your test case.


问:
Binary Trees -- Tracing through code
Given the binary tree shown below, determine the order in which the nodes of the binary tree shown below are visited assuming the function A(root) is invoked.  Assume that the tree nodes and pointers are defined as shown.  Assume that root is a pointer to the node containing 60.
My answer to this problem is given below. Is it correct? What did I do wrong?

```<code>                                   60
                                 /    \
                                30     90
                               /  \   /
                              5   38  77
                               \  /  / \
                               8 32 62  88

struct treeNode{
  int data;
  struct treeNode *left, *right:
  {

struct treeNode *tree_ptr;

void A(struct treeNode *node_ptr){
    if (node_ptr != NULL){
    printf(“%d ,”,node_ptr->data);
    B(node_ptr->left);
    B(node_ptr->right);
   }
}

void B(struct treeNode *node_ptr){
    if (node_ptr != NULL) {
    A(node_ptr->left);
    printf(“%d ,”,node_ptr->data);
    A(node_ptr->right);
   }
 }
</code>```

Answer:
In void A it says to first print node_ptr-> data so 60 gets printed
Then the function calls B(node_ptr->left) then within B, A gets called (node_ptr->left) then you print that data which is 5. And then A(node_ptr->right) gets called go back up to A, print that data so 8 gets printed. Now Im not so sure what to do next but I get logically it would make sense to print 30 but Im not sure how the ptr gets from 8 to 30. And then if you continue in the same pattern 38 gets printed and 32 gets printed.
For the right subtree...
90 77 62 88

答:
Just write out the full execution stack over time. Like this:

```<code>A(60)
  printf
  B(30)
    A(5)
      ...
    printf
    A(38)
      ...
  B(90)
    ...
</code>```

(The remainder of the tree left as an exercise to the reader.)

Then just go from top to bottom, writing down the results of the printf statements.

Title: Binary Trees -- Tracing through code

Body:
Given the binary tree shown below, determine the order in which the nodes of the binary tree shown below are visited assuming the function A(root) is invoked.  Assume that the tree nodes and pointers are defined as shown.  Assume that root is a pointer to the node containing 60.
My answer to this problem is given below. Is it correct? What did I do wrong?

                                   60
                                 /    \
                                30     90
                               /  \   /
                              5   38  77
                               \  /  / \
                               8 32 62  88

struct treeNode{
  int data;
  struct treeNode *left, *right:
  {

struct treeNode *tree_ptr;

void A(struct treeNode *node_ptr){
    if (node_ptr != NULL){
    printf(“%d ,”,node_ptr->data);
    B(node_ptr->left);
    B(node_ptr->right);
   }
}

void B(struct treeNode *node_ptr){
    if (node_ptr != NULL) {
    A(node_ptr->left);
    printf(“%d ,”,node_ptr->data);
    A(node_ptr->right);
   }
 }

Answer:
In void A it says to first print node_ptr-> data so 60 gets printed
Then the function calls B(node_ptr->left) then within B, A gets called (node_ptr->left) then you print that data which is 5. And then A(node_ptr->right) gets called go back up to A, print that data so 8 gets printed. Now Im not so sure what to do next but I get logically it would make sense to print 30 but Im not sure how the ptr gets from 8 to 30. And then if you continue in the same pattern 38 gets printed and 32 gets printed.
For the right subtree...
90 77 62 88

Body:
Just write out the full execution stack over time. Like this:

A(60)
  printf
  B(30)
    A(5)
      ...
    printf
    A(38)
      ...
  B(90)
    ...

(The remainder of the tree left as an exercise to the reader.)

Then just go from top to bottom, writing down the results of the printf statements.


问:
Unable to start DSE Graph on reset Cassandra
I am testing DSE Graph (using DSE 5.0.7) a on a single node and managed to corrupt it completely.  As a result I wiped out all the data files with the intention of rebuilding everything from scratch.  On the first restart of Cassandra I forgot to include the -G option but Cassandra came up fine and was viewable from Opscenter, nodetool etc.  I shut this down, and cleared out the data directories and restarted Cassandra again, this time with the -G option.  It starts up and then shuts itself down with the following warning written to the log:

WARN  [main] 2017-06-08 12:59:03,157  NoSpamLogger.java:97 - Failed to create lease HadoopJT.Graph.  Possible causes include network/C* issues, the lease being disabled, insufficient replication (you created a new DC and didn't ALTER KEYSPACE dse_leases) and the duration (30000) being different (you have to disable/delete/recreate the lease to change the duration).
  java.io.IOException: No live replicas for lease HadoopJT.Graph in table dse_leases.leases Nodes [/10.28.98.53] are all down/still starting.
          at com.datastax.bdp.leasemanager.LeasePlugin.getRemoteMonitor(LeasePlugin.java:538) [dse-core-5.0.7.jar:5.0.7]

After this is the error

ERROR [main] 2017-06-08 12:59:03,182  Configuration.java:2646 - error parsing conf dse-core-default.xml
  org.xml.sax.SAXParseException: Premature end of file.

with a 0 byte dse-core-default.xml being created.  Deleting this and retrying yields the same results so I suspect this is a red herring.

Anyone have any idea how to fix this short of reinstalling everything from scratch?

答: Looks like this might be fixed by removing a very large java_pidnnnnn.hprof file that was sitting in the bin directory.  Not sure why this fixed the problem, if anyone has any idea?</p>


问:
AngularCli not loads image
Just a simple question:

I have an Angular2 application, I serve it using ng serve and the application are properly rendered.

The problem is this:

The css are loaded properly but the image no.

For example, if I put a css file and an image file in the same folder and I try to access them by direct link like these:

css

http://localhost:4200/assets/distAdminLte2/css/AdminLTE.min.css

image

http://localhost:4200/assets/distAdminLte2/css/mosconi.jpg

The css is rendered but the image is not rendered...

How to solve this problem?

Thanks

答:
You need to add your image path in .angular-cli.json.</p>

```<code>"assets":[
   "img/img.png"]
</code>```

Title: AngularCli not loads image

Body:
You need to add your image path in .angular-cli.json.

"assets":[
   "img/img.png"]


问:
CRLF parsing blues in C#
I have the following code:

```<code>  string myTest = "Line1Test" + Environment.NewLine +
                  "Line2Test" + Environment.NewLine +
                  "Line3Test" + Environment.NewLine;
  string[] parseStr = myTest.Split(Environment.NewLine.ToCharArray());
</code>```

What I'm getting is data every other line in the new array.  I think this is because the split line is splitting for both line feeds and carriage returns, but how can I just get one element per line?

答:
You may want to specify StringSplitOptions.RemoveEmptyEntries to, well, remove empty entries.

```<code>string[] parseStr = myTest.Split(Environment.NewLine.ToCharArray(),
                                 StringSplitOptions.RemoveEmptyEntries);
</code>```

Title: CRLF parsing blues in C#

Body:
I have the following code:

  string myTest = "Line1Test" + Environment.NewLine +
                  "Line2Test" + Environment.NewLine +
                  "Line3Test" + Environment.NewLine;
  string[] parseStr = myTest.Split(Environment.NewLine.ToCharArray());

What I'm getting is data every other line in the new array.  I think this is because the split line is splitting for both line feeds and carriage returns, but how can I just get one element per line?

Body:
You may want to specify StringSplitOptions.RemoveEmptyEntries to, well, remove empty entries.

string[] parseStr = myTest.Split(Environment.NewLine.ToCharArray(),
                                 StringSplitOptions.RemoveEmptyEntries);


问:
Pattern matching using information from theorems
I have the following question, look in the code.

```<code>  (* Suppose we have type A *)
  Variable A: Type.

  (* Also we have a function that returns the type (option A) *)
  Definition f_opt x: option A := ...

  (* Then, I can prove that this function always returns something: *)
  Theorem always_some: forall x, exists y, f_opt x = Some y.
  Admitted.

  (* Or, equivalently: *)
  Theorem always_not_none: forall x, f_opt x <> None.
  Admitted.
</code>```

Now I would like to get a version of f_opt that always returns a value of type A. Something like this:

```<code>  Definition f x: A :=
    match f_opt x with
      | Some y => y
    end.
</code>```

But I get the following error:

Non exhaustive pattern-matching: no clause found for pattern None.

I understand that I need to do some kind of work with types, but I do not understand what exactly i should do.

答:
Using Coq's Program module, you can write an exhaustive pattern match, but annotate that some branches should be impossible to reach and then later provide the proof that this is the case:

```<code>Require Import Program.
Program Definition f x : A :=
match f_opt x with
| Some a => a
| None => !
end.
Next Obligation.
destruct (always_some x). congruence.
Qed.
</code>```

(The Program module does a lot of the work behind the scenes that in a complete explicit definition you would have to write using the "convoy pattern".  Do be aware, however, that sometimes Program tends to generate lots of dependencies on JMeq and the axiom JMeq_eq when dependent types are involved, even when it might not be necessary.)

Body:
I have the following question, look in the code.

  (* Suppose we have type A *)
  Variable A: Type.

  (* Also we have a function that returns the type (option A) *)
  Definition f_opt x: option A := ...

  (* Then, I can prove that this function always returns something: *)
  Theorem always_some: forall x, exists y, f_opt x = Some y.
  Admitted.

  (* Or, equivalently: *)
  Theorem always_not_none: forall x, f_opt x <> None.
  Admitted.

Now I would like to get a version of f_opt that always returns a value of type A. Something like this:

  Definition f x: A :=
    match f_opt x with
      | Some y => y
    end.

But I get the following error:

Non exhaustive pattern-matching: no clause found for pattern None.

I understand that I need to do some kind of work with types, but I do not understand what exactly i should do.

Body:
Using Coq's Program module, you can write an exhaustive pattern match, but annotate that some branches should be impossible to reach and then later provide the proof that this is the case:

Require Import Program.
Program Definition f x : A :=
match f_opt x with
| Some a => a
| None => !
end.
Next Obligation.
destruct (always_some x). congruence.
Qed.

(The Program module does a lot of the work behind the scenes that in a complete explicit definition you would have to write using the "convoy pattern".  Do be aware, however, that sometimes Program tends to generate lots of dependencies on JMeq and the axiom JMeq_eq when dependent types are involved, even when it might not be necessary.)


问:
Function call from aspx design time error "name does not exist in the current context"
I want to change the styles of certain elements on my page depending on the role of the logged in user.

To achieve this, I'm calling a function to execute some server code that does the evaluation and returns a string being the name of the style rule:

```<code><li class="<%=CheckAllowed("admin"); %>">
</code>```

In my code file I have the following:

```<code>public string CheckAllowed(string role)
{
    if (HttpContext.Current.User.IsRole(role))
    {
        return "visible-menu-item";
    }
    else
    {
        return "hidden-menu-item";
    }
}
</code>```

The function name in the markup is underlined red with the following error:

The name 'CheckAllowed' does not exist in the current context.

Am I calling the function correctly? If not, how would this be done correctly?

答:
From the use of HttpContext.Current in the method, it looks like it is located in a separate class than the page you are using it on. So provide the full namespace.

```<code><%= Project1.ClassName.CheckAllowed("admin") %>
</code>```

You probably need to make it a static class to work. But the intellisense should tell you that.

And it's IsInRole not IsRole

Body:
I want to change the styles of certain elements on my page depending on the role of the logged in user.

To achieve this, I'm calling a function to execute some server code that does the evaluation and returns a string being the name of the style rule:

<li class="<%=CheckAllowed("admin"); %>">

In my code file I have the following:

public string CheckAllowed(string role)
{
    if (HttpContext.Current.User.IsRole(role))
    {
        return "visible-menu-item";
    }
    else
    {
        return "hidden-menu-item";
    }
}

The function name in the markup is underlined red with the following error:

The name 'CheckAllowed' does not exist in the current context.

Am I calling the function correctly? If not, how would this be done correctly?

Body:
From the use of HttpContext.Current in the method, it looks like it is located in a separate class than the page you are using it on. So provide the full namespace.

<%= Project1.ClassName.CheckAllowed("admin") %>

You probably need to make it a static class to work. But the intellisense should tell you that.

And it's IsInRole not IsRole


问:
JobDispatcher.cancel() is not calling onStopJob()
I have used FirebaseJobDispatcher in my project. This is the sample code.

```<code>public class MyCustomDispatcher extends JobService {
    @Override
    public boolean onStartJob(JobParameters job) {
        Log.e("MyCustomDispatcher", "onStartJob() called with: " + "job = [" + job.getTag() + "]");

        return false;
    }

    @Override
    public boolean onStopJob(JobParameters job) {
        Log.e("MyCustomDispatcher", "onStopJob() called with: " + "job = [" + job + "]");
        return false;
    }
}
</code>```

And to start my job i have done simple thing in my activity.

```<code>FirebaseJobDispatcher firebaseJobDispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
Job myJob = firebaseJobDispatcher.newJobBuilder()
            .setService(MyCustomDispatcher.class)
            .setTag("service")
            .setRecurring(false)
            .setTrigger(Trigger.executionWindow(0,10))
            .setConstraints(Constraint.ON_ANY_NETWORK)
            .build();

firebaseJobDispatcher.mustSchedule(myJob);
</code>```

It is starting my service and onStartJob() is being called whenever i schedule my job.

Only problem is when i use firebaseJobDispatcher.cancel("service");, it is not calling onStopJob().

Is it the actual behavior or is there anything that i am missing?

答: I believe onStopJob() is only called when your job is stopped before it has completed whatever onStartJob() is trying to do.</p>

Body:
I have used FirebaseJobDispatcher in my project. This is the sample code.

public class MyCustomDispatcher extends JobService {
    @Override
    public boolean onStartJob(JobParameters job) {
        Log.e("MyCustomDispatcher", "onStartJob() called with: " + "job = [" + job.getTag() + "]");

        return false;
    }

    @Override
    public boolean onStopJob(JobParameters job) {
        Log.e("MyCustomDispatcher", "onStopJob() called with: " + "job = [" + job + "]");
        return false;
    }
}

And to start my job i have done simple thing in my activity.

FirebaseJobDispatcher firebaseJobDispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
Job myJob = firebaseJobDispatcher.newJobBuilder()
            .setService(MyCustomDispatcher.class)
            .setTag("service")
            .setRecurring(false)
            .setTrigger(Trigger.executionWindow(0,10))
            .setConstraints(Constraint.ON_ANY_NETWORK)
            .build();

firebaseJobDispatcher.mustSchedule(myJob);

It is starting my service and onStartJob() is being called whenever i schedule my job.

Only problem is when i use firebaseJobDispatcher.cancel("service");, it is not calling onStopJob().

Is it the actual behavior or is there anything that i am missing?


问:
How to mask URL for a C# MVC site with multiple tenant sub-domains
I have a .NET MVC site with multiple tenants all with their own sub-domains. And I'm trying to mask the controller location for a certain subset of those tenants as they're segmented to an area of the site.

For example I want subdomain.domain.com to point to /Controller/View without the extra stuff on the end of the domain.

More specifically,

http://subdomain.domain.com/Controller/View

Becomes:

http://subdomain.domain.com

What's the best way to accomplish this? In the Web.config?

答:
you can use this in global.asax to remove controller and view part from url.

```<code>routes.MapRoute("SpecificRoute", "/{id}", new {controller = "YourController", action = "YourAction", id = UrlParameter.Optional});

// default route
routes.MapRoute("Default", "{controller}/{action}/{id}", new {controller = "Home", action = "Index", id = UrlParameter.Optional} );
</code>```

Also you can use Route() over your action

```<code>[Route("")]
public ActionResult YourAction()
{
...
}
</code>```

Url will be like http://example.com/

Body:
you can use this in global.asax to remove controller and view part from url.

routes.MapRoute("SpecificRoute", "/{id}", new {controller = "YourController", action = "YourAction", id = UrlParameter.Optional});

// default route
routes.MapRoute("Default", "{controller}/{action}/{id}", new {controller = "Home", action = "Index", id = UrlParameter.Optional} );

Also you can use Route() over your action

[Route("")]
public ActionResult YourAction()
{
...
}

Url will be like http://example.com/


问:
Can AWS redirect HTTP to HTTPS?

Background

I am serving an application on AWS using Route53 + LoadBalancer + EC2.

I want to force all users to use https. Whenever a request is made on http, I want it redirected to a https request.

Potential Solutions

I know of three ways to redirect HTTP to HTTPS:

Client side. This involves using JS to check if the host is http or https, and redirecting if it's https.

Server Side. This involves configuring the webserver to redirect all http requests to https.

However, I'm curious: can this be done at the Route53 or LoadBalancer stage?

Question

Is there some way to configure Route53 or LoadBalancer so that any requests on http are redirected to https?

Thanks!

Edit

For downvoters: please explain why you are down voting. The solutions I have found on SO / Google are "how do do redirection via server, which is option 2. I'm trying to solve this at the AWS layer."

答:
There is no point in doing 'client side redirect'. By the time the JS runs and does the redirect, is way too late. The request response content has already leaked all over the net. You must do it at the server side, respond with a 301 status and Location header, and no content. This can and should be done by your Web server stack (nginx, Apache) before hitting your app (php, node, etc).

ELB does not support redirect. It supports SSL/TLS offloading by forwarding the HTTPS traffic to HTTP target group and adding the X-Forwarded-proto headers, see How do I redirect HTTP traffic on my server to HTTPS on my load balancer?. But redirect must be handled by your back end server.

Latest Update:
AWS announces support for Redirects and Fixed Responses for Application Load Balancer with two new actions: redirect and fixed-response. This way you can configure the HTTP to HTTPS redirection at the Load Balancer Level.

Title: Can AWS redirect HTTP to HTTPS?


问:
Advanced D3 transition sequencing; inheriting delay/duration from transitions over different selections
I have ranking data for the top n employees that I'd like to use to drive a visualization. I know that because the number of employees, n, that are displayed will never change, if I update the data join using a composite (employee + rank) key function, the enter and exit selections should always contain the same number of elements and I should receive an exiting/entering employee pair everytime an employee's rank changes.

Now I'm trying to animate the exiting and entering of elements. Using the technique described by Mr. Bostock in d3: How to properly chain transitions on different selections I can chain two transitions and apply the first to the exiting selection and the second to the entering selection to sequence transitions on different selections.

The problem comes when I try to embellish the exit transition with sub-transitions (e.g. turning the exiting transition into a two-part, chained transition composed of a text tween and then background transition). As the enter transition doesn't know about the number of sub-transitions (nor the delay/duration) in the exit transition, I have to manually compute the enter transition delay/duration. Furthermore, I either have to calculate from the data how long the delay/duration of the sub-transitions are or have to assume the longest delay/duration possible for every transition on every element in the exiting selection (e.g. I have to assume the sub-transition to tween the text for every employee is tweening the longest possible employee name).

Is there some way, since I have the same number of exiting and entering elements, to chain transitions like they were on the same elements? I.e. with the same selection I can chain transitions such that subsequent transitions inherit delay/duration, can I do this with disparate selections of the same size? Basically, how can I write the following without having to estimate delay/duration?

function chart() {
  var scale = d3.scale.ordinal().rangeBands([0, 150], .5);
  return function(selection) {
    selection.each(function(data) {
      scale.domain(data);
      var svg = d3.select(this).selectAll('svg').data([data]);
      var svgEnter = svg.enter().append('svg');
        var g = svg.selectAll('g').data(function(d) {
          return d;
        }, function(d, i) {
          return d + i;
        }).attr('class', 'update');
       var gExit = g.exit();
        var gEnter = g.enter().append('g').attr('class', 'enter').attr('transform', function(d) {
          return 'translate(150 ' + scale(d) + ')';
        });
        g.order();
        var gExitTransition = d3.transition().each(function() {
          var t0 = gExit.transition().delay(function(_, i) {
            return i * 100;
          }).duration(function(d) {
            return d.length * 250 / 5;
          });
          var t1 = t0.transition();
          var t2 = t1.transition();
          t0.select('text').tween('text', function(d) {
            var i = d3.interpolate(this.textContent.length, 0);
            return function(t) {
              this.textContent = d.slice(0, i(t));
            };
          });
          t1.select('rect').attr('y', scale.rangeBand() / 2).attr('height', 1e-6);
          t2.remove();
        });
        var gEnterTransition = gExitTransition.transition().each(function() {
          var t0 = gEnter.transition().delay(function(_, i) {
            return i * 100 + 500;
          });
          var t1 = t0.transition().duration(function(d) {
            return d.length * 250 / 5;
          });
            var rectEnter = gEnter.append('rect').attr('y', scale.rangeBand() / 2).attr('width', 50).attr('height', 1e-6).style('fill', 'rgba(0, 0, 0, .1)');
            t0.select('rect').attr('y', 0).attr('height', scale.rangeBand());
            var textEnter = gEnter.append('text').attr('y', scale.rangeBand() / 2).style('alignment-baseline', 'middle');
            t1.select('text').tween('text', function(d) {
              var i = d3.interpolate(this.textContent.length, d.length);
              return function(t) {
                this.textContent = d.slice(0, i(t));
              };
            });
        });
    });
  };
}
var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('').map(function(c) {
  return d3.range(Math.floor(5 * Math.random()) + 1).map(function() {
    return c;
  }).join('');
});
var myChart = chart();
var selection = d3.select('body');
(function(f) {
  f();
  setInterval(f, 3000);
})(function() {
  selection.datum(d3.shuffle(alphabet.slice(0)).slice(0, 10).sort()).call(myChart);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script></code>```

答:
I got a partial solution working by switching to v4 on Gerardo's advice; it works and avoids the need to calculate timing/duration across differing selections, but I basically wait for a start event from the transition on the first selection and then filter a transition on the second selection until the element indices are equal which feels really dumb.

function chart() {
  var scale = d3.scaleBand().range([0, 150]).padding(.5);
  return function(selection) {
    selection.each(function(data) {
      scale.domain(data);
      var svg = d3.select(this).selectAll('svg').data([data]);
      var svgEnter = svg.enter().append('svg');
      svg = svg.merge(svgEnter);
        var g = svg.selectAll('g').data(function(d) {
          return d;
        }, function(d, i) {
          return d + i;
        }).attr('class', 'update');
       var gExit = g.exit().attr('class', 'exit');
        var gEnter = g.enter().append('g').attr('class', 'enter').attr('transform', function(d) {
          return 'translate(150 ' + scale(d) + ')';
        });
        g = g.merge(gEnter).order();
          var rectEnter = gEnter.append('rect').attr('y', scale.bandwidth() / 2).attr('width', 50).attr('height', 1e-6).style('fill', 'rgba(0, 0, 0, .1)');
          var textEnter = gEnter.append('text').attr('y', scale.bandwidth() / 2).style('alignment-baseline', 'middle');
          var t0 = gExit.transition().delay(function(_, i) {
            return i * 100;
          });
          t0.select('text').duration(function(d) {
            return d.length * 250 / 5;
          }).tween('text', function(d) {
            var i = d3.interpolate(this.textContent.length, 0);
            return function(t) {
              this.textContent = d.slice(0, i(t));
            }.bind(this);
          });
          var t1 = t0.transition();
          t1.select('rect').attr('y', scale.bandwidth() / 2).attr('height', 1e-6);
          var t2 = t1.transition().on('start', function(d, i) {
            var t3 = gEnter.transition(d3.active(this)).filter(function(_, j) {
              return i === j;
            });
            t3.select('rect').attr('y', 0).attr('height', scale.bandwidth());
            var t4 = t3.transition();
            t4.select('text').duration(function(d) {
              return d.length * 250 / 5;
            }).tween('text', function(d) {
              var i = d3.interpolate(this.textContent.length, d.length);
              return function(t) {
                this.textContent = d.slice(0, i(t));
              }.bind(this);
            });
          });
          t2.remove();
    });
  };
}
var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('').map(function(c) {
  return d3.range(Math.floor(5 * Math.random()) + 1).map(function() {
    return c;
  }).join('');
});
var myChart = chart();
var selection = d3.select('body');
(function(f) {
  f();
  d3.interval(f, 3000);
})(function() {
  selection.datum(d3.shuffle(alphabet.slice(0)).slice(0, 10).sort()).call(myChart);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.9.1/d3.min.js"></script></code>```

Body:
I got a partial solution working by switching to v4 on Gerardo's advice; it works and avoids the need to calculate timing/duration across differing selections, but I basically wait for a start event from the transition on the first selection and then filter a transition on the second selection until the element indices are equal which feels really dumb.

function chart() {
  var scale = d3.scaleBand().range([0, 150]).padding(.5);
  return function(selection) {
    selection.each(function(data) {
      scale.domain(data);
      var svg = d3.select(this).selectAll('svg').data([data]);
      var svgEnter = svg.enter().append('svg');
      svg = svg.merge(svgEnter);
        var g = svg.selectAll('g').data(function(d) {
          return d;
        }, function(d, i) {
          return d + i;
        }).attr('class', 'update');
       var gExit = g.exit().attr('class', 'exit');
        var gEnter = g.enter().append('g').attr('class', 'enter').attr('transform', function(d) {
          return 'translate(150 ' + scale(d) + ')';
        });
        g = g.merge(gEnter).order();
          var rectEnter = gEnter.append('rect').attr('y', scale.bandwidth() / 2).attr('width', 50).attr('height', 1e-6).style('fill', 'rgba(0, 0, 0, .1)');
          var textEnter = gEnter.append('text').attr('y', scale.bandwidth() / 2).style('alignment-baseline', 'middle');
          var t0 = gExit.transition().delay(function(_, i) {
            return i * 100;
          });
          t0.select('text').duration(function(d) {
            return d.length * 250 / 5;
          }).tween('text', function(d) {
            var i = d3.interpolate(this.textContent.length, 0);
            return function(t) {
              this.textContent = d.slice(0, i(t));
            }.bind(this);
          });
          var t1 = t0.transition();
          t1.select('rect').attr('y', scale.bandwidth() / 2).attr('height', 1e-6);
          var t2 = t1.transition().on('start', function(d, i) {
            var t3 = gEnter.transition(d3.active(this)).filter(function(_, j) {
              return i === j;
            });
            t3.select('rect').attr('y', 0).attr('height', scale.bandwidth());
            var t4 = t3.transition();
            t4.select('text').duration(function(d) {
              return d.length * 250 / 5;
            }).tween('text', function(d) {
              var i = d3.interpolate(this.textContent.length, d.length);
              return function(t) {
                this.textContent = d.slice(0, i(t));
              }.bind(this);
            });
          });
          t2.remove();
    });
  };
}
var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('').map(function(c) {
  return d3.range(Math.floor(5 * Math.random()) + 1).map(function() {
    return c;
  }).join('');
});
var myChart = chart();
var selection = d3.select('body');
(function(f) {
  f();
  d3.interval(f, 3000);
})(function() {
  selection.datum(d3.shuffle(alphabet.slice(0)).slice(0, 10).sort()).call(myChart);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.9.1/d3.min.js"></script>


问:
MVC Dynamic Partial View Data Disappearing In IE7
I'm having problems with dynamic partial view data disappearing from the textbox after a httppost. Here is my scenario:

The user clicks a radio button, and the coapplicant partial view is loaded dynamically.

Index.aspx (Embedded Javascript):

```<code>function showCoApplicant() {
 $.ajax({
  type: "GET",
  url: '<%= Url.Action("LoadCoApplicantInfo","Application") %>',
  data: {},
  dataType: "html",
  async: true,
  success: function (data) {
   $("#CoApplicantInfo").html(data);
  }
 }); }
</code>```

ApplicationController.cs:

```<code>public ActionResult LoadCoApplicantInfo() {
 Configurator.Models.CreditApplicationModel model = null;
 if (Session["model"] != null)
  model = (Configurator.Models.CreditApplicationModel)Session["model"];

 return PartialView("CoApplicant", model);
}
</code>```

CoApplicant.ascx:

```<code><table>
 <tr>
  <th>
   <%= Html.LabelFor(model => model.CoApplicant.FirstName)%>
  </th>
  <td>
   <%= Html.TextBoxFor(model => model.CoApplicant.FirstName)%>
   <%= Html.ValidationMessageFor(model => model.CoApplicant.FirstName)%>
  </td>
 </tr>
</table>
</code>```

The user enters in data, and clicks the submit button. The model is then validated in the controller. If the ModelState is invalid, I return the view along with the model in session (I do this because I need to return that model to the partial view. This was the only way I could get the data back to it.). On httppost, in Javascript, I determine if the coapplicant partial view should be showing, and if so, I load it again by calling showCoApplicant().

```<code>[HttpPost]
 public ActionResult Index(Configurator.Models.CreditApplicationModel model)
 {
 if (!ModelState.IsValid)
 {
  Session["model"] = model;
        return View();
 }
 }
</code>```

This is where I have the problem. The data for the coapplicant is missing in IE7. It works fine in other versions of IE, Chrome, and Firefox. Why is the data missing in IE7? How can I get it to show?

答: More than likely, you have some goofy HTML being generated.  Because you're using ajax, you can't just run it against the w3c validator to find out, but maybe you can figure out a way to post the generated data in the view without ajax so you can view it, or validate it.</p>

Body:
I'm having problems with dynamic partial view data disappearing from the textbox after a httppost. Here is my scenario:

The user clicks a radio button, and the coapplicant partial view is loaded dynamically.

Index.aspx (Embedded Javascript):

function showCoApplicant() {
 $.ajax({
  type: "GET",
  url: '<%= Url.Action("LoadCoApplicantInfo","Application") %>',
  data: {},
  dataType: "html",
  async: true,
  success: function (data) {
   $("#CoApplicantInfo").html(data);
  }
 }); }

ApplicationController.cs:

public ActionResult LoadCoApplicantInfo() {
 Configurator.Models.CreditApplicationModel model = null;
 if (Session["model"] != null)
  model = (Configurator.Models.CreditApplicationModel)Session["model"];

 return PartialView("CoApplicant", model);
}

CoApplicant.ascx:

   <%= Html.LabelFor(model => model.CoApplicant.FirstName)%>

   <%= Html.TextBoxFor(model => model.CoApplicant.FirstName)%>
   <%= Html.ValidationMessageFor(model => model.CoApplicant.FirstName)%>

The user enters in data, and clicks the submit button. The model is then validated in the controller. If the ModelState is invalid, I return the view along with the model in session (I do this because I need to return that model to the partial view. This was the only way I could get the data back to it.). On httppost, in Javascript, I determine if the coapplicant partial view should be showing, and if so, I load it again by calling showCoApplicant().

[HttpPost]
 public ActionResult Index(Configurator.Models.CreditApplicationModel model)
 {
 if (!ModelState.IsValid)
 {
  Session["model"] = model;
        return View();
 }
 }

This is where I have the problem. The data for the coapplicant is missing in IE7. It works fine in other versions of IE, Chrome, and Firefox. Why is the data missing in IE7? How can I get it to show?


问:
Crystal Reports - Can I reference a field/value from my sub-report in my main report?
I'm building a delivery note for our company. In the main report I have one SQL query, and in the sub-report, I have the order at line level (items ordered, quantity and price).

I've populated a running total of the quantities*items to give me a 'sub-total' field.

What I want to be able to do though, in my main report is formulate a 'grand total' in my main report, which takes postage and discounts away from the sub total in the sub report.

I'm not sure if there's an easy way to do this though? I obviously can't see that value in my main report.

答:
You can use a shared variable in both subreport and main report.

Create a formula in the subreport:

```<code>shared numbervar total;
total := {#YourRunningTotalField};
</code>```

Put the formula where the value is "ready". Maybe the subreport footer section.

Create a formula in the main report:

```<code>shared numbervar total;
total;
</code>```

Put this formula somewhere after the subreport.

It would work in some scenarios, give it a try.

Body:
You can use a shared variable in both subreport and main report.

Create a formula in the subreport:

shared numbervar total;
total := {#YourRunningTotalField};

Put the formula where the value is "ready". Maybe the subreport footer section.

Create a formula in the main report:

shared numbervar total;
total;

Put this formula somewhere after the subreport.

It would work in some scenarios, give it a try.


问:
Tkinter skips over part of the code detailing the reaction to an input - Python
I am creating a program that judges the strength of passwords. Part of the code is supposed to check whether a password has any numbers. However, when I enter a password, it completely neglects the code detailing what to print as the output if there are no numbers, and instead returns with: 'this is too short.'

```<code>from tkinter import *

import re

def pass_Type():
  strength = pass_Type  #Applies pass_Type to the entire program

def value():
  value

def click():
    entered_text = entry.get()
    if entered_text in pass_Type:
        strength = pass_Type[entered_text]
        output.delete(0.0, END)
        output.insert(END, strength)
         #Click function
    elif len(entered_text) < 9:
        output.delete(0.0, END)
        output.insert(END, 'This is too short')
    elif pass_Type and len(entered_text) < 9:
       output.delete(0.0, END)
       output.insert(END, strength)
    elif value(entered_text):                              }
        if not any(c.isdigit() for c in value):            }
          output.delete(0.0, END)                          }
          output.insert(END, 'Incorporate some numbers')   } #The problematic area
    elif value(entered_text) and len(entered_text)  < 9:   }
        if not any(c.isdigit() for c in value):            }
          output.delete(0.0, END)
          output.insert(END, 'Try to incorporate some numbers and increase the length of your password')
    else:
        output.delete(0.0, END)
        output.insert(END, "This password is acceptable!") #When the password is ok

Password = Tk()
Password.title('Password tester')

label = Label(Password, text="Password:")
label.grid(row=0, column=0, sticky=W)    #Entry label

entry = Entry(width=20, bg='light blue')
entry.grid(row=1, column=0, sticky=W)     #Entry box

Button(Password, text='SUBMIT',width=5, command=click).grid(row=2,column=0, sticky=W)  #Button

label = Label(Password, text='Strength:')
label.grid(row=4, column=0, sticky=W)          #Output label

output = Text(Password, width=75, height=6, wrap=WORD, background='light blue')
output.grid(row=5, column=0, columnspan=2, sticky=W)                              #Output box

pass_Type = {
  'Password': 'This is a very predicatable password. You should incorporate numbers',
  'password': 'This is a very predicatable password. You should incorporate numbers and capital letters',  #Common password glossary
  '12345': 'Try and incorporate some letters',
  'qwerty': 'Try to jumble up your letters so the password is not so predictable.'
  }

Password.mainloop()
</code>```

When I attempt to test the code by itself by entering over 9 characters, it rejects the code with the following error:

```<code>Exception in Tkinter callback
Traceback (most recent call last):
  File "", line 1549, in __call__
    return self.func(*args)
  File "", line 25, in click
    elif value(entered_text):
TypeError: value() takes 0 positional arguments but 1 was given
</code>```

How can I make the program not skip over the aspect, and use the alternative output that I have programmed?
And if incorporating numbers was the only problem, how can I fix the error?

答:
Look at the function you defined:

```<code>def value():
   value
</code>```

As the error message says it takes no positional arguments despite you passing them in from your condition(s).

Moreover, even if you fixhed that what is value it's not defined? At this point it's just referencing the function.

It looks like your trying to test whether there was simply any text entered in which case you can just directly test the "truthiness" of the string since a blank string "" will equate to false.

Body:
I am creating a program that judges the strength of passwords. Part of the code is supposed to check whether a password has any numbers. However, when I enter a password, it completely neglects the code detailing what to print as the output if there are no numbers, and instead returns with: 'this is too short.'

from tkinter import *

import re

def pass_Type():
  strength = pass_Type  #Applies pass_Type to the entire program

def value():
  value

def click():
    entered_text = entry.get()
    if entered_text in pass_Type:
        strength = pass_Type[entered_text]
        output.delete(0.0, END)
        output.insert(END, strength)
         #Click function
    elif len(entered_text) < 9:
        output.delete(0.0, END)
        output.insert(END, 'This is too short')
    elif pass_Type and len(entered_text) < 9:
       output.delete(0.0, END)
       output.insert(END, strength)
    elif value(entered_text):                              }
        if not any(c.isdigit() for c in value):            }
          output.delete(0.0, END)                          }
          output.insert(END, 'Incorporate some numbers')   } #The problematic area
    elif value(entered_text) and len(entered_text)  < 9:   }
        if not any(c.isdigit() for c in value):            }
          output.delete(0.0, END)
          output.insert(END, 'Try to incorporate some numbers and increase the length of your password')
    else:
        output.delete(0.0, END)
        output.insert(END, "This password is acceptable!") #When the password is ok

Password = Tk()
Password.title('Password tester')

label = Label(Password, text="Password:")
label.grid(row=0, column=0, sticky=W)    #Entry label

entry = Entry(width=20, bg='light blue')
entry.grid(row=1, column=0, sticky=W)     #Entry box

Button(Password, text='SUBMIT',width=5, command=click).grid(row=2,column=0, sticky=W)  #Button

label = Label(Password, text='Strength:')
label.grid(row=4, column=0, sticky=W)          #Output label

output = Text(Password, width=75, height=6, wrap=WORD, background='light blue')
output.grid(row=5, column=0, columnspan=2, sticky=W)                              #Output box

pass_Type = {
  'Password': 'This is a very predicatable password. You should incorporate numbers',
  'password': 'This is a very predicatable password. You should incorporate numbers and capital letters',  #Common password glossary
  '12345': 'Try and incorporate some letters',
  'qwerty': 'Try to jumble up your letters so the password is not so predictable.'
  }

Password.mainloop()

When I attempt to test the code by itself by entering over 9 characters, it rejects the code with the following error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "", line 1549, in __call__
    return self.func(*args)
  File "", line 25, in click
    elif value(entered_text):
TypeError: value() takes 0 positional arguments but 1 was given

How can I make the program not skip over the aspect, and use the alternative output that I have programmed?
And if incorporating numbers was the only problem, how can I fix the error?

Body:
Look at the function you defined:

def value():
   value

As the error message says it takes no positional arguments despite you passing them in from your condition(s).

Moreover, even if you fixhed that what is value it's not defined? At this point it's just referencing the function.

It looks like your trying to test whether there was simply any text entered in which case you can just directly test the "truthiness" of the string since a blank string "" will equate to false.


问:
How to shape a nested struct into another without nested loops?
How can I inject A and B's selected values into children C below?

decoder.go (Playground link)

```<code>package main

import (
    "fmt"
)

type Input struct {
    A []A
}

type A struct {
    AID int
    B []B
}

type B struct {
    BID int
    C []C
}

type C struct {
    // I want to inject only AID and BID here
    // But, without injecting A and B directly
    //   (without recursively)
    CID int
}

func main() {
    res := Input{
        A: []A {
            A {
                AID: 1,
                B: []B {
                    B{ BID: 11, C: []C{{ 111 }, { 111 }}},
                    B{ BID: 12, C: []C{{ 121 }, { 122 }}},
                },
            },
            A {
                AID: 2,
                B: []B {
                    B{ BID: 21, C: []C{{ 211 }, { 211 }}},
                    B{ BID: 22, C: []C{{ 221 }, { 222 }}},
                },
            },
        },
    }

    // I want to inject AID and BID into C
    // WITHOUT nested loops like this:
    for _, a := range res.A {
        for _, b := range a.B {
            for _, c := range b.C {
                fmt.Println(a.AID, b.BID, c.CID)
            }
        }
    }
}
</code>```

答: Go generally encourages an explicit approach, and nested for loops are very explicit in terms of what is actually going on here. There's likely no need to try to find a more concise solution and Go likely won't offer it.</p>

Body:
How can I inject A and B's selected values into children C below?

decoder.go (Playground link)

package main

import (
    "fmt"
)

type Input struct {
    A []A
}

type A struct {
    AID int
    B []B
}

type B struct {
    BID int
    C []C
}

type C struct {
    // I want to inject only AID and BID here
    // But, without injecting A and B directly
    //   (without recursively)
    CID int
}

func main() {
    res := Input{
        A: []A {
            A {
                AID: 1,
                B: []B {
                    B{ BID: 11, C: []C{{ 111 }, { 111 }}},
                    B{ BID: 12, C: []C{{ 121 }, { 122 }}},
                },
            },
            A {
                AID: 2,
                B: []B {
                    B{ BID: 21, C: []C{{ 211 }, { 211 }}},
                    B{ BID: 22, C: []C{{ 221 }, { 222 }}},
                },
            },
        },
    }

    // I want to inject AID and BID into C
    // WITHOUT nested loops like this:
    for _, a := range res.A {
        for _, b := range a.B {
            for _, c := range b.C {
                fmt.Println(a.AID, b.BID, c.CID)
            }
        }
    }
}


问:
Data encapsulation and security in Swift
I'm currently studying iOS development in Swift and came across the concept of data encapsulation and security. Let's start with an example:

```<code>Class Person {
    private var _weight: Int!

    var weight: Int {
        get {
            return _weight
        }
        set {
            _weight = newValue
        }
    }
}
</code>```

In the tutorial, I was taught to always make a private var for the purpose of security so the variable cannot be excessed externally and mutate the data. And the instructor also emphasized to explicitly set the getter and setter like above. Writing getter and setter seems very cumbersome to me and it seems like I only need to utilize getter and setter when they are needed. (i.e. getter could be used for read-only property and setter could be used for the purpose of Computed Property).

I wonder if I need to follow this practice all the time or whether I can simply define the property like following:

```<code>Class Person {
    var _weight: Int!
}
</code>```

答:
Your prof is correct but for swift in my opinion you do not need to add _ to your variables to emphasize that they are private since we already have the "private
" opt in swift. The _ is for languages like python that you can't set specific identifiers like private to your variables and functions. Also, you do not need to need to write getters and setters if you are not manipulating it or if it does not have a specific condition/implication on it. Defining it like your bottom example is fine </p>

Body:
I'm currently studying iOS development in Swift and came across the concept of data encapsulation and security. Let's start with an example:

Class Person {
    private var _weight: Int!

    var weight: Int {
        get {
            return _weight
        }
        set {
            _weight = newValue
        }
    }
}

In the tutorial, I was taught to always make a private var for the purpose of security so the variable cannot be excessed externally and mutate the data. And the instructor also emphasized to explicitly set the getter and setter like above. Writing getter and setter seems very cumbersome to me and it seems like I only need to utilize getter and setter when they are needed. (i.e. getter could be used for read-only property and setter could be used for the purpose of Computed Property).

I wonder if I need to follow this practice all the time or whether I can simply define the property like following:

Class Person {
    var _weight: Int!
}