问:
Why Log4j2 is taking an extra of 11 Milli seconds to write into the file?
I am new to Log4j2. I have written a simple program that actually logs data into RollingRandomAccessFile using log4j2. Below is the program:

```<code>public class Log4j2Example {

/**
 * @param args the command line arguments
 */
public static Logger mlogger = null;

public static void main(String[] args) throws InterruptedException {

    mlogger = LogManager.getLogger("Messages-log");
    int i = 0;
    while (true) {
        String str = "Hello" + i;
        System.out.println(str);
        mlogger.info(str);
        i++;
        Thread.sleep(20);
    }
}
}
</code>```

My log4j2.xml file

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
  <Appenders>
     <RollingRandomAccessFile name="Messages-log" fileName="Log4J/Messages-${date:yyyy-MM-dd}.log"
               immediateflush="true" filePattern="Log4J/Messages-%d{MM-dd-yyyy-HH}-%i.log.gz">
      <PatternLayout>
        <Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %p %m%n</Pattern>
      </PatternLayout>
      <Policies>
        <TimeBasedTriggeringPolicy />
        <SizeBasedTriggeringPolicy size="500 MB"/>
      </Policies>
      <DefaultRolloverStrategy max="50"/>
    </RollingRandomAccessFile>
  </Appenders>
  <Loggers>
    <Logger name="Messages-log" level="info" additivity="false">
        <appender-ref ref="Messages-log" level="info"/>
      </Logger>
    <root level="info">
        <appender-ref ref="Messages-log"/>
    </root>
</Loggers>
</Configuration>
</code>```

I am writing a simple statement into the log file sleeping for 20 milli-seconds for every record. Now the time stamp in the file should be for example:
If the first statement is logged at 17:20:32:354 then the next statement should be logged at 17:20:32:374 but it is logging at 17:20:32:384. An extra of 11 milli-seconds constantly is added for every record. Below is my log file output

```<code>2017-12-04 17:40:42.205 INFO Hello11
2017-12-04 17:40:42.236 INFO Hello12
2017-12-04 17:40:42.268 INFO Hello13
2017-12-04 17:40:42.299 INFO Hello14
2017-12-04 17:40:42.330 INFO Hello15
2017-12-04 17:40:42.361 INFO Hello16
2017-12-04 17:40:42.393 INFO Hello17
2017-12-04 17:40:42.424 INFO Hello18
</code>```

You can see that first statement is logged at .205 milli second and the second statement is logged at .236 milli second. Infact I am sleeping the thread for 20 milliseconds so the correct timestamp should be .226 milli second. What am I doing wrong here? I need the exact time stamp to be written as it is very important in production. I have also tried this with log4j 1 but the same result. I have synchronized my System time with Internet time also. And one thing I found it worked perfectly with 5 and 15 milli-seconds of sleep but from 20 milli seconds this is causing a big issue.

答:
What am I doing wrong here?

Mostly flawed assumptions and expectations:

Incorrect micro-benchmark.

Flawed assumption that System.currentTimeMillis has sufficient granularity.

Assuming Thread.sleep is accurate.

Assuming adjustments to the system clock won't change wake up time.

Trying to solve a realtime problem without using realtime software.

Not accounting for code logging framework.

Not accounting for appenders that perform I/O.

Body:
I am new to Log4j2. I have written a simple program that actually logs data into RollingRandomAccessFile using log4j2. Below is the program:

public class Log4j2Example {

/**
 * @param args the command line arguments
 */
public static Logger mlogger = null;

public static void main(String[] args) throws InterruptedException {

    mlogger = LogManager.getLogger("Messages-log");
    int i = 0;
    while (true) {
        String str = "Hello" + i;
        System.out.println(str);
        mlogger.info(str);
        i++;
        Thread.sleep(20);
    }
}
}

My log4j2.xml file

    <?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
  <Appenders>
     <RollingRandomAccessFile name="Messages-log" fileName="Log4J/Messages-${date:yyyy-MM-dd}.log"
               immediateflush="true" filePattern="Log4J/Messages-%d{MM-dd-yyyy-HH}-%i.log.gz">
      <PatternLayout>
        <Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %p %m%n</Pattern>
      </PatternLayout>
      <Policies>
        <TimeBasedTriggeringPolicy />
        <SizeBasedTriggeringPolicy size="500 MB"/>
      </Policies>
      <DefaultRolloverStrategy max="50"/>
    </RollingRandomAccessFile>
  </Appenders>
  <Loggers>
    <Logger name="Messages-log" level="info" additivity="false">
        <appender-ref ref="Messages-log" level="info"/>
      </Logger>
    <root level="info">
        <appender-ref ref="Messages-log"/>
    </root>
</Loggers>
</Configuration>

I am writing a simple statement into the log file sleeping for 20 milli-seconds for every record. Now the time stamp in the file should be for example:
If the first statement is logged at 17:20:32:354 then the next statement should be logged at 17:20:32:374 but it is logging at 17:20:32:384. An extra of 11 milli-seconds constantly is added for every record. Below is my log file output

2017-12-04 17:40:42.205 INFO Hello11
2017-12-04 17:40:42.236 INFO Hello12
2017-12-04 17:40:42.268 INFO Hello13
2017-12-04 17:40:42.299 INFO Hello14
2017-12-04 17:40:42.330 INFO Hello15
2017-12-04 17:40:42.361 INFO Hello16
2017-12-04 17:40:42.393 INFO Hello17
2017-12-04 17:40:42.424 INFO Hello18

You can see that first statement is logged at .205 milli second and the second statement is logged at .236 milli second. Infact I am sleeping the thread for 20 milliseconds so the correct timestamp should be .226 milli second. What am I doing wrong here? I need the exact time stamp to be written as it is very important in production. I have also tried this with log4j 1 but the same result. I have synchronized my System time with Internet time also. And one thing I found it worked perfectly with 5 and 15 milli-seconds of sleep but from 20 milli seconds this is causing a big issue.


来源: stackexchange

问:
vue-tables-2 emit page number to parent component
I've been trying to find a way of getting the page number from vue-tables-2 but I couldn't figure it out. My best guess was with Vuex but I couldn't get it to work either. I just find the documentation very briefed and not detailed enough for newbies to Vue like me.

Is there anyone who managed to get it working or at least a similar tutorial.

Any help will be greatly appreciated!

答:
Vue tables 2 has a vue-tables.pagination custom event which is fired on page change. You can use it to track the current page.

Alternatively you can dive into the instance itself (If you are not using vuex) and fetch the Page data property (E.g this.$refs.myTable.Page)

ContentLicense: CC BY-SA 3.0


问:
C# Programmatically creating xyseries
I am trying to create an XyDataSeries for every column of my Datatable programmatically to be used for charting (SciChart). I need to do this is because the amount of columns and names are unknown in advance.

For any given series the x value will always just be an incrementing integer from 0 and the y values are the column values.

I am importing excel data into the Datatable and then passing each column to a Dictionary as a List where the column header is the name of the List by the following;

```<code>dict = dt.Columns.Cast<DataColumn>().ToDictionary(c => c.ColumnName, c => dt.AsEnumerable().Select(r => r[c]).ToList());
</code>```

Can i do something like the above where Dictionary<string, XyDataSeries<double, double>>?

Assuming i did know the amount of columns and their names, I could do something like this for every column/list;

Manually creating an XyDataSeries and iterating through a list to append the values. I then set the chartseries.DataSeries for the chart (defined in XAML) to the respective XyDataSeries.

```<code>var list = dict["ListName"];
XyDataSeries<double, double> xyseries;
xyseries = new XyDataSeries<double, double>() { SeriesName = "ListName" };
foreach (var i in list)
{
    double x = 1;
    var d = Convert.ToDouble(i);
    xyseries.Append(x++, d);
}
chartseries.DataSeries = xyseries;
</code>```

I also have to declare the series in XAML - Can I get around this?

Having to do this over 600 times is far from ideal though and I am really desperate for an elegant solution for this.

答:
Can i do something like the above where Dictionary<string, XyDataSeries<double, double>>?

The ToDictionary method accepts a Func<TSource, TElement> as its second argument. So you could create and populate the XyDataSeries<double, double> in this one. Something like this:

```<code>dict = dt.Columns.Cast<DataColumn>()
    .ToDictionary(c => c.ColumnName, c =>
    {
        var dataSeries = new XyDataSeries<double, double>();
        double x = 1.0;
        dataSeries.Append(dt.AsEnumerable().Select(_ => x++), dt.AsEnumerable().Select(r => Convert.ToDouble(r[c])));
        return dataSeries;
    });
</code>```

Title: C# Programmatically creating xyseries

Body:
I am trying to create an XyDataSeries for every column of my Datatable programmatically to be used for charting (SciChart). I need to do this is because the amount of columns and names are unknown in advance.

For any given series the x value will always just be an incrementing integer from 0 and the y values are the column values.

I am importing excel data into the Datatable and then passing each column to a Dictionary as a List where the column header is the name of the List by the following;

dict = dt.Columns.Cast<DataColumn>().ToDictionary(c => c.ColumnName, c => dt.AsEnumerable().Select(r => r[c]).ToList());

Can i do something like the above where Dictionary<string, XyDataSeries<double, double>>?

Assuming i did know the amount of columns and their names, I could do something like this for every column/list;

Manually creating an XyDataSeries and iterating through a list to append the values. I then set the chartseries.DataSeries for the chart (defined in XAML) to the respective XyDataSeries.

var list = dict["ListName"];
XyDataSeries<double, double> xyseries;
xyseries = new XyDataSeries<double, double>() { SeriesName = "ListName" };
foreach (var i in list)
{
    double x = 1;
    var d = Convert.ToDouble(i);
    xyseries.Append(x++, d);
}
chartseries.DataSeries = xyseries;

I also have to declare the series in XAML - Can I get around this?

Having to do this over 600 times is far from ideal though and I am really desperate for an elegant solution for this.

Body:
Can i do something like the above where Dictionary<string, XyDataSeries<double, double>>?

The ToDictionary method accepts a Func<TSource, TElement> as its second argument. So you could create and populate the XyDataSeries<double, double> in this one. Something like this:

dict = dt.Columns.Cast<DataColumn>()
    .ToDictionary(c => c.ColumnName, c =>
    {
        var dataSeries = new XyDataSeries<double, double>();
        double x = 1.0;
        dataSeries.Append(dt.AsEnumerable().Select(_ => x++), dt.AsEnumerable().Select(r => Convert.ToDouble(r[c])));
        return dataSeries;
    });


问:
Mouse events between two ItemsContorl elements
Take a look at below code. BoxControl has MouseLeftButtonDown/MouseLeftButtonUp events and those work fine when the mouse is clicked on
the box control other than when the mouse is clicked on below text block. I want MouseLeftButtonDown/MouseLeftButtonUp events of BoxControl
to work when the mouse is clicked on below textblock. Appreciate your help!</p>

答: You should hook into the PreviewMouseLeftButtonDown and PreviewMouseLeftButtonUp events instead.  Make sure to mark them as handled if you don't want them to bubble up any further.</p>

ContentLicense: CC BY-SA 2.5


问:
Bash command line parsing maintaining quotes of options
Without introducing getopts, I'd like to parse expressions like so:

./cli.sh data i -f -f="./path/to/file.txt" --flags="--a --b"

And variations/combinations thereof:

./cli.sh -file="./path/to/file.txt" data --flags="--a --b" -f i

Unfortunately, I am stuck with reading all optional values of the long options submitted, for example: --flags="--a --b" only returns --a as value for the long option --flags.

I have created a minimalized version of a parser which exhibits my current issue:

```<code>#!/usr/bin/env bash

__init_system () {
    CMD_SED="sed"
    CMD_SED_EXT="sed -E"
}

__init_system_Darwin () {
    __init_system
    CMD_SED="gsed"
    CMD_SED_EXT="gsed -E"
}

invoke_func () {
    SYSTEM=$(uname)
    FUNC=$1 && shift 1
    declare -f ${FUNC}_${SYSTEM} >/dev/null
    [ $? -eq 0 ] && { ${FUNC}_${SYSTEM} "$@"; return $?; } || { ${FUNC} "$@"; return $?; }
}

handle_cli_harmonizing () {
    cli_adjusted=$(echo "$@" | ${CMD_SED_EXT} \
                    -e 's@([ ])+@ @g'\
                    -e 's@\<h\>@help@g'\
                    -e 's@\<e\>@enable@g'\
                    -e 's@\<d\>@disable@g'\
                    -e 's@\<i\>@import@g'\
                    -e 's@\<sl\>@showlog@g'\
                    -e 's@\<st\>@status@g'\
                    | tr ' ' '\n' | sort -u | xargs
                )
    #echo ">>>  Original: <$@>"
    #echo ">>>  Adjusted: <$cli_adjusted>"
}

handle_cli_parsing () {
    for param in $@; do
        case ${param} in
            start|stop|status|enable|disable|data|showlog)
                CMD=$param
                ;;
            help|app|stats|import|export|dbinfo|exec)
                SPEC=$param
                ;;
            --*|-*)
                #echo ">>> Found param: <$param>"
                OPT="$OPT $param"
                ;;
            *)
                echo ">>> Parsing mismatch: $param"
                ;;
        esac
    done
}

handle_cli_optparams () {
    for opt in $OPT; do
        case "$opt" in
            --force|-f)
                OPT_FORCE=1
                ;;
            --file=*|-f=*)
                OPT_FILE=1
                FILE=${opt#*=}
                ;;
            --flags=*)
                OPT_FLAGS=1
                FLAGS=${opt#*=}
                ;;
            *)
                echo ">>> Unknown/unimplemented option specifier: $opt"
                ;;
        esac
    done
}

invoke_func __init_system
invoke_func handle_cli_harmonizing "$@"
invoke_func handle_cli_parsing ${cli_adjusted}
invoke_func handle_cli_optparams

echo "DEBUG[   CLI]: CMD=$CMD SPEC=$SPEC"
echo "DEBUG[TOGGLE]: FORCE=$OPT_FORCE FILE=$OPT_FILE FLAGS=$OPT_FLAGS"
echo "DEBUG[  OPTS]: FILE=$FILE FLAGS=$FLAGS"
</code>```

Expected ouput:

```<code>$ ./cli.sh data i -f -f="./path/to/file.txt" --flags="--a --b"
DEBUG[   CLI]: CMD=data SPEC=import
DEBUG[TOGGLE]: FORCE=1 FILE=1 FLAGS=1
DEBUG[  OPTS]: FILE=./path/to/file.txt FLAGS=--a --b
</code>```

Current output:

```<code>$ ./cli.sh data i -f -f="./path/to/file.txt" --flags="--a --b"
>>> Unknown/unimplemented option specifier: --b
DEBUG[   CLI]: CMD=data SPEC=import
DEBUG[TOGGLE]: FORCE=1 FILE=1 FLAGS=1
DEBUG[  OPTS]: FILE=./path/to/file.txt FLAGS=--a
</code>```

It's probably some quoting issue or a missing set, however I seem to be stuck here, and I'd really prefer to keep the simplistic approach I have taken.

I'd be especially stocked if someone would additionally offer a shell-only (no bashims) version for portability concerns, but that's icing on the cake. Mind you, this is only a very simple part of the whole parser I have written; enough to exhibit my current challenge.

I have read all the suggested linked issues while writing this question, and I have pondered for a while on How do I parse command line arguments in Bash?.

Update (2020/09/12): Even though this question has prematurely been downvoted, I found an elegant and more flexible solution, and have posted it as an answer below. It still beats getopt or any other approach I have seen concerning my specific requirements to command line parsing.

答:
The root of the problem is here:

```<code>OPT="$OPT $param"
</code>```

This is where the spaces embedded in $param become indistinguishable from the space used to append to the end of $OPT.

You can avoid this problem by making OPT an array, append values to it correctly:

```<code>OPT+=("$param")
</code>```

... and then use array syntax to iterate over the values of the array:

```<code>for opt in "${OPT[@]}"; do
</code>```

... and so on, consistently, everywhere, and watch out for correct double-quoting.

ContentLicense: CC BY-SA 4.0

Body:
Without introducing getopts, I'd like to parse expressions like so:

./cli.sh data i -f -f="./path/to/file.txt" --flags="--a --b"

And variations/combinations thereof:

./cli.sh -file="./path/to/file.txt" data --flags="--a --b" -f i

Unfortunately, I am stuck with reading all optional values of the long options submitted, for example: --flags="--a --b" only returns --a as value for the long option --flags.

I have created a minimalized version of a parser which exhibits my current issue:

#!/usr/bin/env bash

__init_system () {
    CMD_SED="sed"
    CMD_SED_EXT="sed -E"
}

__init_system_Darwin () {
    __init_system
    CMD_SED="gsed"
    CMD_SED_EXT="gsed -E"
}

invoke_func () {
    SYSTEM=$(uname)
    FUNC=$1 && shift 1
    declare -f ${FUNC}_${SYSTEM} >/dev/null
    [ $? -eq 0 ] && { ${FUNC}_${SYSTEM} "$@"; return $?; } || { ${FUNC} "$@"; return $?; }
}

handle_cli_harmonizing () {
    cli_adjusted=$(echo "$@" | ${CMD_SED_EXT} \
                    -e 's@([ ])+@ @g'\
                    -e 's@\<h\>@help@g'\
                    -e 's@\<e\>@enable@g'\
                    -e 's@\<d\>@disable@g'\
                    -e 's@\@import@g'\
                    -e 's@\<sl\>@showlog@g'\
                    -e 's@\<st\>@status@g'\
                    | tr ' ' '\n' | sort -u | xargs
                )
    #echo ">>>  Original: <$@>"
    #echo ">>>  Adjusted: <$cli_adjusted>"
}

handle_cli_parsing () {
    for param in $@; do
        case ${param} in
            start|stop|status|enable|disable|data|showlog)
                CMD=$param
                ;;
            help|app|stats|import|export|dbinfo|exec)
                SPEC=$param
                ;;
            --*|-*)
                #echo ">>> Found param: <$param>"
                OPT="$OPT $param"
                ;;
            *)
                echo ">>> Parsing mismatch: $param"
                ;;
        esac
    done
}

handle_cli_optparams () {
    for opt in $OPT; do
        case "$opt" in
            --force|-f)
                OPT_FORCE=1
                ;;
            --file=*|-f=*)
                OPT_FILE=1
                FILE=${opt#*=}
                ;;
            --flags=*)
                OPT_FLAGS=1
                FLAGS=${opt#*=}
                ;;
            *)
                echo ">>> Unknown/unimplemented option specifier: $opt"
                ;;
        esac
    done
}

invoke_func __init_system
invoke_func handle_cli_harmonizing "$@"
invoke_func handle_cli_parsing ${cli_adjusted}
invoke_func handle_cli_optparams

echo "DEBUG[   CLI]: CMD=$CMD SPEC=$SPEC"
echo "DEBUG[TOGGLE]: FORCE=$OPT_FORCE FILE=$OPT_FILE FLAGS=$OPT_FLAGS"
echo "DEBUG[  OPTS]: FILE=$FILE FLAGS=$FLAGS"

Expected ouput:

$ ./cli.sh data i -f -f="./path/to/file.txt" --flags="--a --b"
DEBUG[   CLI]: CMD=data SPEC=import
DEBUG[TOGGLE]: FORCE=1 FILE=1 FLAGS=1
DEBUG[  OPTS]: FILE=./path/to/file.txt FLAGS=--a --b

Current output:

$ ./cli.sh data i -f -f="./path/to/file.txt" --flags="--a --b"
>>> Unknown/unimplemented option specifier: --b
DEBUG[   CLI]: CMD=data SPEC=import
DEBUG[TOGGLE]: FORCE=1 FILE=1 FLAGS=1
DEBUG[  OPTS]: FILE=./path/to/file.txt FLAGS=--a

It's probably some quoting issue or a missing set, however I seem to be stuck here, and I'd really prefer to keep the simplistic approach I have taken.

I'd be especially stocked if someone would additionally offer a shell-only (no bashims) version for portability concerns, but that's icing on the cake. Mind you, this is only a very simple part of the whole parser I have written; enough to exhibit my current challenge.

I have read all the suggested linked issues while writing this question, and I have pondered for a while on How do I parse command line arguments in Bash?.

Update (2020/09/12): Even though this question has prematurely been downvoted, I found an elegant and more flexible solution, and have posted it as an answer below. It still beats getopt or any other approach I have seen concerning my specific requirements to command line parsing.

Body:
The root of the problem is here:

OPT="$OPT $param"

This is where the spaces embedded in $param become indistinguishable from the space used to append to the end of $OPT.

You can avoid this problem by making OPT an array, append values to it correctly:

OPT+=("$param")

... and then use array syntax to iterate over the values of the array:

for opt in "${OPT[@]}"; do

... and so on, consistently, everywhere, and watch out for correct double-quoting.


问:
How can I use a Python script in the command line without cd-ing to its directory? Is it the PYTHONPATH?
How can I make any use of PYTHONPATH? When I try to run a script in the path the file is not
found. When I cd to the directory holding the script the script runs. So what good is the
PYTHONPATH?

```<code>$ echo $PYTHONPATH
:/home/randy/lib/python

$ tree -L 1 '/home/randy/lib/python'
/home/randy/lib/python
├── gbmx_html.py
├── gbmx.py
├── __init__.py
├── __pycache__
├── scripts
└── yesno.py

$ python gbmx.py -h
python: can't open file 'gbmx.py': [Errno 2] No such file or directory

$ cd '/home/randy/lib/python'
</code>```

After cd to the file directory it runs ..

```<code>$ python gbmx.py -h
usage: gbmx.py [-h] [-b]
</code>```

Why can I not make any use of the PYTHONPATH?

答:
I think you're mixed up between PATH and PYTHONPATH. All you have to do to run a 'script' is have it's parental directory appended to your PATH variable. You can test this by running

```<code>which myscript.py
</code>```

Also, if myscripy.py depends on custom modules, their parental directories must also be added to the PYTHONPATH variable. Unfortunately, because the designers of python were clearly on drugs, testing your imports in the repl with the following will not guarantee that your PYTHONPATH is set properly for use in a script. This part of python programming is magic and can't be answered appropriately on stackoverflow.

```<code>$python
Python 2.7.8 blahblahblah
...
>from mymodule.submodule import ClassName
>test = ClassName()
>^D
$myscript_that_needs_mymodule.submodule.py
Traceback (most recent call last):
  File "myscript_that_needs_mymodule.submodule.py", line 5, in <module>
    from mymodule.submodule import ClassName
  File "/path/to/myscript_that_needs_mymodule.submodule.py", line 5, in <module>
    from mymodule.submodule import ClassName
ImportError: No module named submodule
</code>```

Body:
How can I make any use of PYTHONPATH? When I try to run a script in the path the file is not
found. When I cd to the directory holding the script the script runs. So what good is the
PYTHONPATH?

$ echo $PYTHONPATH
:/home/randy/lib/python

$ tree -L 1 '/home/randy/lib/python'
/home/randy/lib/python
├── gbmx_html.py
├── gbmx.py
├── __init__.py
├── __pycache__
├── scripts
└── yesno.py

$ python gbmx.py -h
python: can't open file 'gbmx.py': [Errno 2] No such file or directory

$ cd '/home/randy/lib/python'

After cd to the file directory it runs ..

$ python gbmx.py -h
usage: gbmx.py [-h] [-b]

Why can I not make any use of the PYTHONPATH?

Body:
I think you're mixed up between PATH and PYTHONPATH. All you have to do to run a 'script' is have it's parental directory appended to your PATH variable. You can test this by running

which myscript.py

Also, if myscripy.py depends on custom modules, their parental directories must also be added to the PYTHONPATH variable. Unfortunately, because the designers of python were clearly on drugs, testing your imports in the repl with the following will not guarantee that your PYTHONPATH is set properly for use in a script. This part of python programming is magic and can't be answered appropriately on stackoverflow.

$python
Python 2.7.8 blahblahblah
...
>from mymodule.submodule import ClassName
>test = ClassName()
>^D
$myscript_that_needs_mymodule.submodule.py
Traceback (most recent call last):
  File "myscript_that_needs_mymodule.submodule.py", line 5, in <module>
    from mymodule.submodule import ClassName
  File "/path/to/myscript_that_needs_mymodule.submodule.py", line 5, in <module>
    from mymodule.submodule import ClassName
ImportError: No module named submodule


问:
Sqlite3 causing problems for bundle install and gem install
Using Rails, whenever I try to do anything like "bundle install" or sudo gem install someGem, I get these same errors about sqlite3. I've tried both

```<code>sudo port install sqlite3 +universal
</code>```

and

```<code>sudo port install rb-sqlite3 +universal
</code>```

But neither has helped. Here is the error:

```<code>cmu-435163:photoGlass dpieri$ sudo gem install taps
Password:
Building native extensions.
This could take a while...
ERROR:  Error installing taps:
    ERROR: Failed to build gem native extension.

/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby extconf.rb
checking for sqlite3.h... yes
checking for sqlite3_libversion_number() in -lsqlite3... no
sqlite3 is missing. Try 'port install sqlite3 +universal'
or 'yum install sqlite3-devel' and check your shared library search path (the
location where your sqlite3 shared library is located).
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers.
Check the mkmf.log file for more details.
You may need configuration options.

Provided configuration options:
--with-opt-dir
--without-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
....

....
Gem files will remain installed in /Library/Ruby/Gems/1.8/gems/sqlite3-1.3.3 for inspection. Results logged to /Library/Ruby/Gems/1.8/gems/sqlite3-1.3.3/ext/sqlite3/gem_make.out
</code>```

UPDATE:
I found the mkmf.log file and here are its contents:

```<code>find_header: checking for sqlite3.h...
-------------------- yes

"gcc -E -I.
-I/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/universal-darwin10.0
-I. -I/usr/local/include -I/opt/local/include -I/sw/local/include -I/usr/include  -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE    -g -Os -pipe -fno-common -DENABLE_DTRACE  -fno-common  -pipe -fno-common    conftest.c -o conftest.i" checked program was: /* begin */ 1: #include <sqlite3.h> /* end */

--------------------

find_library: checking for sqlite3_libversion_number() in
-lsqlite3... -------------------- no

"gcc -o conftest -I.
-I/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/universal-darwin10.0
-I. -I/usr/local/include -I/opt/local/include -I/sw/local/include -I/usr/include  -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE    -g -Os -pipe -fno-common -DENABLE_DTRACE  -fno-common  -pipe -fno-common   conftest.c  -L. -L/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib
-L/usr/local/lib -L/opt/local/lib -L/sw/local/lib -L/usr/lib -L.       -lruby -lsqlite3  -lpthread -ldl  " conftest.c: In function ‘t’: conftest.c:3: error: ‘sqlite3_libversion_number’ undeclared (first use in this function) conftest.c:3: error: (Each undeclared identifier is reported only once conftest.c:3: error: for each function it appears in.) checked program was: /* begin */ 1: /*top*/ 2: int main() { return 0; } 3: int t() { void ((*volatile p)()); p = (void ((*)()))sqlite3_libversion_number; return 0; } /* end */

"gcc -o conftest -I.
-I/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/universal-darwin10.0
-I. -I/usr/local/include -I/opt/local/include -I/sw/local/include -I/usr/include  -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE    -g -Os -pipe -fno-common -DENABLE_DTRACE  -fno-common  -pipe -fno-common   conftest.c  -L. -L/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib
-L/usr/local/lib -L/opt/local/lib -L/sw/local/lib -L/usr/lib -L.       -lruby -lsqlite3  -lpthread -ldl  " ld: warning: directory '/sw/local/lib' following -L not found ld: warning: in /usr/local/lib/libsqlite3.dylib, missing required architecture x86_64 in file Undefined symbols:   "_sqlite3_libversion_number", referenced from:
      _t in ccSWkK1V.o ld: symbol(s) not found collect2: ld returned 1 exit status checked program was: /* begin
*/ 1: /*top*/ 2: int main() { return 0; } 3: int t() { sqlite3_libversion_number(); return 0; } /* end */

--------------------
</code>```

答:
Figured it out:

Did "which -a ruby" and "which -a
sqlite3" and "which -a gem" to
realize I had two or three versions
of each

Use port to uninstall all the versions of Ruby, Sqlite3, and rubygems it had installed

Manually uninstall the other sqlite3 that was not along the same
path as Ruby and Rubygems

Once Ruby, Rubygems, and Sqlite3 were all along the same bath
(usr/bin) it all works fine again.

Body:
Using Rails, whenever I try to do anything like "bundle install" or sudo gem install someGem, I get these same errors about sqlite3. I've tried both

sudo port install sqlite3 +universal

and

sudo port install rb-sqlite3 +universal

But neither has helped. Here is the error:

cmu-435163:photoGlass dpieri$ sudo gem install taps
Password:
Building native extensions.
This could take a while...
ERROR:  Error installing taps:
    ERROR: Failed to build gem native extension.

/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby extconf.rb
checking for sqlite3.h... yes
checking for sqlite3_libversion_number() in -lsqlite3... no
sqlite3 is missing. Try 'port install sqlite3 +universal'
or 'yum install sqlite3-devel' and check your shared library search path (the
location where your sqlite3 shared library is located).
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers.
Check the mkmf.log file for more details.
You may need configuration options.

Provided configuration options:
--with-opt-dir
--without-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
....

....
Gem files will remain installed in /Library/Ruby/Gems/1.8/gems/sqlite3-1.3.3 for inspection. Results logged to /Library/Ruby/Gems/1.8/gems/sqlite3-1.3.3/ext/sqlite3/gem_make.out

UPDATE:
I found the mkmf.log file and here are its contents:

find_header: checking for sqlite3.h...
-------------------- yes

"gcc -E -I.
-I/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/universal-darwin10.0
-I. -I/usr/local/include -I/opt/local/include -I/sw/local/include -I/usr/include  -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE    -g -Os -pipe -fno-common -DENABLE_DTRACE  -fno-common  -pipe -fno-common    conftest.c -o conftest.i" checked program was: /* begin */ 1: #include <sqlite3.h> /* end */

--------------------

find_library: checking for sqlite3_libversion_number() in
-lsqlite3... -------------------- no

"gcc -o conftest -I.
-I/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/universal-darwin10.0
-I. -I/usr/local/include -I/opt/local/include -I/sw/local/include -I/usr/include  -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE    -g -Os -pipe -fno-common -DENABLE_DTRACE  -fno-common  -pipe -fno-common   conftest.c  -L. -L/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib
-L/usr/local/lib -L/opt/local/lib -L/sw/local/lib -L/usr/lib -L.       -lruby -lsqlite3  -lpthread -ldl  " conftest.c: In function ‘t’: conftest.c:3: error: ‘sqlite3_libversion_number’ undeclared (first use in this function) conftest.c:3: error: (Each undeclared identifier is reported only once conftest.c:3: error: for each function it appears in.) checked program was: /* begin */ 1: /*top*/ 2: int main() { return 0; } 3: int t() { void ((*volatile p)()); p = (void ((*)()))sqlite3_libversion_number; return 0; } /* end */

"gcc -o conftest -I.
-I/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/universal-darwin10.0
-I. -I/usr/local/include -I/opt/local/include -I/sw/local/include -I/usr/include  -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE    -g -Os -pipe -fno-common -DENABLE_DTRACE  -fno-common  -pipe -fno-common   conftest.c  -L. -L/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib
-L/usr/local/lib -L/opt/local/lib -L/sw/local/lib -L/usr/lib -L.       -lruby -lsqlite3  -lpthread -ldl  " ld: warning: directory '/sw/local/lib' following -L not found ld: warning: in /usr/local/lib/libsqlite3.dylib, missing required architecture x86_64 in file Undefined symbols:   "_sqlite3_libversion_number", referenced from:
      _t in ccSWkK1V.o ld: symbol(s) not found collect2: ld returned 1 exit status checked program was: /* begin
*/ 1: /*top*/ 2: int main() { return 0; } 3: int t() { sqlite3_libversion_number(); return 0; } /* end */

--------------------


问:
How to set max width based on parent's width in Sass?
I have a container(Buttons) that is resizable. There's 2 buttons inside, 1 with dynamic text.

in my scss, I want to check if the width of the container is < 200, then max width of dynamic-button is 135px, else max width of dynamic button is 200px.

```<code>Buttons {
            height: 100%;
            margin: 0 auto;
            width: auto;
            text-align: center;
        }

Button {
        @include box-sizing;

        margin: 9px 9px 9px 9px;
        min-width: 60px;

        &.hot {
            margin-left: 9px;
        }
    }
</code>```

答: According to my experience and what I understand in your questions you must use a media query, inside the class your class "Button"</p>

Body:
I have a container(Buttons) that is resizable. There's 2 buttons inside, 1 with dynamic text.

in my scss, I want to check if the width of the container is < 200, then max width of dynamic-button is 135px, else max width of dynamic button is 200px.

Buttons {
            height: 100%;
            margin: 0 auto;
            width: auto;
            text-align: center;
        }

Button {
        @include box-sizing;

        margin: 9px 9px 9px 9px;
        min-width: 60px;

        &.hot {
            margin-left: 9px;
        }
    }


问:
What should you use instead of UICollectionViewFlowLayoutAutomaticSize in iOS 9?
I have a collectionView with a custom-spaced flowLayout. In iOS 10 and beyond, UICollectionViewFlowLayoutAutomaticSize works perfectly.

In iOS 9, using estimatedItemSize is breaking the layout, since the layout is using the values I pass to estimatedItemSize, even though they aren't accurate; they're estimates.

The size of the cells varies based on what comes back from the server, so they are all different.

layout.estimatedItemSize is being set in the collectionView's super's init.

How can I achieve a correct layout behavior in iOS 9?

Please let me know if I can clarify!

Edit: With the accepted answer, I also used the intrinsicContentSize of the element I wanted to size.

答:
Implement Following method:</p>

```<code>- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath;
</code>```

Body:
Implement Following method:

- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath;


问:
How to create nested structure in redis using python?
```<code>redis = {}
        redis['A'] = {}
        redis['A']['1'] = value1
        redis['A']['2'] = value2
        redis['A']['3'] = value3
</code>```

I need to make above structure in redis using python.
I have established connection using redis-py client in python like this:

```<code>_connection = redis.StrictRedis(host='localhost', port=6379, db=0)
</code>```

please let me know how to create , store and get values in redis using python?

答:
It's important to know that Redis does not support arbitrarily nested data structures natively. Instead, it has a few (maps, lists, queues). Anything more sophisticated, you need to decompose into these structures.

Now if you only care about two levels of nesting, then you can use HMAP support. See HSET and HGET

In your example, the HMAP's name would be 'A', and 1, 2, and 3 would be keys.

Also note that Redis only supports binary and string key/values. So you would need to decide whether you are going to store keys in str(x) form, or encode in binary (x.to_bytes(4, byteorder = 'big')

I leave it to you to figure out how to map this to the python client's APIs -- they tend to match the logical operations faithfully. For example,

```<code>_connection.hget('A', '1')
</code>```

Body:
redis = {}
        redis['A'] = {}
        redis['A']['1'] = value1
        redis['A']['2'] = value2
        redis['A']['3'] = value3

I need to make above structure in redis using python.
I have established connection using redis-py client in python like this:

_connection = redis.StrictRedis(host='localhost', port=6379, db=0)

please let me know how to create , store and get values in redis using python?

Body:
It's important to know that Redis does not support arbitrarily nested data structures natively. Instead, it has a few (maps, lists, queues). Anything more sophisticated, you need to decompose into these structures.

Now if you only care about two levels of nesting, then you can use HMAP support. See HSET and HGET

In your example, the HMAP's name would be 'A', and 1, 2, and 3 would be keys.

Also note that Redis only supports binary and string key/values. So you would need to decide whether you are going to store keys in str(x) form, or encode in binary (x.to_bytes(4, byteorder = 'big')

I leave it to you to figure out how to map this to the python client's APIs -- they tend to match the logical operations faithfully. For example,

_connection.hget('A', '1')


问:
View Device models for Event in Firebase Analytics
This is detail view of level_end event in Firebase Analytics.

I want to see all (or top 10) values of user properties, for example device_model (or custom user properies) for those users with whom the event happened.
Now I can see this information for gender, location, age.
For other properties I can only filtrate.

Is it possible to see other properties on Event detail view?

答:
Click on the "Add filter" button on the top left next to the event name dropdown, and choose User Property. You can filter device_model there. After that, you can see how many event count for each model and see which one performs better.
If you want to have a custom dashboard, I'd recommend to use BigQuery instead to aggregate and display custom query.


问:
CSS GRID - grid-template-areas with empty cells and auto placement
I’m trying to use the css grid layout module to display a 12 columns - 3 rows grid.

I need to have the 1st row to display only 2 elements (1st on the left hand side of the grid, 2nd on the right hand side).
I separated them with empty cells using 10 periods.

Then I need the following rows to display the remaining elements automatically.

I decided to go with grid-template-areas to have more control on positioning but might not be the best approach since it seems I have to give a specific grid-area name to all the elements.

Also, when I try using the auto grid-area property to the remaining cells so that they can automatically fill the 3rd row, it seems they fill the empty cells from the first row.

What would be the most effective way to solve this problem?

Here is my code:

.grid {
  display: grid;
  grid-template-areas:
   "elem1 . . . . . . . . . . elem2"
   "elem3 elem4 elem5 elem6 elem7 elem8 elem9 elem10 elem11 elem12 elem13 elem14";
}
.elem{
 text-align: center;
 color: white;
}
.elem1 {
  background-color: blue;
  grid-area: elem1;
}
.elem2 {
  background-color: red;
  grid-area: elem2;
}
.elem3 {
  background-color: cyan;
  grid-area: elem3;
}
.elem4 {
  background-color: green;
  grid-area: elem4;
}
.elem5 {
  background-color: magenta;
  grid-area: elem5;
}
.elem6 {
  background-color: blue;
  grid-area: elem6;
}
.elem7 {
  background-color: red;
  grid-area: elem7;
}
.elem8 {
  background-color: cyan;
  grid-area: elem8;
}
.elem9 {
  background-color: green;
  grid-area: elem9;
}
.elem10 {
  background-color: magenta;
  grid-area: elem10;
}
.elem11 {
  background-color: blue;
  grid-area: elem11
}
.elem12 {
  background-color: red;
  grid-area: elem12;
}
.elem13 {
  background-color: cyan;
  grid-area: elem13;
}
.elem14 {
  background-color: green;
  grid-area: elem14;
}
.elem15 {
  background-color: magenta;
  grid-area: auto;
}
.elem16 {
  background-color: green;
  grid-area: auto;
}
.elem17 {
  background-color: magenta;
  grid-area: auto;
}
.elem18 {
  background-color: cyan;
  grid-area: auto;
}
.elem19 {
  background-color: magenta;
  grid-area: auto;
}
.elem20 {
  background-color: blue;
  grid-area: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div class="elem elem1">
    elem1
  </div>
  <div class="elem elem2">
    elem2
  </div>
  <div class="elem elem3">
    elem3
  </div>
   <div class="elem elem4">
    elem4
  </div>
  <div class="elem elem5">
    elem5
  </div>
  <div class="elem elem6">
    elem6
  </div>
  <div class="elem elem7">
    elem7
  </div>
  <div class="elem elem8">
    elem8
  </div>
  <div class="elem elem9">
    elem9
  </div>
  <div class="elem elem10">
    elem10
  </div>
  <div class="elem elem11">
    elem11
  </div>
  <div class="elem elem12">
    elem12
  </div>
  <div class="elem elem13">
    elem13
  </div>
  <div class="elem elem14">
    elem14
  </div>
  <div class="elem elem15">
    elem15
  </div>
  <div class="elem elem16">
    elem16
  </div>
  <div class="elem elem17">
    elem17
  </div>
  <div class="elem elem18">
    elem18
  </div>
  <div class="elem elem19">
    elem19
  </div>
  <div class="elem elem20">
    elem20
  </div>
</div></code>```

Many thanks

答:
Using the grid-template-areas property with an implicit grid, the grid auto placement algorithm will look for unoccupied cells to fill before creating a new row (see bottom for more details).

Just specify what you want:

```<code>.elem:nth-last-child(-n + 6) {
  grid-row-start: 3;
}
</code>```

This rule overrides the default auto-placement process, placing the last six items on row three.

.grid {
  display: grid;
  grid-template-areas:
   "elem1 . . . . . . . . . . elem2"
   "elem3 elem4 elem5 elem6 elem7 elem8 elem9 elem10 elem11 elem12 elem13 elem14";
}

/* NEW */
.elem:nth-last-child(-n + 6) {
  grid-row-start: 3;
}

.elem{
 text-align: center;
 color: white;
}
.elem1 {
  background-color: blue;
  grid-area: elem1;
}
.elem2 {
  background-color: red;
  grid-area: elem2;
}
.elem3 {
  background-color: cyan;
  grid-area: elem3;
}
.elem4 {
  background-color: green;
  grid-area: elem4;
}
.elem5 {
  background-color: magenta;
  grid-area: elem5;
}
.elem6 {
  background-color: blue;
  grid-area: elem6;
}
.elem7 {
  background-color: red;
  grid-area: elem7;
}
.elem8 {
  background-color: cyan;
  grid-area: elem8;
}
.elem9 {
  background-color: green;
  grid-area: elem9;
}
.elem10 {
  background-color: magenta;
  grid-area: elem10;
}
.elem11 {
  background-color: blue;
  grid-area: elem11
}
.elem12 {
  background-color: red;
  grid-area: elem12;
}
.elem13 {
  background-color: cyan;
  grid-area: elem13;
}
.elem14 {
  background-color: green;
  grid-area: elem14;
}
.elem15 {
  background-color: magenta;
  grid-area: auto;
}
.elem16 {
  background-color: green;
  grid-area: auto;
}
.elem17 {
  background-color: magenta;
  grid-area: auto;
}
.elem18 {
  background-color: cyan;
  grid-area: auto;
}
.elem19 {
  background-color: magenta;
  grid-area: auto;
}
.elem20 {
  background-color: blue;
  grid-area: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div class="elem elem1">elem1</div>
  <div class="elem elem2">elem2</div>
  <div class="elem elem3">elem3</div>
  <div class="elem elem4">elem4</div>
  <div class="elem elem5">elem5</div>
  <div class="elem elem6">elem6</div>
  <div class="elem elem7">elem7</div>
  <div class="elem elem8">elem8</div>
  <div class="elem elem9">elem9</div>
  <div class="elem elem10">elem10</div>
  <div class="elem elem11">elem11</div>
  <div class="elem elem12">elem12</div>
  <div class="elem elem13">elem13</div>
  <div class="elem elem14">elem14</div>
  <div class="elem elem15">elem15</div>
  <div class="elem elem16">elem16</div>
  <div class="elem elem17">elem17</div>
  <div class="elem elem18">elem18</div>
  <div class="elem elem19">elem19</div>
  <div class="elem elem20">elem20</div>
</div></code>```

There are five primary steps in the Grid Item Placement Algorithm (0-4).

One of the first steps is to position grid items that are not auto-positioned. This gives priority to items on which you've specified a position.

Last in the process comes Position the remaining grid items, which says this:

The auto-placement cursor defines the current "insertion point" in the
  grid, specified as a pair of row and column grid lines. Initially the
  auto-placement cursor is set to the start-most row and column lines in
  the implicit grid.

This section also explains why your auto-placed items start on row 1, column 2:

If the item has an automatic grid position in both axes:

Increment the column position of the auto-placement cursor until either this item’s grid area does not overlap any occupied grid cells, or the cursor’s column position, plus the item’s column span, overflow the number of columns in the implicit grid, as determined earlier in this algorithm.

Body:
I’m trying to use the css grid layout module to display a 12 columns - 3 rows grid.

I need to have the 1st row to display only 2 elements (1st on the left hand side of the grid, 2nd on the right hand side).
I separated them with empty cells using 10 periods.

Then I need the following rows to display the remaining elements automatically.

I decided to go with grid-template-areas to have more control on positioning but might not be the best approach since it seems I have to give a specific grid-area name to all the elements.

Also, when I try using the auto grid-area property to the remaining cells so that they can automatically fill the 3rd row, it seems they fill the empty cells from the first row.

What would be the most effective way to solve this problem?

Here is my code:

.grid {
  display: grid;
  grid-template-areas:
   "elem1 . . . . . . . . . . elem2"
   "elem3 elem4 elem5 elem6 elem7 elem8 elem9 elem10 elem11 elem12 elem13 elem14";
}
.elem{
 text-align: center;
 color: white;
}
.elem1 {
  background-color: blue;
  grid-area: elem1;
}
.elem2 {
  background-color: red;
  grid-area: elem2;
}
.elem3 {
  background-color: cyan;
  grid-area: elem3;
}
.elem4 {
  background-color: green;
  grid-area: elem4;
}
.elem5 {
  background-color: magenta;
  grid-area: elem5;
}
.elem6 {
  background-color: blue;
  grid-area: elem6;
}
.elem7 {
  background-color: red;
  grid-area: elem7;
}
.elem8 {
  background-color: cyan;
  grid-area: elem8;
}
.elem9 {
  background-color: green;
  grid-area: elem9;
}
.elem10 {
  background-color: magenta;
  grid-area: elem10;
}
.elem11 {
  background-color: blue;
  grid-area: elem11
}
.elem12 {
  background-color: red;
  grid-area: elem12;
}
.elem13 {
  background-color: cyan;
  grid-area: elem13;
}
.elem14 {
  background-color: green;
  grid-area: elem14;
}
.elem15 {
  background-color: magenta;
  grid-area: auto;
}
.elem16 {
  background-color: green;
  grid-area: auto;
}
.elem17 {
  background-color: magenta;
  grid-area: auto;
}
.elem18 {
  background-color: cyan;
  grid-area: auto;
}
.elem19 {
  background-color: magenta;
  grid-area: auto;
}
.elem20 {
  background-color: blue;
  grid-area: auto;
}

    elem1

    elem2

    elem3

    elem4

    elem5

    elem6

    elem7

    elem8

    elem9

    elem10

    elem11

    elem12

    elem13

    elem14

    elem15

    elem16

    elem17

    elem18

    elem19

    elem20

Many thanks

Body:
Using the grid-template-areas property with an implicit grid, the grid auto placement algorithm will look for unoccupied cells to fill before creating a new row (see bottom for more details).

Just specify what you want:

.elem:nth-last-child(-n + 6) {
  grid-row-start: 3;
}

This rule overrides the default auto-placement process, placing the last six items on row three.

.grid {
  display: grid;
  grid-template-areas:
   "elem1 . . . . . . . . . . elem2"
   "elem3 elem4 elem5 elem6 elem7 elem8 elem9 elem10 elem11 elem12 elem13 elem14";
}

/* NEW */
.elem:nth-last-child(-n + 6) {
  grid-row-start: 3;
}

.elem{
 text-align: center;
 color: white;
}
.elem1 {
  background-color: blue;
  grid-area: elem1;
}
.elem2 {
  background-color: red;
  grid-area: elem2;
}
.elem3 {
  background-color: cyan;
  grid-area: elem3;
}
.elem4 {
  background-color: green;
  grid-area: elem4;
}
.elem5 {
  background-color: magenta;
  grid-area: elem5;
}
.elem6 {
  background-color: blue;
  grid-area: elem6;
}
.elem7 {
  background-color: red;
  grid-area: elem7;
}
.elem8 {
  background-color: cyan;
  grid-area: elem8;
}
.elem9 {
  background-color: green;
  grid-area: elem9;
}
.elem10 {
  background-color: magenta;
  grid-area: elem10;
}
.elem11 {
  background-color: blue;
  grid-area: elem11
}
.elem12 {
  background-color: red;
  grid-area: elem12;
}
.elem13 {
  background-color: cyan;
  grid-area: elem13;
}
.elem14 {
  background-color: green;
  grid-area: elem14;
}
.elem15 {
  background-color: magenta;
  grid-area: auto;
}
.elem16 {
  background-color: green;
  grid-area: auto;
}
.elem17 {
  background-color: magenta;
  grid-area: auto;
}
.elem18 {
  background-color: cyan;
  grid-area: auto;
}
.elem19 {
  background-color: magenta;
  grid-area: auto;
}
.elem20 {
  background-color: blue;
  grid-area: auto;
}

<div class="grid">
  <div class="elem elem1">elem1</div>
  <div class="elem elem2">elem2</div>
  <div class="elem elem3">elem3</div>
  <div class="elem elem4">elem4</div>
  <div class="elem elem5">elem5</div>
  <div class="elem elem6">elem6</div>
  <div class="elem elem7">elem7</div>
  <div class="elem elem8">elem8</div>
  <div class="elem elem9">elem9</div>
  <div class="elem elem10">elem10</div>
  <div class="elem elem11">elem11</div>
  <div class="elem elem12">elem12</div>
  <div class="elem elem13">elem13</div>
  <div class="elem elem14">elem14</div>
  <div class="elem elem15">elem15</div>
  <div class="elem elem16">elem16</div>
  <div class="elem elem17">elem17</div>
  <div class="elem elem18">elem18</div>
  <div class="elem elem19">elem19</div>
  <div class="elem elem20">elem20</div>
</div>

There are five primary steps in the Grid Item Placement Algorithm (0-4).

One of the first steps is to position grid items that are not auto-positioned. This gives priority to items on which you've specified a position.

Last in the process comes Position the remaining grid items, which says this:

The auto-placement cursor defines the current "insertion point" in the
  grid, specified as a pair of row and column grid lines. Initially the
  auto-placement cursor is set to the start-most row and column lines in
  the implicit grid.

This section also explains why your auto-placed items start on row 1, column 2:

If the item has an automatic grid position in both axes:

Increment the column position of the auto-placement cursor until either this item’s grid area does not overlap any occupied grid cells, or the cursor’s column position, plus the item’s column span, overflow the number of columns in the implicit grid, as determined earlier in this algorithm.


问:
Create a consumption based App Service Plan with Powershell
I found this answer for the question

Does anyone know how to create a Consumption app-service-plan with Azure?

When I look at the properties (using https://resources.azure.com/ ) of one I made (by the Gui), I see the following properties;

```<code>  },
  "sku": {
    "name": "Y1",
    "tier": "Dynamic",
    "size": "Y1",
    "family": "Y",
    "capacity": 0
  }

{
  "id": "/subscriptions/xxxxxxxxxxxxxxxxxxxxxxxx/resourceGroups/MyResourceGroup/providers/Microsoft.Web/serverfarms/MyHandMadeConsumptionAppServicePlan",
  "name": "MyHandMadeConsumptionAppServicePlan",
  "type": "Microsoft.Web/serverfarms",
  "kind": "functionapp",
  "location": "East US",
</code>```

But if I try (the important part being "-Tier Dynamic")

```<code>$plan = New-AzureRmAppServicePlan -Name 'MyPowershellCreatedAppServicePlan' -ResourceGroupName 'MyResourceGroup' -Location 'PickALocation' -Tier Dynamic
</code>```

I get the exception:

Exception -  + Cannot validate argument on parameter 'Tier'. The
argument "Dynamic" does not belong to the set
"Free,Shared,Basic,Standard,Premium,PremiumV2" specified by the
ValidateSet attribute. Supply an argument that is in the set and then
try the command again.

答:
This is not really an answer to your questions, but just some research...

You will notice that in older Microsoft.Web schemas, there was no support for "Dynamic". Instead, we see a list similar to what you see in the error message.

https://github.com/Azure/azure-resource-manager-schemas/blob/master/schemas/2015-08-01/Microsoft.Web.json#L37

In the newer schema (from 2016-09-01), which is what I'm seeing when I view my Comsumption App Service Plan in resources.azure.com, you'll find "Dynamic" as a valid value under  computeMode:  https://github.com/Azure/azure-resource-manager-schemas/blob/master/schemas/2016-09-01/Microsoft.Web.json#L189

I'm not sure how you can set the computeMode value in PowerShell, since the documentation doesn't show that this is exposed:
https://learn.microsoft.com/en-us/powershell/module/azurerm.websites/new-azurermappserviceplan?view=azurermps-5.0.0

Body:
I found this answer for the question

Does anyone know how to create a Consumption app-service-plan with Azure?

When I look at the properties (using https://resources.azure.com/ ) of one I made (by the Gui), I see the following properties;

  },
  "sku": {
    "name": "Y1",
    "tier": "Dynamic",
    "size": "Y1",
    "family": "Y",
    "capacity": 0
  }

{
  "id": "/subscriptions/xxxxxxxxxxxxxxxxxxxxxxxx/resourceGroups/MyResourceGroup/providers/Microsoft.Web/serverfarms/MyHandMadeConsumptionAppServicePlan",
  "name": "MyHandMadeConsumptionAppServicePlan",
  "type": "Microsoft.Web/serverfarms",
  "kind": "functionapp",
  "location": "East US",

But if I try (the important part being "-Tier Dynamic")

$plan = New-AzureRmAppServicePlan -Name 'MyPowershellCreatedAppServicePlan' -ResourceGroupName 'MyResourceGroup' -Location 'PickALocation' -Tier Dynamic

I get the exception:

Exception -  + Cannot validate argument on parameter 'Tier'. The
argument "Dynamic" does not belong to the set
"Free,Shared,Basic,Standard,Premium,PremiumV2" specified by the
ValidateSet attribute. Supply an argument that is in the set and then
try the command again.


问:
Recursively merge like indexes
I have an array that has like indexes that I am trying to merge together. For some reason I can't wrap my head around it.

Original Array

```<code>$seperateArray = json_decode('[
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Harold" },
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Arthur" },
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Tom" },
{ "tier1": "Group2", "tier2": "Blue", "tier3": "Round", "tier4": "Beth" },
{ "tier1": "Group3", "tier2": "Blue", "tier3": "Round", "tier4": "Peter" }]', true);
</code>```

Turn it into:

```<code>{
    "Group1": {
        "Blue": {
            "Round": [
                "Harold",
                "Arthur",
                "Tom"
            ]
        }
    },
    "Group2": {
        "Blue": {
            "Round": [
                "Peter"
            ]
        }
    }
}
</code>```

This is where I am at so far but I don't know if I'm moving in the right direction.

```<code>$newCombined = array();

//this each statement will show every tier 1-4 array object
foreach($seperateArray as $s) {

    if(!array_key_exists($s['tier1'], $newCombined) $newCombined[$s['tier1']] = array();
    if(!array_key_exists($newCombined[$s['tier1']][$s['tier2']], $newCombined[$s['tier1']])) $newCombined[$s['tier1']][$s['tier2']] = array();
    //.. and so on

}
</code>```

答:
Sidyll's answer is perfect but as I was working on my own solution, I'll post it too:

```<code>$input = json_decode('[
  { "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Harold" },
  { "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Arthur" },
  { "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Tom" },
  { "tier1": "Group2", "tier2": "Blue", "tier3": "Round", "tier4": "Beth" },
  { "tier1": "Group3", "tier2": "Blue", "tier3": "Round", "tier4": "Peter" }]', true);

$output = [];

foreach($input as $row) {
  $recursion = &$output;
  foreach($row as $key => $value) {
    if ($key != 'tier4' && !isset($recursion[$value])) {
      $recursion[$value] = [];
    }
    if ($key == 'tier4') {
      $recursion[] = $value;
    } else {
      $recursion = &$recursion[$value];
    }
  }
}

var_dump($output);
</code>```

array(3) { ["Group1"]=> array(1) { ["Blue"]=> array(1) { ["Round"]=> array(3) { [0]=> string(6) "Harold" [1]=> string(6) "Arthur" [2]=> string(3) "Tom" } } } ["Group2"]=> array(1) { ["Blue"]=> array(1) { ["Round"]=> array(1) { [0]=> string(4) "Beth" } } } ["Group3"]=> array(1) { ["Blue"]=> array(1) { ["Round"]=> &array(1) { [0]=> string(5) "Peter" } } } }

Not particularly proud of it, but it works.

Title: Recursively merge like indexes

Body:
I have an array that has like indexes that I am trying to merge together. For some reason I can't wrap my head around it.

Original Array

$seperateArray = json_decode('[
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Harold" },
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Arthur" },
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Tom" },
{ "tier1": "Group2", "tier2": "Blue", "tier3": "Round", "tier4": "Beth" },
{ "tier1": "Group3", "tier2": "Blue", "tier3": "Round", "tier4": "Peter" }]', true);

Turn it into:

{
    "Group1": {
        "Blue": {
            "Round": [
                "Harold",
                "Arthur",
                "Tom"
            ]
        }
    },
    "Group2": {
        "Blue": {
            "Round": [
                "Peter"
            ]
        }
    }
}

This is where I am at so far but I don't know if I'm moving in the right direction.

$newCombined = array();

//this each statement will show every tier 1-4 array object
foreach($seperateArray as $s) {

    if(!array_key_exists($s['tier1'], $newCombined) $newCombined[$s['tier1']] = array();
    if(!array_key_exists($newCombined[$s['tier1']][$s['tier2']], $newCombined[$s['tier1']])) $newCombined[$s['tier1']][$s['tier2']] = array();
    //.. and so on

}

Body:
Sidyll's answer is perfect but as I was working on my own solution, I'll post it too:

$input = json_decode('[
  { "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Harold" },
  { "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Arthur" },
  { "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Tom" },
  { "tier1": "Group2", "tier2": "Blue", "tier3": "Round", "tier4": "Beth" },
  { "tier1": "Group3", "tier2": "Blue", "tier3": "Round", "tier4": "Peter" }]', true);

$output = [];

foreach($input as $row) {
  $recursion = &$output;
  foreach($row as $key => $value) {
    if ($key != 'tier4' && !isset($recursion[$value])) {
      $recursion[$value] = [];
    }
    if ($key == 'tier4') {
      $recursion[] = $value;
    } else {
      $recursion = &$recursion[$value];
    }
  }
}

var_dump($output);

array(3) { ["Group1"]=> array(1) { ["Blue"]=> array(1) { ["Round"]=> array(3) { [0]=> string(6) "Harold" [1]=> string(6) "Arthur" [2]=> string(3) "Tom" } } } ["Group2"]=> array(1) { ["Blue"]=> array(1) { ["Round"]=> array(1) { [0]=> string(4) "Beth" } } } ["Group3"]=> array(1) { ["Blue"]=> array(1) { ["Round"]=> &array(1) { [0]=> string(5) "Peter" } } } }

Not particularly proud of it, but it works.


问:
shared_ptr causing segfault
I am trying to use shared_ptr with my class but for some reason I get segfault. Maybe I am doing something stupid. </p>

```<code>#include <tr1/memory>
#include <iostream>
class Dataset ;
typedef int DataClass;
class Dataset_Impl{
    friend class Dataset ;
    DataClass *dc;
    Dataset_Impl(){dc = new DataClass[10];}
    public:
    void getSubset(Dataset_Impl* &dObj){
        dObj = new Dataset_Impl();  //Causing segfault when using shared_ptr
        /*copy subset of 'dc' to dObj->dc and return*/std::cout<<"Copied subset";
    }
};
class Dataset{
    Dataset_Impl *d;
    public:
        Dataset (){};
        inline void const getSubset(Dataset &dObj) const{d->getSubset(dObj.d);}
};
int main(){
    Dataset m1,subset1;std::shared_ptr<Dataset> subset2;
    m1.getSubset(subset1);
    m1.getSubset((*subset2)); //Causing segfault
}
</code>```

答:
Your shared_ptr is empty. It does not store a pointer to a Dataset.
Use e.g.</p>

```<code> std::shared_ptr<Dataset> subset2(new Dataset) ;
</code>```

Title: shared_ptr causing segfault

Body:
I am trying to use shared_ptr with my class but for some reason I get segfault. Maybe I am doing something stupid.

#include <tr1/memory>
#include <iostream>
class Dataset ;
typedef int DataClass;
class Dataset_Impl{
    friend class Dataset ;
    DataClass *dc;
    Dataset_Impl(){dc = new DataClass[10];}
    public:
    void getSubset(Dataset_Impl* &dObj){
        dObj = new Dataset_Impl();  //Causing segfault when using shared_ptr
        /*copy subset of 'dc' to dObj->dc and return*/std::cout<<"Copied subset";
    }
};
class Dataset{
    Dataset_Impl *d;
    public:
        Dataset (){};
        inline void const getSubset(Dataset &dObj) const{d->getSubset(dObj.d);}
};
int main(){
    Dataset m1,subset1;std::shared_ptr<Dataset> subset2;
    m1.getSubset(subset1);
    m1.getSubset((*subset2)); //Causing segfault
}

Body:
Your shared_ptr is empty. It does not store a pointer to a Dataset.
Use e.g.

 std::shared_ptr<Dataset> subset2(new Dataset) ;


问:
Angular's `@Host` decorator not reaching the top?
In my main app.ts I've declared a global provider :

```<code>providers: [{provide: Dependency, useValue: createDependency('AppModule provider')}]
</code>```

(Where createDependency is just a function that returns a class which has a getName() method.)

I also have a components :

```<code>    <my-app-component-3>Hello from 3</my-app-component-3>
</code>```

Code :

```<code>@Component({
    selector: 'my-app-component-3',
    template: `
        <div>Component3:
            <ng-content></ng-content>
            : <span [innerHTML]="dependency?.getName()"></span>
        </div>
    `,

})
export class Component3 {
    constructor(@Host() @Optional() public dependency: Dependency) {}
}
</code>```

The result is:

Component3: Hello from 3 :

But I expect the result to be :

Component3: Hello from 3 :AppModule provider

Because basically the app structure is :

```<code><my-app>
  <my-app-component-3>
  </my-app-component-3>
</my-app>
</code>```

Question:

Why doesn't @Host()  match the parent provider ?

(which is   : providers: [{provide: Dependency, useValue: createDependency('AppModule provider')}])

To my knowledge - the injector should seek for a Dependency in this manner :

So why doesn't it find it ?

PLUNKER

Notice

I already know that if I remove @host - it does reach the top. My question is why adding @host - is not reaching the top - despite the fact thatmy-component3 is under my-app !!

答:
straight from Angular's docs on dependency injection and the Host decorator: https://angular.io/guide/dependency-injection-in-action#qualify-dependency-lookup-with-optional-and-host

```<code>The @Host decorator stops the upward search at the host component.

The host component is typically the component requesting the dependency.
</code>```

with the @Host decorator, you're telling it to only check the host component for a provider, and you're making it optional, so it's just seeing there's no provider and quitting.

In practice, the use case for the Host decorator is extremely narrow, and really only ever makes sense if you're projecting content.

Body:
In my main app.ts I've declared a global provider :

providers: [{provide: Dependency, useValue: createDependency('AppModule provider')}]

(Where createDependency is just a function that returns a class which has a getName() method.)

I also have a components :

    <my-app-component-3>Hello from 3</my-app-component-3>

Code :

@Component({
    selector: 'my-app-component-3',
    template: `

Component3:
            <ng-content></ng-content>
            :

    `,

})
export class Component3 {
    constructor(@Host() @Optional() public dependency: Dependency) {}
}

The result is:

Component3: Hello from 3 :

But I expect the result to be :

Component3: Hello from 3 :AppModule provider

Because basically the app structure is :

<my-app>
  <my-app-component-3>
  </my-app-component-3>
</my-app>

Question:

Why doesn't @Host()  match the parent provider ?

(which is   : providers: [{provide: Dependency, useValue: createDependency('AppModule provider')}])

To my knowledge - the injector should seek for a Dependency in this manner :

So why doesn't it find it ?

PLUNKER

Notice

I already know that if I remove @host - it does reach the top. My question is why adding @host - is not reaching the top - despite the fact thatmy-component3 is under my-app !!

Body:
straight from Angular's docs on dependency injection and the Host decorator: https://angular.io/guide/dependency-injection-in-action#qualify-dependency-lookup-with-optional-and-host

The @Host decorator stops the upward search at the host component.

The host component is typically the component requesting the dependency.

with the @Host decorator, you're telling it to only check the host component for a provider, and you're making it optional, so it's just seeing there's no provider and quitting.

In practice, the use case for the Host decorator is extremely narrow, and really only ever makes sense if you're projecting content.


问:
How can show a JTree in a JDialog?
I would like to put a JTree inside a JDialog so that the user can select an item on the tree hierarchy and confirm selection by clicking the OK button. The user can cancel the selection by clicking the CANCEL button.

What is the easiest way to get that dialog in a Java Swing app?

答:
Try this:
first create a App like this:

```<code>import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;

public class App {

    private JFrame frame;
    private JTextField textField;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    App window = new App();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public App() {
        initialize();
    }

    public void setValue(Object obj) {
        textField.setText(obj.toString());
    }

    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JButton btnOpen = new JButton("Open");
        btnOpen.setBounds(100, 57, 177, 43);
        btnOpen.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                new MyDialog(App.this).setVisible(true);
            }
        });
        frame.getContentPane().setLayout(null);
        frame.getContentPane().add(btnOpen);

        textField = new JTextField();
        textField.setBounds(100, 126, 177, 19);
        frame.getContentPane().add(textField);
        textField.setColumns(10);
    }
}
</code>```

Then in the same package create MyDialog:

```<code>import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.border.EmptyBorder;
import javax.swing.tree.DefaultMutableTreeNode;

public class MyDialog extends JDialog {

    private final JPanel contentPanel = new JPanel();
    private JTree tree = null;

    public MyDialog(App ref) {
        setModalityType(ModalityType.APPLICATION_MODAL);
        setTitle("MyDialog");
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        getContentPane().setLayout(new BorderLayout());
        contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
        getContentPane().add(contentPanel, BorderLayout.CENTER);
        contentPanel.setLayout(new BorderLayout(0, 0));

        {
            tree = new JTree();
            contentPanel.add(tree);
        }
        {
            JPanel buttonPane = new JPanel();
            buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
            getContentPane().add(buttonPane, BorderLayout.SOUTH);
            {
                JButton okButton = new JButton("OK");
                okButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent arg0) {
                        DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
                        if (node == null)
                            return;
                        Object userObject = node.getUserObject();

                        ref.setValue(userObject);
                        MyDialog.this.dispose();
                    }
                });
                okButton.setActionCommand("OK");
                buttonPane.add(okButton);
                getRootPane().setDefaultButton(okButton);
            }
            {
                JButton cancelButton = new JButton("Cancel");
                cancelButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent arg0) {
                        MyDialog.this.dispose();
                    }
                });
                cancelButton.setActionCommand("Cancel");
                buttonPane.add(cancelButton);
            }
        }
    }
}
</code>```

App will deply a Dialog with a tree. If you select a tree node and hit "ok" it'll close the dialog and show the value in the App's textfield. "cancel" will abort the whole process. It works for me.

hope it helps

Title: How can show a JTree in a JDialog?

Body:
Try this:
first create a App like this:

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;

public class App {

    private JFrame frame;
    private JTextField textField;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    App window = new App();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public App() {
        initialize();
    }

    public void setValue(Object obj) {
        textField.setText(obj.toString());
    }

    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JButton btnOpen = new JButton("Open");
        btnOpen.setBounds(100, 57, 177, 43);
        btnOpen.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                new MyDialog(App.this).setVisible(true);
            }
        });
        frame.getContentPane().setLayout(null);
        frame.getContentPane().add(btnOpen);

        textField = new JTextField();
        textField.setBounds(100, 126, 177, 19);
        frame.getContentPane().add(textField);
        textField.setColumns(10);
    }
}

Then in the same package create MyDialog:

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.border.EmptyBorder;
import javax.swing.tree.DefaultMutableTreeNode;

public class MyDialog extends JDialog {

    private final JPanel contentPanel = new JPanel();
    private JTree tree = null;

    public MyDialog(App ref) {
        setModalityType(ModalityType.APPLICATION_MODAL);
        setTitle("MyDialog");
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        getContentPane().setLayout(new BorderLayout());
        contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
        getContentPane().add(contentPanel, BorderLayout.CENTER);
        contentPanel.setLayout(new BorderLayout(0, 0));

        {
            tree = new JTree();
            contentPanel.add(tree);
        }
        {
            JPanel buttonPane = new JPanel();
            buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
            getContentPane().add(buttonPane, BorderLayout.SOUTH);
            {
                JButton okButton = new JButton("OK");
                okButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent arg0) {
                        DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
                        if (node == null)
                            return;
                        Object userObject = node.getUserObject();

                        ref.setValue(userObject);
                        MyDialog.this.dispose();
                    }
                });
                okButton.setActionCommand("OK");
                buttonPane.add(okButton);
                getRootPane().setDefaultButton(okButton);
            }
            {
                JButton cancelButton = new JButton("Cancel");
                cancelButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent arg0) {
                        MyDialog.this.dispose();
                    }
                });
                cancelButton.setActionCommand("Cancel");
                buttonPane.add(cancelButton);
            }
        }
    }
}

App will deply a Dialog with a tree. If you select a tree node and hit "ok" it'll close the dialog and show the value in the App's textfield. "cancel" will abort the whole process. It works for me.

hope it helps


问:
How can I replace two double quotes with one double quotes using Regex without capturing occurrences of one double quote?
I'm trying to do a replace on a JSON string. Something like this:

```<code>'{"val1":"1","val2":"2"","val3":"","val4":""}'
</code>```

Looking at the value tied to key "val2", I'm getting two double quotes together " 2 " ", but I can't fix that because that's how I get the JSON, I'm trying to replace those occurrences with 1 double quote: from "2"" to "2"

I'm doing replace() but I can't find the right regex to do it. I have tried this:

```<code>replace(/""/g, '"')
</code>```

If I do this it will replace "val3" and "val4" too.

This one doesn't work:

```<code>replace(/[^:]+"";/g, '"')
</code>```

I'm trying to accomplish replace(REGEX_HERE):
From "SomeCharactersHere"" to "SomeCharactersHere"

答:
Have you tried:

var s = '{"val1":"1","val2":"2"","val3":"","val4":""}';
s = s.replace(/([^:])\"\"/g, '$1\"')
console.log(s);```
</div>
</div>
</p>

<p>This matches some non-colon character followed by a set of double-double-quotes and replaces it with the originally found non-colon character along with a single-double-quotes.</p>

<p>Per a suggestion by ctwheels:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var s = '{"val1":"1","val2":"2"","val3":"","val4":""}';
s = s.replace(/([^:]")"+/g, '$1')
console.log(s);</code>```

As mentioned, it will capture the possibility of more than one extraneous double-quote and simplifies the replacement to just $1. Thanks!

Body:
I'm trying to do a replace on a JSON string. Something like this:

'{"val1":"1","val2":"2"","val3":"","val4":""}'

Looking at the value tied to key "val2", I'm getting two double quotes together " 2 " ", but I can't fix that because that's how I get the JSON, I'm trying to replace those occurrences with 1 double quote: from "2"" to "2"

I'm doing replace() but I can't find the right regex to do it. I have tried this:

replace(/""/g, '"')

If I do this it will replace "val3" and "val4" too.

This one doesn't work:

replace(/[^:]+"";/g, '"')

I'm trying to accomplish replace(REGEX_HERE):
From "SomeCharactersHere"" to "SomeCharactersHere"

Body:
Have you tried:

var s = '{"val1":"1","val2":"2"","val3":"","val4":""}';
s = s.replace(/([^:])\"\"/g, '$1\"')
console.log(s);

This matches some non-colon character followed by a set of double-double-quotes and replaces it with the originally found non-colon character along with a single-double-quotes.

Per a suggestion by ctwheels:

var s = '{"val1":"1","val2":"2"","val3":"","val4":""}';
s = s.replace(/([^:]")"+/g, '$1')
console.log(s);

As mentioned, it will capture the possibility of more than one extraneous double-quote and simplifies the replacement to just $1. Thanks!


问:
Would it be wise to serve static content on a cookie-free domain in SSL?
I have long read about "Use cookie-free domains" aka create a subdomain that can serve css, js, and images, all in 1 subdomain.

However 99% of our site is served via ssl, and ssl certificates can be expensive.

And so if we did this cookie-free subdomain, and to avoid that error that says "This page contains both secure and nonsecure items" error, we'd have to have ssl on the cookie-free subdomain.

Have any of you done similar things?

Would it really be worth the cost, to setup a 2nd ssl subdomain to host all the css, images, and javascript for all of our sites?

Thank you.

答:
No.

If you use HTTPS, you can probably also use HTTP/2, which avoids re-sending cookies unnecessarily, so the problem goes away.

There's a significant cost of opening a new TLS connection to a domain for the first time, so the more domains you use, the more first-connection overhead you pay for.

Unless your cookies are very large or you have lots and lots of requests, then the cost of establishing an additional TLS connection is likely to be greater than the cost of sending cookies on an already-open connection.

BTW: when using HTTPS be sure to add an HTTP header that explicitly allows caching (e.g. Cache-Control:public, max-age=604800), because otherwise browsers may not cache anything and waste bandwidth re-downloading files over and over again.


问:
.NET MVC Core 2 Deployment Issue on IIS 10
I am trying to deploy my ASP.NET MVC Core 2 site to a Windows Server 2016 server running IIS 10 and I am getting the following error in the Application Logs.

I have researched the issue and found this .NET Core app unable to start in IIS due to ErrorCode = '0x80004005 : 80008083 question which has an answer that reads, "As VS2017 RC is shipped with the new version of .NET Core SDK (.NET Core 1.0.4 SDK 1.0.1), you need to update framework on server as well."

I have tried installing both the SDK and runtime on the server as advised in the answer above but I am still receiving the error when I navigate to the site.

How can I resolve this issue?

```<code>Faulting application name: dotnet.exe, version: 2.0.25816.2, time stamp: 0x59e535ea
Faulting module name: coreclr.dll, version: 4.6.25815.2, time stamp: 0x59e2b767
Exception code: 0xc00000fd
Fault offset: 0x000000000008247a
Faulting process id: 0x1c68
Faulting application start time: 0x01d36aeaea2429cf
Faulting application path: C:\Program Files\dotnet\dotnet.exe
Faulting module path: C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.0.3\coreclr.dll
Report Id: 100b3c83-7509-487e-b1cd-6a0357f8b7e7
Faulting package full name:
Faulting package-relative application ID:
</code>```

答:
Running the following command revealed the true error:

```<code>C:\Windows\system32>"C:\Program Files\dotnet\dotnet" C:\inetpub\wwwroot\{YOUR_IIS_SITE_NAME}\{YOUR_PROJECT_NAME}.dll
</code>```

The result in the command prompt was the following which told me I had an error in my connection string:

```<code>C:\Windows\system32>"C:\Program Files\dotnet\dotnet" C:\inetpub\wwwroot\www_projectx_com\ProjectX.dll
info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
      User profile is available. Using 'C:\Users\darchual\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[58]
      Creating key {70b30c91-49df-45be-95cc-2e681b5cde76} with creation date 2017-12-04 16:34:08Z, activation date 2017-12-04 16:34:08Z, and expiration date 2018-03-04 16:34:08Z.
info: Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository[39]
      Writing data to file 'C:\Users\darchual\AppData\Local\ASP.NET\DataProtection-Keys\key-70b30c91-49df-45be-95cc-2e681b5cde76.xml'.

Unhandled Exception: System.ArgumentNullException: Value cannot be null.
Parameter name: connectionString
   at Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(String value, String parameterName)
   at Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuilder, String connectionString, Action`1 sqlServerOptionsAction)
   at ProjectX.Startup.<ConfigureServices>b__4_0(DbContextOptionsBuilder options) in C:\VSO\Avvenire Source\Internal\Project X\ProjectX\Startup.cs:line 35
   ... truncated for brevity ...
</code>```

Once resolved the application ran perfectly!

Also, keep in mind (when hosting an MVC Core app on IIS) to update your Program.cs file accordingly:

```<code>public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseIISIntegration()
            .UseStartup<Startup>()
            .Build();
}
</code>```

Last, but not least, I needed to fix the connection string by adding a newly created SQL user (it wouldn't work simply using integrated security):

```<code>"ConnectionStrings": {
    "DefaultConnection": "Server={theserver};Database={thedatabase};MultipleActiveResultSets=true;User Id={theusername};Password={thepassword};"
},
</code>```

Ref. https://stackoverflow.com/a/42363471/1477388

Body:
I am trying to deploy my ASP.NET MVC Core 2 site to a Windows Server 2016 server running IIS 10 and I am getting the following error in the Application Logs.

I have researched the issue and found this .NET Core app unable to start in IIS due to ErrorCode = '0x80004005 : 80008083 question which has an answer that reads, "As VS2017 RC is shipped with the new version of .NET Core SDK (.NET Core 1.0.4 SDK 1.0.1), you need to update framework on server as well."

I have tried installing both the SDK and runtime on the server as advised in the answer above but I am still receiving the error when I navigate to the site.

How can I resolve this issue?

Faulting application name: dotnet.exe, version: 2.0.25816.2, time stamp: 0x59e535ea
Faulting module name: coreclr.dll, version: 4.6.25815.2, time stamp: 0x59e2b767
Exception code: 0xc00000fd
Fault offset: 0x000000000008247a
Faulting process id: 0x1c68
Faulting application start time: 0x01d36aeaea2429cf
Faulting application path: C:\Program Files\dotnet\dotnet.exe
Faulting module path: C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.0.3\coreclr.dll
Report Id: 100b3c83-7509-487e-b1cd-6a0357f8b7e7
Faulting package full name:
Faulting package-relative application ID:

Body:
Running the following command revealed the true error:

C:\Windows\system32>"C:\Program Files\dotnet\dotnet" C:\inetpub\wwwroot\{YOUR_IIS_SITE_NAME}\{YOUR_PROJECT_NAME}.dll

The result in the command prompt was the following which told me I had an error in my connection string:

C:\Windows\system32>"C:\Program Files\dotnet\dotnet" C:\inetpub\wwwroot\www_projectx_com\ProjectX.dll
info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
      User profile is available. Using 'C:\Users\darchual\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[58]
      Creating key {70b30c91-49df-45be-95cc-2e681b5cde76} with creation date 2017-12-04 16:34:08Z, activation date 2017-12-04 16:34:08Z, and expiration date 2018-03-04 16:34:08Z.
info: Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository[39]
      Writing data to file 'C:\Users\darchual\AppData\Local\ASP.NET\DataProtection-Keys\key-70b30c91-49df-45be-95cc-2e681b5cde76.xml'.

Unhandled Exception: System.ArgumentNullException: Value cannot be null.
Parameter name: connectionString
   at Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(String value, String parameterName)
   at Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuilder, String connectionString, Action`1 sqlServerOptionsAction)
   at ProjectX.Startup.<ConfigureServices>b__4_0(DbContextOptionsBuilder options) in C:\VSO\Avvenire Source\Internal\Project X\ProjectX\Startup.cs:line 35
   ... truncated for brevity ...

Once resolved the application ran perfectly!

Also, keep in mind (when hosting an MVC Core app on IIS) to update your Program.cs file accordingly:

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseIISIntegration()
            .UseStartup<Startup>()
            .Build();
}

Last, but not least, I needed to fix the connection string by adding a newly created SQL user (it wouldn't work simply using integrated security):

"ConnectionStrings": {
    "DefaultConnection": "Server={theserver};Database={thedatabase};MultipleActiveResultSets=true;User Id={theusername};Password={thepassword};"
},

Ref. https://stackoverflow.com/a/42363471/1477388


问:
Uploading files using js fileReader results in corrupted files
I am trying to upload a file using js file reader and AJAX to my server.

I used FileAPI and fileReader to read the file and convert it to string and then send it to the server via an AJAX request.
Here is my client side js code :

```<code>function upload() {
    var file = document.getElementById('periodExcel').files[0];
    if (file) {
        console.log(file);
        var reader = new FileReader();
        reader.readAsText(file, file.type);
        console.log(reader);
        reader.onload = uploadAndRun;
    }
}
function uploadAndRun(event) {
    console.log(event);
    var result = event.target.result;
    $('#js').html(result);
    var fileName = document.getElementById('periodExcel').files[0].name; //Should be 'picture.jpg'

    $.post('./upload.php', {data: result, name: fileName}, function(result2){
        $('#php').html(result2);
    });
}
</code>```

Here is the upload php script:

```<code>file_put_contents('upload/' . $_POST['name'], $_POST['data']);
</code>```

it just write the file using php file_put_contents function.

My problem is that the uploaded file is corrupted and has a different size than the original file (it is larger).

I tried to use php file_get_contents function to read the same file and write it again using file_put_contents and the result file was fine and same as the original one.

I then tried to compare the two strings (the one that comes from the file reader and the one that comes from file_get_contents ) and compares the two strings using strcmp, that gives me that the string that come from the fileReader is larger than the one comes from file_get_contents.

So, what is the problem with my code and how to use the FileReader to upload file in this way while using readAsText function.

答:
You are using the wrong collection in PHP. To access uploaded file stream use $_FILES.
See here:
http://php.net/manual/en/reserved.variables.files.php

and here: http://php.net/manual/en/features.file-upload.post-method.php

In short, PHP runtime takes care of reading the upload stream from the HTTP request, stores it locally in a temp folder and exposes the above map for you to access the temp file and possibly move it to another location (or do whatever else you need to do with it).

Body:
I am trying to upload a file using js file reader and AJAX to my server.

I used FileAPI and fileReader to read the file and convert it to string and then send it to the server via an AJAX request.
Here is my client side js code :

function upload() {
    var file = document.getElementById('periodExcel').files[0];
    if (file) {
        console.log(file);
        var reader = new FileReader();
        reader.readAsText(file, file.type);
        console.log(reader);
        reader.onload = uploadAndRun;
    }
}
function uploadAndRun(event) {
    console.log(event);
    var result = event.target.result;
    $('#js').html(result);
    var fileName = document.getElementById('periodExcel').files[0].name; //Should be 'picture.jpg'

    $.post('./upload.php', {data: result, name: fileName}, function(result2){
        $('#php').html(result2);
    });
}

Here is the upload php script:

file_put_contents('upload/' . $_POST['name'], $_POST['data']);

it just write the file using php file_put_contents function.

My problem is that the uploaded file is corrupted and has a different size than the original file (it is larger).

I tried to use php file_get_contents function to read the same file and write it again using file_put_contents and the result file was fine and same as the original one.

I then tried to compare the two strings (the one that comes from the file reader and the one that comes from file_get_contents ) and compares the two strings using strcmp, that gives me that the string that come from the fileReader is larger than the one comes from file_get_contents.

So, what is the problem with my code and how to use the FileReader to upload file in this way while using readAsText function.


答:
This is one way of doing it:

```<code>;WITH Tally AS (
   SELECT ROW_NUMBER() OVER (ORDER BY t1.n) AS n
   FROM (VALUES (1), (1), (1), (1), (1), (1), (1), (1)) AS t1(n)
   CROSS JOIN (VALUES (1), (1), (1), (1), (1), (1), (1), (1)) AS t2(n)
)
SELECT x.d AS WeeklyDate, COALESCE(z.running_total, 0) AS WeeklyValue
FROM Tally AS t
CROSS APPLY (SELECT DATEADD (DAY, (t.n - 1) * 7, '2017-04-01')) AS x(d)
OUTER APPLY (
   SELECT SUM(Value) AS running_total
   FROM mytable
   WHERE [Date] <= x.d) AS z
</code>```

The query uses a tally table created by a CTE. It is large enough to accommodate more than the week number of a whole year.

Using the numbers of the tally table, a CROSS APPLY operation calculates the weekly date value up to which the running total is calculated.

The OUTER APPLY performs a SUM aggregation to obtain the actual value of the running total.

Demo here

Title: Cumulative Sum of values of a table in SQL Server

Body:
I have a table as below

    Date            Value
    ----------      -----
    02-04-2017      20
    04-04-2017      10
    09-04-2017      15
    14-04-2017      8
    25-04-2017      3
    28-04-2017      2
    02-05-2017      5

Expected output:

    WeeklyDate   WeeklyValue
    -----------  ------------
    01-04-2017   0
    08-04-2017   30
    15-04-2017   53
    22-04-2017   53
    29-04-2017   58
    06-05-2017   63

I want the output with dates with 7 days interval starting from 1st of the month and cumulative sum of values.

Kindly help!!

Body:
This is one way of doing it:

;WITH Tally AS (
   SELECT ROW_NUMBER() OVER (ORDER BY t1.n) AS n
   FROM (VALUES (1), (1), (1), (1), (1), (1), (1), (1)) AS t1(n)
   CROSS JOIN (VALUES (1), (1), (1), (1), (1), (1), (1), (1)) AS t2(n)
)
SELECT x.d AS WeeklyDate, COALESCE(z.running_total, 0) AS WeeklyValue
FROM Tally AS t
CROSS APPLY (SELECT DATEADD (DAY, (t.n - 1) * 7, '2017-04-01')) AS x(d)
OUTER APPLY (
   SELECT SUM(Value) AS running_total
   FROM mytable
   WHERE [Date] <= x.d) AS z

The query uses a tally table created by a CTE. It is large enough to accommodate more than the week number of a whole year.

Using the numbers of the tally table, a CROSS APPLY operation calculates the weekly date value up to which the running total is calculated.

The OUTER APPLY performs a SUM aggregation to obtain the actual value of the running total.

Demo here


问:
if statement in Django template issue
I am trying to compare value inside template of django. if statement is not working
here is my code
Model class:

```<code>class Run(models.Model):
    run_id = models.AutoField(primary_key=True)
    run_name = models.CharField(unique=True, max_length=30)
    pms_id = models.ForeignKey('ProcessManagementSystem', db_column = 'pms_id')

def __unicode__(self):
    return self.run_name

class ProcessManagementSystem(models.Model):
    pms_id = models.AutoField(primary_key=True)
    pms_name = models.CharField(unique=True, max_length=30)

def __unicode__(self):
       return self.pms_name
</code>```

My template

```<code>{% for run in all_runs %}
        {{run.pms_id}}
        {% if run.pms_id == "PMSName1" %}
                    {{run.pms_id}}
        {% endif %}
{% endfor %}
</code>```

the interesting thing is when I am printing {{run.pms_id}} , it is not showing the ID, It is showing pms_name (maybe because of return self.pms_name)

So during compare, I am trying to compare with name i.e. "PMSName1" instead of id But still no luck.
Any suggestion how to compare?

Thanks

答:
Pms_id is an object so if you want to get the id or the name do something like:

```<code>{% if run.pms_id.pms_id == 1 %} or {% if run.pms_id.pms_name == "PMSName1" %}
</code>```

Title: if statement in Django template issue

Body:
I am trying to compare value inside template of django. if statement is not working
here is my code
Model class:

class Run(models.Model):
    run_id = models.AutoField(primary_key=True)
    run_name = models.CharField(unique=True, max_length=30)
    pms_id = models.ForeignKey('ProcessManagementSystem', db_column = 'pms_id')

def __unicode__(self):
    return self.run_name

class ProcessManagementSystem(models.Model):
    pms_id = models.AutoField(primary_key=True)
    pms_name = models.CharField(unique=True, max_length=30)

def __unicode__(self):
       return self.pms_name

My template

{% for run in all_runs %}
        {{run.pms_id}}
        {% if run.pms_id == "PMSName1" %}
                    {{run.pms_id}}
        {% endif %}
{% endfor %}

the interesting thing is when I am printing {{run.pms_id}} , it is not showing the ID, It is showing pms_name (maybe because of return self.pms_name)

So during compare, I am trying to compare with name i.e. "PMSName1" instead of id But still no luck.
Any suggestion how to compare?

Thanks

Body:
Pms_id is an object so if you want to get the id or the name do something like:

{% if run.pms_id.pms_id == 1 %} or {% if run.pms_id.pms_name == "PMSName1" %}


问:
perl regex match using global switch
I am trying to match a word that starts with a letter and is followed by at .

I use this regex for it

```<code>use strict;
use warnings;

use Data::Dumper;

my $str = "fat 123 cat sat on the mat";

my @a = $str =~ /(\s?[a-z]{1,2}(at)\s?)/g;

print Dumper( @a );
</code>```

the out put I am getting is:

```<code>$ perl ~/playground/regex.pl
$VAR1 = 'fat ';
$VAR2 = 'at';
$VAR3 = ' cat ';
$VAR4 = 'at';
$VAR5 = 'sat ';
$VAR6 = 'at';
$VAR7 = ' mat';
$VAR8 = 'at';
</code>```

why does it match "at" as well when I clearly say match just 1 character before at.

答:
Your optional spaces aren't a good way to delimit words: they are optional

Use the word boundary construct \b for a rough match to the ends of words

```<code>use strict;
use warnings;

use Data::Dumper;

my $str = "fat 123 cat sat on the mat";

my @aa = $str =~ /\b[a-z]+at\b/gi;

print Dumper \@aa;
</code>```

output

```<code>$VAR1 = [
          'fat',
          'cat',
          'sat',
          'mat'
        ];
</code>```

If you want to be more clever and be certain that the word found isn't preceded or followed by a non-space character then you can write this instead

```<code>my @aa = $str =~ /(?<!\S)[a-z]+at(?!\S)/gi;
</code>```

which produces the same result for the data you show

Title: perl regex match using global switch

Body:
I am trying to match a word that starts with a letter and is followed by at .

I use this regex for it

use strict;
use warnings;

use Data::Dumper;

my $str = "fat 123 cat sat on the mat";

my @a = $str =~ /(\s?[a-z]{1,2}(at)\s?)/g;

print Dumper( @a );

the out put I am getting is:

$ perl ~/playground/regex.pl
$VAR1 = 'fat ';
$VAR2 = 'at';
$VAR3 = ' cat ';
$VAR4 = 'at';
$VAR5 = 'sat ';
$VAR6 = 'at';
$VAR7 = ' mat';
$VAR8 = 'at';

why does it match "at" as well when I clearly say match just 1 character before at.

Body:
Your optional spaces aren't a good way to delimit words: they are optional

Use the word boundary construct \b for a rough match to the ends of words

use strict;
use warnings;

use Data::Dumper;

my $str = "fat 123 cat sat on the mat";

my @aa = $str =~ /\b[a-z]+at\b/gi;

print Dumper \@aa;

output

$VAR1 = [
          'fat',
          'cat',
          'sat',
          'mat'
        ];

If you want to be more clever and be certain that the word found isn't preceded or followed by a non-space character then you can write this instead

my @aa = $str =~ /(?<!\S)[a-z]+at(?!\S)/gi;

which produces the same result for the data you show