问:
Count occurrences per data.table row
I have a data.table too large to melt/cast in RAM (millions of rows).

From that I need to extract the rows that do not have duplicate values per row. Duplicate zeros and NA are ok to keep.

In this MWE, the "Duplicates"-column is what I want to calculate.

```<code>DT <- data.table(C1=c(0L, 7L, 0L, 0L),
                 C2=c(0L, 0L, 0L, 4L),
                 C3=c(2L, 0L, 2L, 3L),
                 C4=c(0L, NA_integer_, 2L, 6L),
                 C5=c(1L, 3L, 1L, 1L),
                 c6=c(0L, 4L, 2L, 4L),
                 Duplicates=c(FALSE, FALSE, TRUE, TRUE))

DT.wanted <- DT[Duplicates==FALSE, ]
</code>```

Number of columns vary.

Edit: Here is a for-loop example. Is way too slow.

```<code>DT <- data.table(C1=c(0L, 7L, 0L, 0L),
                 C2=c(0L, 0L, 0L, 4L),
                 C3=c(2L, 0L, 2L, 3L),
                 C4=c(0L, NA_integer_, 2L, 6L),
                 C5=c(1L, 3L, 1L, 1L),
                 c6=c(0L, 4L, 2L, 4L))
DT[, Duplicates:=FALSE]
for (i in 1L:nrow(DT)){
  dt.i <- data.table(table(as.integer(DT[i, ])))
  if (max(dt.i[V1>0, N])>1) DT[i, Duplicates:=TRUE]
}
</code>```

答:
here is another data.table go at things...

```<code>DT[ lapply( data.table::transpose( DT ),
            function(x) anyDuplicated( x[!is.na(x) & !x == 0] ) ) == 0, ]
</code>```

Not sure how it holds up memory-wise.. but is is waaaaay faster than for-looping..

benchmark

```<code># Unit: microseconds
#      expr     min         lq      mean    median         uq       max neval
#      loop 11764.5 12164.2010 13987.589 12725.601 13775.0010 25885.601   100
# transpose   524.5   550.3515   592.633   566.601   597.4515  1116.201   100
</code>```

benchmark-code

```<code>mydata <- data.table(C1=c(0L, 7L, 0L, 0L),
                 C2=c(0L, 0L, 0L, 4L),
                 C3=c(2L, 0L, 2L, 3L),
                 C4=c(0L, NA_integer_, 2L, 6L),
                 C5=c(1L, 3L, 1L, 1L),
                 C6=c(0L, 4L, 2L, 4L))

microbenchmark::microbenchmark(
 loop = {
   DT <- copy(mydata)
   DT[, Duplicates:=FALSE]
   for (i in 1L:nrow(DT)){
     dt.i <- data.table(table(as.integer(DT[i, ])))
     if (max(dt.i[V1>0, N])>1) DT[i, Duplicates:=TRUE]
   }
 },
 transpose = {
   DT <- copy(mydata)
   DT[ lapply( transpose(DT), function(x) anyDuplicated( x[!is.na(x) & ! x == 0] ) ) == 0, ]
 },times = 100L )
</code>```

Title: Count occurrences per data.table row

Body:
I have a data.table too large to melt/cast in RAM (millions of rows).

From that I need to extract the rows that do not have duplicate values per row. Duplicate zeros and NA are ok to keep.

In this MWE, the "Duplicates"-column is what I want to calculate.

DT <- data.table(C1=c(0L, 7L, 0L, 0L),
                 C2=c(0L, 0L, 0L, 4L),
                 C3=c(2L, 0L, 2L, 3L),
                 C4=c(0L, NA_integer_, 2L, 6L),
                 C5=c(1L, 3L, 1L, 1L),
                 c6=c(0L, 4L, 2L, 4L),
                 Duplicates=c(FALSE, FALSE, TRUE, TRUE))

DT.wanted <- DT[Duplicates==FALSE, ]

Number of columns vary.

Edit: Here is a for-loop example. Is way too slow.

DT <- data.table(C1=c(0L, 7L, 0L, 0L),
                 C2=c(0L, 0L, 0L, 4L),
                 C3=c(2L, 0L, 2L, 3L),
                 C4=c(0L, NA_integer_, 2L, 6L),
                 C5=c(1L, 3L, 1L, 1L),
                 c6=c(0L, 4L, 2L, 4L))
DT[, Duplicates:=FALSE]
for (i in 1L:nrow(DT)){
  dt.i <- data.table(table(as.integer(DT[i, ])))
  if (max(dt.i[V1>0, N])>1) DT[i, Duplicates:=TRUE]
}

Body:
here is another data.table go at things...

DT[ lapply( data.table::transpose( DT ),
            function(x) anyDuplicated( x[!is.na(x) & !x == 0] ) ) == 0, ]

Not sure how it holds up memory-wise.. but is is waaaaay faster than for-looping..

benchmark

# Unit: microseconds
#      expr     min         lq      mean    median         uq       max neval
#      loop 11764.5 12164.2010 13987.589 12725.601 13775.0010 25885.601   100
# transpose   524.5   550.3515   592.633   566.601   597.4515  1116.201   100

benchmark-code

mydata <- data.table(C1=c(0L, 7L, 0L, 0L),
                 C2=c(0L, 0L, 0L, 4L),
                 C3=c(2L, 0L, 2L, 3L),
                 C4=c(0L, NA_integer_, 2L, 6L),
                 C5=c(1L, 3L, 1L, 1L),
                 C6=c(0L, 4L, 2L, 4L))

microbenchmark::microbenchmark(
 loop = {
   DT <- copy(mydata)
   DT[, Duplicates:=FALSE]
   for (i in 1L:nrow(DT)){
     dt.i <- data.table(table(as.integer(DT[i, ])))
     if (max(dt.i[V1>0, N])>1) DT[i, Duplicates:=TRUE]
   }
 },
 transpose = {
   DT <- copy(mydata)
   DT[ lapply( transpose(DT), function(x) anyDuplicated( x[!is.na(x) & ! x == 0] ) ) == 0, ]
 },times = 100L )


来源: stackexchange

问:
cmake transitive usage: propagate libs but keep headers private
If I create a static lib like this:

```<code>add_library(mylib STATIC
    mylib.h
    mylib.cpp
)
</code>```

mylib.cpp includes headers from another library, let's call it koko.

Whoever uses mylib, needs to link to koko as well, but doesn't need to see the headers of koko.

But if I do this:

```<code>target_link_libraries(mylib PUBLIC koko)
</code>```

Anyone using mylib will also see the headers of koko

How do I make it so that if a target uses mylib would link to koko but not see its headers?

答:
This is exactly what PRIVATE linking does. It propagates libraries and keeps headers private.

```<code>target_link_libraries(mylib PRIVATE koko)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If I create a static lib like this:

add_library(mylib STATIC
    mylib.h
    mylib.cpp
)

mylib.cpp includes headers from another library, let's call it koko.

Whoever uses mylib, needs to link to koko as well, but doesn't need to see the headers of koko.

But if I do this:

target_link_libraries(mylib PUBLIC koko)

Anyone using mylib will also see the headers of koko

How do I make it so that if a target uses mylib would link to koko but not see its headers?

Body:
This is exactly what PRIVATE linking does. It propagates libraries and keeps headers private.

target_link_libraries(mylib PRIVATE koko)


问:
NestedScrollView body keeps scrolling even if empty space is available
My requirement is to create a page with collapsing toolbar and two tabs.
To do this, I am using the code below.

```<code>SafeArea(
        child: DefaultTabController(
          length: 2,
          child: NestedScrollView(
            headerSliverBuilder:
                (BuildContext context, bool innerBoxIsScrolled) {
              return [
                SliverPersistentHeader(
                  pinned: true,
                  delegate: _Header(),
                )
              ];
            },
            body: TabBarView(
              children: <Widget>[
                Container1(),
                Container2(),
              ],
            ),
          ),
        ),
      )
</code>```

Everything works, but once the scrolling starts and the header collapses, the body keeps on scrolling even if all the widgets are visible.

How do I make it behave like Android native, where if the list is small in size, the list doesn't scroll after the header collapses.

答:
For anyone who is facing the same issue, this is how I fixed it.
You can just copy the entire code and run it to check and modify accordingly.
The code is taken from the official documentation.</p>

```<code>import 'dart:convert';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_module/app_constants.dart';
import 'package:flutter_module/data/local/shared_pref.dart';
import 'package:flutter_module/data/remote/api_end_points.dart';
import 'package:flutter_module/string_localization.dart';
import 'package:flutter_module/ui/router.dart';
import 'package:flutter_module/util.dart';
import 'package:http/http.dart' as http;

import 'data/local/dao/sync_dao.dart';
import 'data/remote/response_pojo/video_challenges_response.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MainCollapsingToolbar(),
    );
  }
}

class MainCollapsingToolbar extends StatefulWidget {
  @override
  _MainCollapsingToolbarState createState() => _MainCollapsingToolbarState();
}

class _MainCollapsingToolbarState extends State<MainCollapsingToolbar> {
  @override
  Widget build(BuildContext context) {
    var _tabs = ["One", "Two"];
    return Scaffold(
      body: DefaultTabController(
        length: _tabs.length, // This is the number of tabs.
        child: NestedScrollView(
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
            // These are the slivers that show up in the "outer" scroll view.
            return <Widget>[
              SliverOverlapAbsorber(
                // This widget takes the overlapping behavior of the SliverAppBar,
                // and redirects it to the SliverOverlapInjector below. If it is
                // missing, then it is possible for the nested "inner" scroll view
                // below to end up under the SliverAppBar even when the inner
                // scroll view thinks it has not been scrolled.
                // This is not necessary if the "headerSliverBuilder" only builds
                // widgets that do not overlap the next sliver.
                handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
                child: SliverPersistentHeader(
                  pinned: true,
                  delegate: _SliverAppBarDelegate(minHeight: 100, maxHeight: 150, child: Container(
                    color: Colors.blue,
                  )),
                ),
              ),
            ];
          },
          body: TabBarView(
            // These are the contents of the tab views, below the tabs.
            children: _tabs.map((String name) {
              return SafeArea(
                top: false,
                bottom: false,
                child: Builder(
                  // This Builder is needed to provide a BuildContext that is
                  // "inside" the NestedScrollView, so that
                  // sliverOverlapAbsorberHandleFor() can find the
                  // NestedScrollView.
                  builder: (BuildContext context) {
                    return CustomScrollView(
                      // The "controller" and "primary" members should be left
                      // unset, so that the NestedScrollView can control this
                      // inner scroll view.
                      // If the "controller" property is set, then this scroll
                      // view will not be associated with the NestedScrollView.
                      // The PageStorageKey should be unique to this ScrollView;
                      // it allows the list to remember its scroll position when
                      // the tab view is not on the screen.
                      key: PageStorageKey<String>(name),
                      slivers: <Widget>[
                        SliverOverlapInjector(
                          // This is the flip side of the SliverOverlapAbsorber
                          // above.
                          handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
                        ),
                        SliverPadding(
                          padding: const EdgeInsets.all(8.0),
                          // In this example, the inner scroll view has
                          // fixed-height list items, hence the use of
                          // SliverFixedExtentList. However, one could use any
                          // sliver widget here, e.g. SliverList or SliverGrid.
                          sliver: SliverFixedExtentList(
                            // The items in this example are fixed to 48 pixels
                            // high. This matches the Material Design spec for
                            // ListTile widgets.
                            itemExtent: 48.0,
                            delegate: SliverChildBuilderDelegate(
                                  (BuildContext context, int index) {
                                // This builder is called for each child.
                                // In this example, we just number each list item.
                                return ListTile(
                                  title: Text('Item $index'),
                                );
                              },
                              // The childCount of the SliverChildBuilderDelegate
                              // specifies how many children this inner list
                              // has. In this example, each tab has a list of
                              // exactly 30 items, but this is arbitrary.
                              childCount: 1,
                            ),
                          ),
                        ),
                      ],
                    );
                  },
                ),
              );
            }).toList(),
          ),
        ),
      ),
    );
  }
}
</code>```

Body:
My requirement is to create a page with collapsing toolbar and two tabs.
To do this, I am using the code below.

SafeArea(
        child: DefaultTabController(
          length: 2,
          child: NestedScrollView(
            headerSliverBuilder:
                (BuildContext context, bool innerBoxIsScrolled) {
              return [
                SliverPersistentHeader(
                  pinned: true,
                  delegate: _Header(),
                )
              ];
            },
            body: TabBarView(
              children: <Widget>[
                Container1(),
                Container2(),
              ],
            ),
          ),
        ),
      )

Everything works, but once the scrolling starts and the header collapses, the body keeps on scrolling even if all the widgets are visible.

How do I make it behave like Android native, where if the list is small in size, the list doesn't scroll after the header collapses.

Body:
For anyone who is facing the same issue, this is how I fixed it.
You can just copy the entire code and run it to check and modify accordingly.
The code is taken from the official documentation.

import 'dart:convert';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_module/app_constants.dart';
import 'package:flutter_module/data/local/shared_pref.dart';
import 'package:flutter_module/data/remote/api_end_points.dart';
import 'package:flutter_module/string_localization.dart';
import 'package:flutter_module/ui/router.dart';
import 'package:flutter_module/util.dart';
import 'package:http/http.dart' as http;

import 'data/local/dao/sync_dao.dart';
import 'data/remote/response_pojo/video_challenges_response.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MainCollapsingToolbar(),
    );
  }
}

class MainCollapsingToolbar extends StatefulWidget {
  @override
  _MainCollapsingToolbarState createState() => _MainCollapsingToolbarState();
}

class _MainCollapsingToolbarState extends State<MainCollapsingToolbar> {
  @override
  Widget build(BuildContext context) {
    var _tabs = ["One", "Two"];
    return Scaffold(
      body: DefaultTabController(
        length: _tabs.length, // This is the number of tabs.
        child: NestedScrollView(
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
            // These are the slivers that show up in the "outer" scroll view.
            return <Widget>[
              SliverOverlapAbsorber(
                // This widget takes the overlapping behavior of the SliverAppBar,
                // and redirects it to the SliverOverlapInjector below. If it is
                // missing, then it is possible for the nested "inner" scroll view
                // below to end up under the SliverAppBar even when the inner
                // scroll view thinks it has not been scrolled.
                // This is not necessary if the "headerSliverBuilder" only builds
                // widgets that do not overlap the next sliver.
                handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
                child: SliverPersistentHeader(
                  pinned: true,
                  delegate: _SliverAppBarDelegate(minHeight: 100, maxHeight: 150, child: Container(
                    color: Colors.blue,
                  )),
                ),
              ),
            ];
          },
          body: TabBarView(
            // These are the contents of the tab views, below the tabs.
            children: _tabs.map((String name) {
              return SafeArea(
                top: false,
                bottom: false,
                child: Builder(
                  // This Builder is needed to provide a BuildContext that is
                  // "inside" the NestedScrollView, so that
                  // sliverOverlapAbsorberHandleFor() can find the
                  // NestedScrollView.
                  builder: (BuildContext context) {
                    return CustomScrollView(
                      // The "controller" and "primary" members should be left
                      // unset, so that the NestedScrollView can control this
                      // inner scroll view.
                      // If the "controller" property is set, then this scroll
                      // view will not be associated with the NestedScrollView.
                      // The PageStorageKey should be unique to this ScrollView;
                      // it allows the list to remember its scroll position when
                      // the tab view is not on the screen.
                      key: PageStorageKey<String>(name),
                      slivers: <Widget>[
                        SliverOverlapInjector(
                          // This is the flip side of the SliverOverlapAbsorber
                          // above.
                          handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
                        ),
                        SliverPadding(
                          padding: const EdgeInsets.all(8.0),
                          // In this example, the inner scroll view has
                          // fixed-height list items, hence the use of
                          // SliverFixedExtentList. However, one could use any
                          // sliver widget here, e.g. SliverList or SliverGrid.
                          sliver: SliverFixedExtentList(
                            // The items in this example are fixed to 48 pixels
                            // high. This matches the Material Design spec for
                            // ListTile widgets.
                            itemExtent: 48.0,
                            delegate: SliverChildBuilderDelegate(
                                  (BuildContext context, int index) {
                                // This builder is called for each child.
                                // In this example, we just number each list item.
                                return ListTile(
                                  title: Text('Item $index'),
                                );
                              },
                              // The childCount of the SliverChildBuilderDelegate
                              // specifies how many children this inner list
                              // has. In this example, each tab has a list of
                              // exactly 30 items, but this is arbitrary.
                              childCount: 1,
                            ),
                          ),
                        ),
                      ],
                    );
                  },
                ),
              );
            }).toList(),
          ),
        ),
      ),
    );
  }
}


问:
asp.net mvc client side validation
I've been tinkering with the client side validation features in ASP.net MVC after reading ScottGU's blog post on the subject. It's pretty easy to use the System.Componentmodel.DataAnnotations attributes like this:

```<code>    [Required(ErrorMessage = "You must specify a reason")]
    public string ReasonText { get; set; }
</code>```

... but what happens if you need something just a little more complex. What if you have an Address class with a PostalCode and CountryCode field. You would want to validate the postal code against a different regex for each country. [0-9]{5} works for the USA, but you need a different one for Canada.

I got around that by rolling my own ValidationService class that takes the ModelState property of the controller and validates it accordingly. This works great on the server side but doesn't work with the fancy new client side validation.

In Webforms I would use javascript-emitting controls like RequiredFieldValidator or CompareValidator for the easy stuff and then use a CustomValidator for the complex rules. This way I have all my validation logic in one place, and I get the benefit of rapid javascript validation for simple stuff (90% of the time) while I still get the security of server side validation as a backstop.

What would be the equivalent approach in MVC?

答:
I think solution to your problem is System.ComponentModel.DataAnnotations in MVC

For complex logic you can Implement your own  logic. Its very easy.
Have a look for customising on this link : http://msdn.microsoft.com/en-us/library/cc668224.aspx

For basic thing make you View Binded with Model Class and add attribute on top of properties...
Like

```<code>public class CustomerSearchDE
{
    [StringLength(2, ErrorMessageResourceType = typeof(Translation), ErrorMessageResourceName = MessageConstants.conCompanyNumberMaxLength)]
    public string CompanyNumber { get; set; }
 }
</code>```

View Strongly type with this Class

ContentLicense: CC BY-SA 2.5

Title: asp.net mvc client side validation

Body:
I've been tinkering with the client side validation features in ASP.net MVC after reading ScottGU's blog post on the subject. It's pretty easy to use the System.Componentmodel.DataAnnotations attributes like this:

    [Required(ErrorMessage = "You must specify a reason")]
    public string ReasonText { get; set; }

... but what happens if you need something just a little more complex. What if you have an Address class with a PostalCode and CountryCode field. You would want to validate the postal code against a different regex for each country. [0-9]{5} works for the USA, but you need a different one for Canada.

I got around that by rolling my own ValidationService class that takes the ModelState property of the controller and validates it accordingly. This works great on the server side but doesn't work with the fancy new client side validation.

In Webforms I would use javascript-emitting controls like RequiredFieldValidator or CompareValidator for the easy stuff and then use a CustomValidator for the complex rules. This way I have all my validation logic in one place, and I get the benefit of rapid javascript validation for simple stuff (90% of the time) while I still get the security of server side validation as a backstop.

What would be the equivalent approach in MVC?

Body:
I think solution to your problem is System.ComponentModel.DataAnnotations in MVC

For complex logic you can Implement your own  logic. Its very easy.
Have a look for customising on this link : http://msdn.microsoft.com/en-us/library/cc668224.aspx

For basic thing make you View Binded with Model Class and add attribute on top of properties...
Like

public class CustomerSearchDE
{
    [StringLength(2, ErrorMessageResourceType = typeof(Translation), ErrorMessageResourceName = MessageConstants.conCompanyNumberMaxLength)]
    public string CompanyNumber { get; set; }
 }

View Strongly type with this Class

ContentLicense: CC BY-SA 3.0


问:
Is there any way to tell angular-cli (for angular 2) to generate minified version of css?
As the title says, when I run "ng serve" angular-cli generates normal css whereas I expect to get the minified version.
Is there any specific setting to use for angular-cli-build, or some additional plugin to install and use?

This is my angular-cli-build.js

```<code>var Angular2App = require('angular-cli/lib/broccoli/angular2-app');

module.exports = function(defaults) {
  return new Angular2App(defaults, {
    vendorNpmFiles: [
      'systemjs/dist/system-polyfills.js',
      'systemjs/dist/system.src.js',
      'zone.js/dist/**/*.+(js|js.map)',
      'es6-shim/es6-shim.js',
      'reflect-metadata/**/*.+(ts|js|js.map)',
      'rxjs/**/*.+(js|js.map)',
      '@angular/**/*.+(js|js.map)',
      'angular2-cookie/**/*.js'
    ]
  });
};
</code>```

答:
In 2020 it is just enough to use <code>--prod</code> flag, when building project: </p>

```<code>ng build --prod
</code>```

Body:
As the title says, when I run "ng serve" angular-cli generates normal css whereas I expect to get the minified version.
Is there any specific setting to use for angular-cli-build, or some additional plugin to install and use?

This is my angular-cli-build.js

var Angular2App = require('angular-cli/lib/broccoli/angular2-app');

module.exports = function(defaults) {
  return new Angular2App(defaults, {
    vendorNpmFiles: [
      'systemjs/dist/system-polyfills.js',
      'systemjs/dist/system.src.js',
      'zone.js/dist/**/*.+(js|js.map)',
      'es6-shim/es6-shim.js',
      'reflect-metadata/**/*.+(ts|js|js.map)',
      'rxjs/**/*.+(js|js.map)',
      '@angular/**/*.+(js|js.map)',
      'angular2-cookie/**/*.js'
    ]
  });
};

Body:
In 2020 it is just enough to use --prod flag, when building project:

ng build --prod


问:
Using v-for in laravel + vue.js, am trying to display a table containing information of the user but nothing shows
```<code><script>
    export default {
        name: "OutPatient",
        data(){
            return{
                out_patients: {}
            }
        },
        methods: {
                index(){
                        axios.get('/data/out_patient').then(({data}) =>
                                (this.out_patients = data.data));

                },
                update(){}
        },
        created(){
                this.index();
        }

    }
</script>

<tr v-for="out_patient in out_patients" v-bind:key="out_patient.id">
    <td>{{out_patient.id}}</td>
    <td>{{out_patient.first_name}}</td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td>
      <a href="#"><i class="fa fa-edit blue"></i></a>
      |
      <a href="#"><i class="fa fa-trash red"></i></a>
    </td>
</tr>

</code>```

This is my code but the data is not showing in the table even though in the XHR the data shows there.

In the inspect element I can see the data but the v-for loop is unable to display the data.

答: can you try fetching the data on mounted life cycle hook instead of created in order to populate the table with data on page load mounted is the best hook lifecycle as much I know.</p>

Body:
    {{out_patient.id}}
    {{out_patient.first_name}}

      |

This is my code but the data is not showing in the table even though in the XHR the data shows there.

In the inspect element I can see the data but the v-for loop is unable to display the data.


问:
Golang bad file descriptor
I am getting a bad file descriptor when trying to append to a logging file within my go routine.

write ./log.log: bad file descriptor

The file exists and has 666 for permissions. At first I thought well maybe it is because each one of them is trying to open the file at the same time. I implemented a mutex to try and avoid that but got the same issue so I removed it.

```<code>logCh := make(chan string, 150)
go func() {
    for {
        msg, ok := <-logCh
        if ok {
            if f, err := os.OpenFile("./log.log", os.O_APPEND, os.ModeAppend); err != nil {
                panic(err)
            } else {
                logTime := time.Now().Format(time.RFC3339)
                if _, err := f.WriteString(logTime + " - " + msg); err != nil {
                    fmt.Print(err)
                }
                f.Close()
            }
        } else {
            fmt.Print("Channel closed! \n")
            break
        }
    }
}()
</code>```

答:
This appears to be a discrepancy between windows and linux.
On windows os.O_APPEND implies write access, as can be seen in the code in syscall_windows.go.

```<code>if mode&O_APPEND != 0 {
    access &^= GENERIC_WRITE
    access |= FILE_APPEND_DATA
}
</code>```

in linux the openflags are passed as-is to a linux syscall

So in DOS/WINDOWS you do not need to explicitly add a write flag with an append flag, as it is implied. (this has been default behaviour since the DOS days)
Go in linux does need the extra flag added to work.

(...but imo it should not need this flag, as appending implicitly implies that I want to write. Should I bugreport this to golang ?)

Title: Golang bad file descriptor

Body:
I am getting a bad file descriptor when trying to append to a logging file within my go routine.

write ./log.log: bad file descriptor

The file exists and has 666 for permissions. At first I thought well maybe it is because each one of them is trying to open the file at the same time. I implemented a mutex to try and avoid that but got the same issue so I removed it.

logCh := make(chan string, 150)
go func() {
    for {
        msg, ok := <-logCh
        if ok {
            if f, err := os.OpenFile("./log.log", os.O_APPEND, os.ModeAppend); err != nil {
                panic(err)
            } else {
                logTime := time.Now().Format(time.RFC3339)
                if _, err := f.WriteString(logTime + " - " + msg); err != nil {
                    fmt.Print(err)
                }
                f.Close()
            }
        } else {
            fmt.Print("Channel closed! \n")
            break
        }
    }
}()

Body:
This appears to be a discrepancy between windows and linux.
On windows os.O_APPEND implies write access, as can be seen in the code in syscall_windows.go.

if mode&O_APPEND != 0 {
    access &^= GENERIC_WRITE
    access |= FILE_APPEND_DATA
}

in linux the openflags are passed as-is to a linux syscall

So in DOS/WINDOWS you do not need to explicitly add a write flag with an append flag, as it is implied. (this has been default behaviour since the DOS days)
Go in linux does need the extra flag added to work.

(...but imo it should not need this flag, as appending implicitly implies that I want to write. Should I bugreport this to golang ?)


问:
Why does dir="rtl" change order, but only sometimes?
Why does

```<code><input type="text" dir="rtl" value="08/15 word">
</code>```

render into word 08/15 and not into 08/15 word?

Why does

```<code><input type="text" dir="rtl" value="one word">
</code>```

render into one word?

Why is the order switched in the first case but not in the second one?

https://jsfiddle.net/powtac/4aLn71mb/

答:
dir=rtl gives the base direction of the text. Within that text, words with Latin letters will still be written left-to-right and multiple words with Latin letters (i.e. English sentences) will be ordered left-to-right as well!

The same is true for e.g. Arabic in dir=ltr (default) base direction: it will be written right-to-left anyway, and multiple Arabic words will be ordered form right-to-left, even though the environment tells otherwise.

For that to work, the browser (or text renderer in general) uses the Unicode bidi algorithm. The algorithm by itself needs to know the directionality of the characters, which is part of Unicode as well. Latin and Arabic letters have a strong directionality, while the “normal” numbers have a weak left-to-right direction.

This distinction between weak and strong is made, because numbers are used in both ltr and rtl languages. The number itself is always written left-to-right, but it will be word-ordered right-to-left if surrounded by strong rtl words, and it will be word-ordered left-to-right if surrounded by strong ltr words.

If the number is not surrounded by strong typed words, the base direction is used.

Your ltr-“08/15” is not surrounded by ltr, so it is put rtl (base direction) from ltr-word “word”.

“one word” are two strong directioned words, so they are layed out ltr themselves and the words layed out ltr as well. No matter what the base direction is.

Try “first 08/15 second” and the numbers will be considered part of a bigger ltr sentence and laid out ltr.

Body:
Why does

<input type="text" dir="rtl" value="08/15 word">

render into word 08/15 and not into 08/15 word?

Why does

<input type="text" dir="rtl" value="one word">

render into one word?

Why is the order switched in the first case but not in the second one?

https://jsfiddle.net/powtac/4aLn71mb/


问:
How to make code wait for okay/cancel button selection?
I am using JQuery's $.dialog(), where I open a dialog with OK and Cancel buttons.

I would have expected that when the dialog opens, the code stops, and would first continue, when the user had selected OK or Cancel.

Here is my complete source code
http://pastebin.com/uw7bvtn7

The section where I have the problem is at line 127-151.

```<code>$("#dialog:ui-dialog").dialog("destroy");

$("#dialog-confirm").dialog({
    resizable: false,
    height: 600,
    modal: true,
    open: function() {
    $(this).children('div.dialog-text').replaceWith("<h3><b>Users</b></h3>" + makeDialogTable(users) + "<h3><b>Owners</b></h3>" + makeDialogTable(owners));
    },

    buttons: {
    "Okay": function() {
        $(this).dialog("close");
    },

    Cancel: function() {
        is_okay = 0;
        $(this).dialog("close");
    }
    } // buttons

}); // dialog

alert(is_okay);
</code>```

What the code does right now is to first show the dialog and then the alert(is_okay) on top.

What I would like is that the code first continues when the user have pressed OK or Cancel.

How could that be done?

答:
Browsers use an event-based, asynchronous programming model where many things can (and do) occur at the same time.  This is how style-transitions (animations like rolldown or fade) work.

Your example displays a dialog and then throws an alert. It cannot "wait" for the user to click on a button because doing so would stop the browser from doing anything else.

So you'll need to refactor your code to do whatever you require to happen when either the OK or Cancel buttons are clicked within the callback associated with the action.

In other words, you need to:

```<code>buttons: {
  "Okay": function() { // this function is called when a user clicks the Okay button
    // do whatever work is required here
  }
}
</code>```

Body:
I am using JQuery's $.dialog(), where I open a dialog with OK and Cancel buttons.

I would have expected that when the dialog opens, the code stops, and would first continue, when the user had selected OK or Cancel.

Here is my complete source code
http://pastebin.com/uw7bvtn7

The section where I have the problem is at line 127-151.

$("#dialog:ui-dialog").dialog("destroy");

$("#dialog-confirm").dialog({
    resizable: false,
    height: 600,
    modal: true,
    open: function() {
    $(this).children('div.dialog-text').replaceWith("
Users
" + makeDialogTable(users) + "
Owners
" + makeDialogTable(owners));
    },

    buttons: {
    "Okay": function() {
        $(this).dialog("close");
    },

    Cancel: function() {
        is_okay = 0;
        $(this).dialog("close");
    }
    } // buttons

}); // dialog

alert(is_okay);

What the code does right now is to first show the dialog and then the alert(is_okay) on top.

What I would like is that the code first continues when the user have pressed OK or Cancel.

How could that be done?

Body:
Browsers use an event-based, asynchronous programming model where many things can (and do) occur at the same time.  This is how style-transitions (animations like rolldown or fade) work.

Your example displays a dialog and then throws an alert. It cannot "wait" for the user to click on a button because doing so would stop the browser from doing anything else.

So you'll need to refactor your code to do whatever you require to happen when either the OK or Cancel buttons are clicked within the callback associated with the action.

In other words, you need to:

buttons: {
  "Okay": function() { // this function is called when a user clicks the Okay button
    // do whatever work is required here
  }
}


问:
Laravel Queues Not adding Jobs in Database
I have enabled Laravel Queues but the Jobs is not adding inside mine database:

here is the steps what i have follow:

```<code>php artisan queue:table

php artisan migrate
</code>```

in .env file i have changed QUEUE_CONNECTION=database

In mine controller:

```<code>    CreateCoinImage::dispatch()
                ->delay(now()->addMinutes(1));
</code>```

Do anyone know why the Queues is not working

答:
.env file you should change queue_driver from sync to database

```<code>queue_driver=database
</code>```

OR

```<code>QUEUE_CONNECTION=database
</code>```

create queue table in your database with artisan command :

```<code>php artisan queue:table
php artisan migrate
php artisan queue:work
</code>```

Body:
I have enabled Laravel Queues but the Jobs is not adding inside mine database:

here is the steps what i have follow:

php artisan queue:table

php artisan migrate

in .env file i have changed QUEUE_CONNECTION=database

In mine controller:

    CreateCoinImage::dispatch()
                ->delay(now()->addMinutes(1));

Do anyone know why the Queues is not working

Body:
.env file you should change queue_driver from sync to database

queue_driver=database

OR

QUEUE_CONNECTION=database

create queue table in your database with artisan command :

php artisan queue:table
php artisan migrate
php artisan queue:work


问:
System.setProperty("sun.net.http.allowRestrictedHeaders", "true") is not working in jenkins
I am trying to send origin header in http request header but when I am getting its value I am getting null instead of the url that I had set in origin header.

Also I have enabled the restricted headers to be send as part of request header in jenkins job by using the following

```<code>System.setProperty("sun.net.http.allowRestrictedHeaders", "true")
</code>```

But it seems that this command is not working.

答:
I am adding to the answers by Cady and Hank:

If you are using sun.net.www.protocol.http.HttpURLConnection to perform the request (I did by using the spring boot TestRestTemplate) the system property is only read once statically.

This means, that setting the property right before performing the request may not affect HttpURLConnection although it changes the system property value.

So make sure to set it as early as possible (e.g. by Maven)

Body:
I am trying to send origin header in http request header but when I am getting its value I am getting null instead of the url that I had set in origin header.

Also I have enabled the restricted headers to be send as part of request header in jenkins job by using the following

System.setProperty("sun.net.http.allowRestrictedHeaders", "true")

But it seems that this command is not working.


问:
What is the function of emptyList in Kotlin
Why there is such emptyList constructor in Kotlin?
It was a immutable List, so there is no way to add or remove its elements and it was empty!
So, what is the function of this emptyList?</p>

答:
Actually，even if you declare an empty list，you can still add elements to this empty list by using the "+", because Kotlin override some operators in its libraries:

```<code>var l = emptyList<Int>()
print(l + 1) // output [1]
</code>```

Body:
Actually，even if you declare an empty list，you can still add elements to this empty list by using the "+", because Kotlin override some operators in its libraries:

var l = emptyList<Int>()
print(l + 1) // output [1]


问:
why the two types are different between readfile and string in kotlin?
I want to read text file and use that strings. so I used raw folder and wrote one YouTube URL.

When I read the .txt file and try to transfer to next activity, that URL didn't work.

So, I compared the literal to text file string. but the types were different.

I don't understand this. How can I solve this problem?

musicfile.txt

```<code>lLZLWUz2veg

</code>```

MainActivity

```<code>var music_url = readFile(musicfile).split("\n")
var url = music_url.get(item.id)
var isEquals = music_url.get(item.id).equals("lLZLWUz2veg")
Log.d("Tag","equals : "+isEquals)
Log.d("Tag","url : "+url)
Log.d("Tag","literal : lLZLWUz2veg")

</code>```

Result

```<code>D/Tag: equals : false
D/Tag: url : lLZLWUz2veg
D/Tag: literal : lLZLWUz2veg
</code>```

答:
Since you don't declare the types, ensure you are using Structural Equality (‘==’)

https://medium.com/@agrawalsuneet/equality-in-kotlin-and-equals-d8373ef529f1

and

Check that your URL does not include the newline character on the beginning or end. You will not be able to tell with your current log statement.

i.e:

```<code>val music_url = readFile(musicfile).split("\n")
val url = music_url.get(0) // I assume its 0? makes the question clearer
val literal = "lLZLWUz2veg"
val isEquals = url == literal

Log.d("Tag", "equals : $isEquals")
Log.d("Tag", "url : [$url]") // Putting [] characters either sides will expose new lines
Log.d("Tag", "literal : [$literal]")
</code>```

Body:
I want to read text file and use that strings. so I used raw folder and wrote one YouTube URL.

When I read the .txt file and try to transfer to next activity, that URL didn't work.

So, I compared the literal to text file string. but the types were different.

I don't understand this. How can I solve this problem?

musicfile.txt

lLZLWUz2veg

MainActivity

var music_url = readFile(musicfile).split("\n")
var url = music_url.get(item.id)
var isEquals = music_url.get(item.id).equals("lLZLWUz2veg")
Log.d("Tag","equals : "+isEquals)
Log.d("Tag","url : "+url)
Log.d("Tag","literal : lLZLWUz2veg")

Result

D/Tag: equals : false
D/Tag: url : lLZLWUz2veg
D/Tag: literal : lLZLWUz2veg

Body:
Since you don't declare the types, ensure you are using Structural Equality (‘==’)

https://medium.com/@agrawalsuneet/equality-in-kotlin-and-equals-d8373ef529f1

and

Check that your URL does not include the newline character on the beginning or end. You will not be able to tell with your current log statement.

i.e:

val music_url = readFile(musicfile).split("\n")
val url = music_url.get(0) // I assume its 0? makes the question clearer
val literal = "lLZLWUz2veg"
val isEquals = url == literal

Log.d("Tag", "equals : $isEquals")
Log.d("Tag", "url : [$url]") // Putting [] characters either sides will expose new lines
Log.d("Tag", "literal : [$literal]")


问:
Scaling SVG dynamically
I am not sure how i can work with SVG backgrounds that scale depending on the screen size (full-width) and depending on how much content we have within the
-tag. I would like to be able to scale to SVG in height, but not in width in that case.

I have been trying to make this work for quite some time now but I don't know how to do it. Could someone help me?

html

```<code><html>
<head>

</head>
<body>
<ul>
  <li>test 1</li>
  <li>test 2</li>
  <li>test 3</li>
</ul>
</body>
</html>
</code>```

css

```<code>ul li {
 height: 6em;
}

li:nth-child(odd) {
    background: url(http://leanimpactaward.ch/img/GRAFIK_Accordeon_V1.svg);
    background-size: 100%;
    background-repeat: no-repeat;
}

li:nth-child(even) {
    background: url(http://leanimpactaward.ch/img/GRAFIK_Accordeon_V2.svg);
    background-size: 100%;
    background-repeat: no-repeat;
}
</code>```

https://jsfiddle.net/3g7n2v5e/3/

答:
Use the transform:scale(x,y) css property to change the scale of your SVG.

For exemple :

li:nth-child(odd) {
    background: url(http://leanimpactaward.ch/img/GRAFIK_Accordeon_V1.svg);
    background-size: 100%;
    background-repeat: no-repeat;
    transform:scale(1, 0.5);
}```
</div>
</div>
</p>

<p>Hope it's helping you.</p>

<p>Edit :</p>

<p>It's a better solution if you want no resizing the text :</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-css lang-css prettyprint-override"><code>ul li {
 height: 6em;
 position: relative;
}

li:nth-child(odd)::before {
 content: '';
 height: 100%;
 width:100%;
 position: absolute;
 background: url(http://leanimpactaward.ch/img/GRAFIK_Accordeon_V1.svg);
 background-size: 100%;
 background-repeat: no-repeat;
 transform: scale(1, 0.5);
}

li:nth-child(even)::before {
    content: '';
 height: 100%;
 width:100%;
 position: absolute;
 background: url(http://leanimpactaward.ch/img/GRAFIK_Accordeon_V2.svg);
 background-size: 100%;
 background-repeat: no-repeat;
    transform: scale(1, 0.5);
}</code>```

test 1

test 2

test 3

```

Title: Scaling SVG dynamically

Body:
I am not sure how i can work with SVG backgrounds that scale depending on the screen size (full-width) and depending on how much content we have within the
-tag. I would like to be able to scale to SVG in height, but not in width in that case.

I have been trying to make this work for quite some time now but I don't know how to do it. Could someone help me?

html

test 1

test 2

test 3

css

ul li {
 height: 6em;
}

li:nth-child(odd) {
    background: url(http://leanimpactaward.ch/img/GRAFIK_Accordeon_V1.svg);
    background-size: 100%;
    background-repeat: no-repeat;
}

li:nth-child(even) {
    background: url(http://leanimpactaward.ch/img/GRAFIK_Accordeon_V2.svg);
    background-size: 100%;
    background-repeat: no-repeat;
}

https://jsfiddle.net/3g7n2v5e/3/

Body:
Use the transform:scale(x,y) css property to change the scale of your SVG.

For exemple :

li:nth-child(odd) {
    background: url(http://leanimpactaward.ch/img/GRAFIK_Accordeon_V1.svg);
    background-size: 100%;
    background-repeat: no-repeat;
    transform:scale(1, 0.5);
}

Hope it's helping you.

Edit :

It's a better solution if you want no resizing the text :

ul li {
 height: 6em;
 position: relative;
}

li:nth-child(odd)::before {
 content: '';
 height: 100%;
 width:100%;
 position: absolute;
 background: url(http://leanimpactaward.ch/img/GRAFIK_Accordeon_V1.svg);
 background-size: 100%;
 background-repeat: no-repeat;
 transform: scale(1, 0.5);
}

li:nth-child(even)::before {
    content: '';
 height: 100%;
 width:100%;
 position: absolute;
 background: url(http://leanimpactaward.ch/img/GRAFIK_Accordeon_V2.svg);
 background-size: 100%;
 background-repeat: no-repeat;
    transform: scale(1, 0.5);
}

<html>
<head>

</head>
<body>
<ul>
  <li>test 1</li>
  <li>test 2</li>
  <li>test 3</li>
</ul>
</body>
</html>


问:
re-open background application via notification item
I got an app with tabs and a notification bar entry,
when I send it to background (click on home button)
and try to re-open the application via click on the
notification bar, the app restarts (last selected
tab is lost).

When I hold the home button if the application is in
the background and select it from there or click the
app's icon on the homescreen, the previous state is
restored per default (the correct tab is selected)

IMO the intent of the notification is wrong, but I'm
not sure how to fix it.

In short: How to get a background application back to
foreground when I click the notification entry?

thx!

答:
Put these two lines. This will resume currently paused activity:</p>

```<code>notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
</code>```

Body:
Put these two lines. This will resume currently paused activity:

notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);


问:
How to change order of a drag and drop list in Angular Material with up or down buttons?
How to change order of a drag and drop list in Angular Material with up or down buttons? So I want to move an item up or down.

template.html

      <button class="up">Up</button>
      <button class="down">Down</button>

```

<p>component.ts</p>

<pre class="lang-js prettyprint-override"><code>public drop(event: CdkDragDrop<string[]>) {
  moveItemInArray(this.categories, event.previousIndex, event.currentIndex);
}
</code>```

答:
You can call a standard function binded to event click of button like this:

component.ts

order(index:number,up: boolean) {

    if(up) // move up
    {
      if(index === 0) {
        console.log('do nothing')
      }
      else{
        const temp = this.movies[index-1];
        this.movies[index-1]=this.movies[index];
        this.movies[index]=temp;
      }
    }
    else{
      if(index == this.movies.length) {
        console.log('do nothing')
      }
      else {
         const temp = this.movies[index+1];
        this.movies[index+1]=this.movies[index];
        this.movies[index]=temp;
      }
      }
    }
```

<p><strong>component.html</strong></p>

<pre class="lang-html prettyprint-override"><code><span style="padding:20px"></span>
<hr>
<div cdkDropList class="example-list" (cdkDropListDropped)="drop($event)">
  <div class="example-box" *ngFor="let movie of movies; let i = index" cdkDrag>{{movie}}
    <div><button mat-fab (click)="order(i,true)">Up</button>
    <button mat-fab (click)="order(i,false)">Down</button></div>
  </div>
</div>
</code>```

example here.

Body:
How to change order of a drag and drop list in Angular Material with up or down buttons? So I want to move an item up or down.

template.html

      <button class="up">Up</button>
      <button class="down">Down</button>

component.ts

public drop(event: CdkDragDrop<string[]>) {
  moveItemInArray(this.categories, event.previousIndex, event.currentIndex);
}

Body:
You can call a standard function binded to event click of button like this:

component.ts

order(index:number,up: boolean) {

    if(up) // move up
    {
      if(index === 0) {
        console.log('do nothing')
      }
      else{
        const temp = this.movies[index-1];
        this.movies[index-1]=this.movies[index];
        this.movies[index]=temp;
      }
    }
    else{
      if(index == this.movies.length) {
        console.log('do nothing')
      }
      else {
         const temp = this.movies[index+1];
        this.movies[index+1]=this.movies[index];
        this.movies[index]=temp;
      }
      }
    }

component.html

<span style="padding:20px"></span>
<hr>
<div cdkDropList class="example-list" (cdkDropListDropped)="drop($event)">
  <div class="example-box" *ngFor="let movie of movies; let i = index" cdkDrag>{{movie}}
    <div><button mat-fab (click)="order(i,true)">Up</button>
    <button mat-fab (click)="order(i,false)">Down</button></div>
  </div>
</div>

example here.


问:
PayUMoney payment method for sandbox is not showing in frontend for Magento 1.9
I downloaded PayuMoney payment extension for Magento 1.9 from their website and copied the respective directories/code in the app folder.

In the Admin, it is showing the configuration settings for this extension where I entered following details as instructed in the integration guide document:

```<code>Enabled:  ‘Yes’
Environment: sandbox
PayUmoney Key: Test key as    provided in the guide (for testing purpose)
PayUmoney Salt: Test    salt as provided in the guide (for testing purpose)
Citrus Payment/Vanity Url: Blank
Citrus Access Key: Blank
Citrus Secret Key: Blank
Route (%): Blank
</code>```

Refer the screenshot: PayuMoney extension setting in Magento Admin

I want to test the functionality hence want to use sandbox environment with test credentials provided in the guide. But with above configuration setting, PayuMoney is not coming up for the customer in the checkout page as a payment option.

I checked related threads but it has not helped much. Appreciate if anyone has any idea to solve this problem.

答:
There will be two options:

```<code>Route to PayUMoney = 100
Route to Citrus  = 0
</code>```

Fill these values it will work.

Body:
I downloaded PayuMoney payment extension for Magento 1.9 from their website and copied the respective directories/code in the app folder.

In the Admin, it is showing the configuration settings for this extension where I entered following details as instructed in the integration guide document:

Enabled:  ‘Yes’
Environment: sandbox
PayUmoney Key: Test key as    provided in the guide (for testing purpose)
PayUmoney Salt: Test    salt as provided in the guide (for testing purpose)
Citrus Payment/Vanity Url: Blank
Citrus Access Key: Blank
Citrus Secret Key: Blank
Route (%): Blank

Refer the screenshot: PayuMoney extension setting in Magento Admin

I want to test the functionality hence want to use sandbox environment with test credentials provided in the guide. But with above configuration setting, PayuMoney is not coming up for the customer in the checkout page as a payment option.

I checked related threads but it has not helped much. Appreciate if anyone has any idea to solve this problem.

Body:
There will be two options:

Route to PayUMoney = 100
Route to Citrus  = 0

Fill these values it will work.


问:
C# webBrowser script error
I keep getting a script error when trying to load the page using  webBrowser.Navigate("https://home.nest.com/"). It will pull up fine from my normal internet browser but not in my program.

Can anyone point me in the right direction?

答:
The WebBrowser control is capable of rendering most web pages, but by default it attempts to render pages in compatibility mode (pretty much IE7, hence the issues). If you are building your own page, it's simple, just add the following tag to the header and it should render fine...

```<code><meta http-equiv="X-UA-Compatible" content="IE=Edge" />
</code>```

However, if you are trying to render a third party site you cannot add tags to, things get more difficult. As mentioned above, you can use a registry key (HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION) if it's just on your own machine.

If neither of these options are a possible solution, using a different browser control (again, great suggestions above) is pretty much your only option.

There's a great blog on controlling the browser control compatibility mode at https://learn.microsoft.com/en-gb/archive/blogs/patricka/controlling-webbrowser-control-compatibility

Title: C# webBrowser script error

Body:
The WebBrowser control is capable of rendering most web pages, but by default it attempts to render pages in compatibility mode (pretty much IE7, hence the issues). If you are building your own page, it's simple, just add the following tag to the header and it should render fine...

<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

However, if you are trying to render a third party site you cannot add tags to, things get more difficult. As mentioned above, you can use a registry key (HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION) if it's just on your own machine.

If neither of these options are a possible solution, using a different browser control (again, great suggestions above) is pretty much your only option.

There's a great blog on controlling the browser control compatibility mode at https://learn.microsoft.com/en-gb/archive/blogs/patricka/controlling-webbrowser-control-compatibility


问:
Incorporating Exploratory Tests created using the Test & Feedback extension in to existing Test Suites
We are embarking on the delivery of a large D365 ERP. As Test Manager I'll be creating  some tests with normal Pass/Fail criteria which can be easily reported on. The bulk of the testing will be done by our project SMEs & other business users.  For some of the larger modules we could have up to 20 people executing test scenarios. Rather than them having to test using Excel I'd like them to use the Test & Feedback extension and create Exploratory Tests when they test a feature/business scenario.

When they are using the extension they will be linking back to the parent item in the Test Suite (either a PBI or a Test Case).  These Exploratory Tests then display as 'Related' to the item in the Test Suite.  So that the project can fully understand the required test effort I'd like to get Exploratory Tests added to the Test Suites, and subsequently reported on the Dashboard.

I've gotten stuck with the last part and am wondering if anyone on here can help with some answers/advice for the following:

Is there a way for a Test Suite to update dynamically (or otherwise) when Exploratory Tests are linked to items in the Test Suite? There doesn't appear to be a way to rerun a query to add items to an existing Test Suite (I can go and recreate the Test Suite using a Query and get the items in, but I lose the test results for other items in the suite)

Is anyone aware of a widget that will allow me to report on Exploratory Tests?

答:
Is there a way for a Test Suite to update dynamically (or otherwise)
  when Exploratory Tests are linked to items in the Test Suite?

For this issue, when you create a test suite ,there are three types to choose from : static test suites, requirement-based suites, and query-based suites. I think query-based suites could meet your need.

What are query-based test suites :
Use a query to group together test cases that have a particular characteristic, for example, all tests that have Priority=1. The suite will automatically include every test case that is returned by the query that you define.

Is anyone aware of a widget that will allow me to report on
  Exploratory Tests?

Regarding the second question,AFAIK,there is currently no such widget.Widgets are implemented as a contribution point in the extension framework. You can try to build a custom widget extension to achieve this feature.


问:
When I create a dynamic dropdown using select2 it breaks
I have a table which has the column "genre" which has a select box which is populated using Select2, and I have a button which adds a new row to the table, once I add a new row to the table, I try to populate the Genre using select2 as well but its buggy, it results in the new select dropdown not being selectable.

Have a look at my JSFiddle here: https://jsfiddle.net/hm3w7jtz/3/

In order to get to the bug, Add a new group and then you will notice that the new row genre is not selectable.

https://jsfiddle.net/szjd6gu4/2/

Code

```<code>   <head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
   <link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
   </head>
   <h3> Movies </h3>
    <table class="my_table" id="movies" border="1px" style="border-collapse: collapse;">
    <thead>
      <tr><b>
        <td>Group</td>
        <td>Genre</td>
        <td>Movie Name</td>
        <td>Imdb</td>
        <td>Rotten Tomato</td>
        <td>Lead Actress</td>
        <td>Lead Actor</td>
        <td>Year of Release</td>
        <td>Revenue</td>
        <td>Budget</td>
      </tr></b>
    </thead>

    <tbody>
    <tr class="group-row">
    <td class="nr"><input type="text" placeholder="" size="9"><button id="btn" class="group" style="float:right;">+</button>
    </td>
    <td><select id="genre" class='genre' style="width:150px;"></select></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="10" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    </tr>
    </tbody>
  </table>
  <script>
    $(document).ready(function() {
    var genre = ['Action', 'Adventure', 'Fantasy', 'Anime', 'Romance'];
     $(".genre").select2({
        data: genre
      });
  });

  var row ="<td class='nr'><input type='text' placeholder='' size='9'><button id='btn' class='group' style='float:right;'>+</button></td><td><select id='genre' class='genre' style='width:150px;'></select></td><td><input type='text' size='7' placeholder=''></td><td><input type='text' size='7' placeholder=''></td><td><input type='text' size='7' placeholder=''></td><td><input type='text' size='7' placeholder=''></td><td><input type='text' size='10' placeholder=''></td><td><input type='text' size='7' placeholder=''></td><td><input type='text' size='7' placeholder=''></td><td><input type='text' size='7' placeholder=''></td>";

const $groupRow = $("<tr>", {
  class: "group-row"
}).append(row);

const tableBody = $("#movies tbody");
tableBody.on('click', '.group', (e) => {
  tableBody.append($groupRow.clone());
      $(".genre").select2({
        data: genre
      });
});
  </script>
</code>```

答:
There are 2 problems with your code:

1) Remove id="genre" from both of your Selects

```<code><select id="genre" class='genre' style="width:150px;"></select>
</code>```

2) You need to move the line with the Array right before the $(document).ready function:

```<code>//BEFORE
    $(document).ready(function() {
    var genre = ['Action', 'Adventure', 'Fantasy', 'Anime', 'Romance'];
     $(".genre").select2({
        data: genre
      });
  });

//AFTER
var genre = ['Action', 'Adventure', 'Fantasy', 'Anime', 'Romance'];

$(document).ready(function() {
         $(".genre").select2({
            data: genre
          });
      });
</code>```

var genre = ['Action', 'Adventure', 'Fantasy', 'Anime', 'Romance'];
    $(document).ready(function() {

     $(".genre").select2({
        data: genre
      });
  });

  var row ="<input type='text' placeholder='' size='9'><button id='btn' class='group' style='float:right;'>+</button>	<select class='genre' style='width:150px;'></select>	<input type='text' size='7' placeholder=''>	<input type='text' size='7' placeholder=''>	<input type='text' size='7' placeholder=''>	<input type='text' size='7' placeholder=''>	<input type='text' size='10' placeholder=''>	<input type='text' size='7' placeholder=''>	<input type='text' size='7' placeholder=''>	<input type='text' size='7' placeholder=''>	";

const $groupRow = $("
", {
  class: "group-row"
}).append(row);

const tableBody = $("#movies tbody");
tableBody.on('click', '.group', (e) => {
  tableBody.append($groupRow.clone());

      $(".genre").select2({
        data: genre
      });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code>   <head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
   <link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
   </head>
   <h3> Movies </h3>
    <table class="my_table" id="movies" border="1px" style="border-collapse: collapse;">
    <thead>
      <tr><b>
        <td>Group</td>
        <td>Genre</td>
        <td>Movie Name</td>
        <td>Imdb</td>
        <td>Rotten Tomato</td>
        <td>Lead Actress</td>
        <td>Lead Actor</td>
        <td>Year of Release</td>
        <td>Revenue</td>
        <td>Budget</td>
      </tr></b>
    </thead>

    <tbody>
    <tr class="group-row">
    <td class="nr"><input type="text" placeholder="" size="9"><button id="btn" class="group" style="float:right;">+</button>
    </td>
    <td><select class='genre' style="width:150px;"></select></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="10" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    </tr>
    </tbody>
  </table></code>```

Body:
I have a table which has the column "genre" which has a select box which is populated using Select2, and I have a button which adds a new row to the table, once I add a new row to the table, I try to populate the Genre using select2 as well but its buggy, it results in the new select dropdown not being selectable.

Have a look at my JSFiddle here: https://jsfiddle.net/hm3w7jtz/3/

In order to get to the bug, Add a new group and then you will notice that the new row genre is not selectable.

https://jsfiddle.net/szjd6gu4/2/

Code

   <link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />

 Movies

        Group
        Genre
        Movie Name
        Imdb
        Rotten Tomato
        Lead Actress
        Lead Actor
        Year of Release
        Revenue
        Budget

    <input type="text" placeholder="" size="9"><button id="btn" class="group" style="float:right;">+</button>

    <select id="genre" class='genre' style="width:150px;"></select>
    <input type="text" size="7" placeholder="">
    <input type="text" size="7" placeholder="">
    <input type="text" size="7" placeholder="">
    <input type="text" size="7" placeholder="">
    <input type="text" size="10" placeholder="">
    <input type="text" size="7" placeholder="">
    <input type="text" size="7" placeholder="">
    <input type="text" size="7" placeholder="">

Body:
There are 2 problems with your code:

1) Remove id="genre" from both of your Selects

<select id="genre" class='genre' style="width:150px;"></select>

2) You need to move the line with the Array right before the $(document).ready function:

//BEFORE
    $(document).ready(function() {
    var genre = ['Action', 'Adventure', 'Fantasy', 'Anime', 'Romance'];
     $(".genre").select2({
        data: genre
      });
  });

//AFTER
var genre = ['Action', 'Adventure', 'Fantasy', 'Anime', 'Romance'];

$(document).ready(function() {
         $(".genre").select2({
            data: genre
          });
      });

var genre = ['Action', 'Adventure', 'Fantasy', 'Anime', 'Romance'];
    $(document).ready(function() {

     $(".genre").select2({
        data: genre
      });
  });

  var row ="<td class='nr'><input type='text' placeholder='' size='9'><button id='btn' class='group' style='float:right;'>+</button></td><td><select class='genre' style='width:150px;'></select></td><td><input type='text' size='7' placeholder=''></td><td><input type='text' size='7' placeholder=''></td><td><input type='text' size='7' placeholder=''></td><td><input type='text' size='7' placeholder=''></td><td><input type='text' size='10' placeholder=''></td><td><input type='text' size='7' placeholder=''></td><td><input type='text' size='7' placeholder=''></td><td><input type='text' size='7' placeholder=''></td>";

const $groupRow = $("<tr>", {
  class: "group-row"
}).append(row);

const tableBody = $("#movies tbody");
tableBody.on('click', '.group', (e) => {
  tableBody.append($groupRow.clone());

      $(".genre").select2({
        data: genre
      });
});

   <head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
   <link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
   </head>
   <h3> Movies </h3>
    <table class="my_table" id="movies" border="1px" style="border-collapse: collapse;">
    <thead>
      <tr><b>
        <td>Group</td>
        <td>Genre</td>
        <td>Movie Name</td>
        <td>Imdb</td>
        <td>Rotten Tomato</td>
        <td>Lead Actress</td>
        <td>Lead Actor</td>
        <td>Year of Release</td>
        <td>Revenue</td>
        <td>Budget</td>
      </tr></b>
    </thead>

    <tbody>
    <tr class="group-row">
    <td class="nr"><input type="text" placeholder="" size="9"><button id="btn" class="group" style="float:right;">+</button>
    </td>
    <td><select class='genre' style="width:150px;"></select></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="10" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    <td><input type="text" size="7" placeholder=""></td>
    </tr>
    </tbody>
  </table>


问:
Base64 PDF data IE and Edge does not show up
I have a PDF whose content is encrypted as a base64 string. I am trying to display it in an embed element. It works fine in Chrome and other browsers except Microsoft Edge and Internet Explorer.

```<code>success: function (data, textStatus, xhr) {
  $("#url").html("");
  $("#url").append("<embed src=\"" + data.encodeUrl + "\" class=\"iframe\"></embed>");
  $("#cameraLink").modal('show');
}
</code>```

答:
I have changed my code, But it only works with newer version of EDGE and has same problem with older version of EDGE and I.E.                                </p>

```<code>     success: function (data, textStatus, xhr) {
        $("#url").html("");
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            var pdfData = data.encodeUrl;
            if(pdfData!=null){
                var actualData = pdfData.split(',');
                var byteCharacters = atob(actualData[1]);
                var byteNumbers = new Array(byteCharacters.length);
            }else{
                var actualData = pdfData;
                var byteCharacters = atob(actualData)
                var byteNumbers = new Array(pdfData.length);
            }
            for (var i = 0; i < byteCharacters.length; i++) {
                byteNumbers[i] = byteCharacters.charCodeAt(i);
            }
            var byteArray = new Uint8Array(byteNumbers);
            var blob = new Blob([byteArray], {type: 'application/pdf'});
            var blob_url = URL.createObjectURL(blob);
        $("#url").append("<iframe id='frame' class=\"iframe\</iframe>");

            var blob_iframe = document.querySelector('#frame');
            blob_iframe.src = blob_url;
        }else{
            $("#url").append("<iframe src=\""+data.encodeUrl+"\"
                    class=\"iframe\" height="+height+" width=\"100%\"></iframe>");
        }
        $("#cameraLink").modal('show');
    }
</code>```

Body:
I have a PDF whose content is encrypted as a base64 string. I am trying to display it in an embed element. It works fine in Chrome and other browsers except Microsoft Edge and Internet Explorer.

success: function (data, textStatus, xhr) {
  $("#url").html("");
  $("#url").append("<embed src=\"" + data.encodeUrl + "\" class=\"iframe\"></embed>");
  $("#cameraLink").modal('show');
}

Body:
I have changed my code, But it only works with newer version of EDGE and has same problem with older version of EDGE and I.E.

     success: function (data, textStatus, xhr) {
        $("#url").html("");
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            var pdfData = data.encodeUrl;
            if(pdfData!=null){
                var actualData = pdfData.split(',');
                var byteCharacters = atob(actualData[1]);
                var byteNumbers = new Array(byteCharacters.length);
            }else{
                var actualData = pdfData;
                var byteCharacters = atob(actualData)
                var byteNumbers = new Array(pdfData.length);
            }
            for (var i = 0; i < byteCharacters.length; i++) {
                byteNumbers[i] = byteCharacters.charCodeAt(i);
            }
            var byteArray = new Uint8Array(byteNumbers);
            var blob = new Blob([byteArray], {type: 'application/pdf'});
            var blob_url = URL.createObjectURL(blob);
        $("#url").append("<iframe id='frame' class=\"iframe\</iframe>");

            var blob_iframe = document.querySelector('#frame');
            blob_iframe.src = blob_url;
        }else{
            $("#url").append("<iframe src=\""+data.encodeUrl+"\"
                    class=\"iframe\" height="+height+" width=\"100%\"></iframe>");
        }
        $("#cameraLink").modal('show');
    }


问:
Ansible force to use --limit and --tags when run playbook
I am using ansible 2.9.4. My goal is to deny run some playbook on all nodes by accident or without tags. This is my app.yaml:

```<code>  - hosts: all
    remote_user: root
    vars:
      server_domain: mydomain.com
      project_name: project
    tasks:
      - name: checking limit arg
        fail:
          msg: "you must use -l or --limit - when you really want to use all hosts, use -l 'all'"
        when: ansible_limit is not defined
        run_once: true
      - name: "suppress message if tag given"
        set_fact: suppress_message=yes
        tags: dev,test,prod
      - name: "message"
        fail:
          msg: "You didn't choose environment 'dev,test,prod'"
        when: suppress_message is not defined
    roles:
      - testrole
</code>```

The problem is, when I am not use --limit option, the role testrole run successfully and then the error message occurs - too late if I already run it on all nodes.

Even when I specify tags --tags "mytag" it will not check if limit was specified.

By similar way I would like to force to use tags, so everytime when you run playbook, you should specify environment tag (dev, test, prod) - e.g ssh keys for different environments, configuration files, etc...

What I would expect from this, that If I not specified tag dev, test or prod,  the suppress_message would not be specified so next task with name message would fail with message "You didn't  choose environement".

The fact is, If I not specified any tag:

- supress message have state OK

- message is skipped

If I specify valid tag --tags "dev":

- supress message have state OK

- message is not even mentioned (I would expect skipping)

If I specify "invalid tag" --tags "dev123":

- supress message is not mentioned

- message is not mentioned

The solution for limit could be replace - hosts: all with  - hosts: randomtext so when no limit is specified there will be no match but what about tags/environments? I am quiet lost about how ansible works. The logic about this decisions what will run is quiet chaotic from this example.

答:
Try using tags like this -  </p>

```<code>tags:
  - dev,test,prod
</code>```

Body:
I am using ansible 2.9.4. My goal is to deny run some playbook on all nodes by accident or without tags. This is my app.yaml:

  - hosts: all
    remote_user: root
    vars:
      server_domain: mydomain.com
      project_name: project
    tasks:
      - name: checking limit arg
        fail:
          msg: "you must use -l or --limit - when you really want to use all hosts, use -l 'all'"
        when: ansible_limit is not defined
        run_once: true
      - name: "suppress message if tag given"
        set_fact: suppress_message=yes
        tags: dev,test,prod
      - name: "message"
        fail:
          msg: "You didn't choose environment 'dev,test,prod'"
        when: suppress_message is not defined
    roles:
      - testrole

The problem is, when I am not use --limit option, the role testrole run successfully and then the error message occurs - too late if I already run it on all nodes.

Even when I specify tags --tags "mytag" it will not check if limit was specified.

By similar way I would like to force to use tags, so everytime when you run playbook, you should specify environment tag (dev, test, prod) - e.g ssh keys for different environments, configuration files, etc...

What I would expect from this, that If I not specified tag dev, test or prod,  the suppress_message would not be specified so next task with name message would fail with message "You didn't  choose environement".

The fact is, If I not specified any tag:

- supress message have state OK

- message is skipped

If I specify valid tag --tags "dev":

- supress message have state OK

- message is not even mentioned (I would expect skipping)

If I specify "invalid tag" --tags "dev123":

- supress message is not mentioned

- message is not mentioned

The solution for limit could be replace - hosts: all with  - hosts: randomtext so when no limit is specified there will be no match but what about tags/environments? I am quiet lost about how ansible works. The logic about this decisions what will run is quiet chaotic from this example.

Body:
Try using tags like this -

tags:
  - dev,test,prod


问:
How to delete data/rows from multiple tables in SQL Server based on some condition
I have a DB that has around 500 tables. I created two table variables to help me with deleting some data:

To store ProductID values (hundreds) from MainTable which are referenced inside 400 other tables in the same DB.

To store the names of all tables that contain ProductID column (referencing the MainTable table), so I can do "foreach" through that list.

Now, how do I tell SQL to delete all data from all the tables in the list that have ProductID from the list?

Now I need to delete all the records from MainTable, but first of course I need to delete all the data from all other tables that is referencing those ProductID values.

Is there a way to create a short query something like:

DELETE *
FROM A_LIST_OF_ALL_TABLES_THAT_CONTAIN_PRODUCTID_COLUMN
WHERE ProductID IN A_LIST_OF_ALL_PRODUCTIDs
```

答:
```<code>WITH LIST_OF_TABLES AS (
    SELECT 'table1' as tablename
    union all
    SELECT 'table2'
    union all
    SELECT 'table3'
), LIST_OF_PRODUCTID AS (
    SELECT 'product1' as product
    union all
    SELECT 'product2'
)
SELECT
   CONCAT('DELETE FROM ',tablename,' WHERE productid=', product,';')
FROM LIST_OF_TABLES
JOIN LIST_OF_PRODUCTID on 1=1
</code>```

output:

```<code>DELETE FROM table1 WHERE productid=product1;
DELETE FROM table2 WHERE productid=product1;
DELETE FROM table3 WHERE productid=product1;
DELETE FROM table1 WHERE productid=product2;
DELETE FROM table2 WHERE productid=product2;
DELETE FROM table3 WHERE productid=product2;
</code>```

Now you only need to fine-tune this script to fit in your situation, so finally you can run the output as a script on your database...

Body:
WITH LIST_OF_TABLES AS (
    SELECT 'table1' as tablename
    union all
    SELECT 'table2'
    union all
    SELECT 'table3'
), LIST_OF_PRODUCTID AS (
    SELECT 'product1' as product
    union all
    SELECT 'product2'
)
SELECT
   CONCAT('DELETE FROM ',tablename,' WHERE productid=', product,';')
FROM LIST_OF_TABLES
JOIN LIST_OF_PRODUCTID on 1=1

output:

DELETE FROM table1 WHERE productid=product1;
DELETE FROM table2 WHERE productid=product1;
DELETE FROM table3 WHERE productid=product1;
DELETE FROM table1 WHERE productid=product2;
DELETE FROM table2 WHERE productid=product2;
DELETE FROM table3 WHERE productid=product2;

Now you only need to fine-tune this script to fit in your situation, so finally you can run the output as a script on your database...


问:
How to convert Spark dense vector to separate colunms with their index in Scala?
I want to convert spark dense vectors to separate columns with their index in Scala? Hope some help, please~

I have a dataframe after minMaxScaler :

```<code>+---+--------+--------------------+---------------------+
| id|category|minMaxScalerFeatures|scaledFeatures_output|
+---+--------+--------------------+---------------------+
|  0|      66|          [0.0,66.0]|            [0.0,0.0]|
|  1|      98|          [1.0,98.0]|            [0.5,1.0]|
|  2|      90|          [2.0,90.0]|           [1.0,0.75]|
+---+--------+--------------------+---------------------+
</code>```

I want to get the value after scaler with their index, like the pattern "index:value" which is String type:

```<code>+---+--------+--------------------+-----------------------+
| id|category|minMaxScalerFeatures|scaledFeatures_output  |
+---+--------+--------------------+-----------------------+
|  0|      66|          [0.0,66.0]|            0:0.0,1:0.0|
|  1|      98|          [1.0,98.0]|            0:0.5,1:1.0|
|  2|      90|          [2.0,90.0]|           0:1.0,1:0.75|
+---+--------+--------------------+-----------------------+
</code>```

Code to generate the data:

```<code>import org.apache.spark.ml.feature._
import org.apache.spark.sql.functions.udf
import org.apache.spark.sql.DataFrame
import org.apache.spark.sql.functions._

val df_1 = Seq((0, 66),(1, 98),(2, 90)).toDF("id", "category")

val minMax_columns = Array("id", "category")

val assembler = new VectorAssembler()
  .setInputCols(minMax_columns)
  .setOutputCol("minMaxScalerFeatures")

val scaler = new MinMaxScaler()
  .setInputCol("minMaxScalerFeatures")
  .setOutputCol("scaledFeatures_output")

val dataset = assembler.transform(df_1)

val scalerModel = scaler.fit(dataset)

val scaledData = scalerModel.transform(dataset)
</code>```

Thank U very much~ :)

答:
The question is how will you complete this task on an array. I would personnaly do that (which may not be optimal but it works) :

```<code>var s = ""
for(i <- 0 until array.length) s = s + s"$i:${a(i)}"
s = s.dropRight(1)
</code>```

Now you can include that in an user defined function and it's done:

```<code>import org.apache.spark.ml.linalg.DenseVector
import org.apache.spark.sql.functions.udf
val myudf = udf((arr: DenseVector) => {
    val a = arr.toArray
    var s = ""
    for(i <- 0 until a.length) s = s + s"$i:${a(i)},"
    s.dropRight(1)
})
</code>```

Body:
I want to convert spark dense vectors to separate columns with their index in Scala? Hope some help, please~

I have a dataframe after minMaxScaler :

+---+--------+--------------------+---------------------+
| id|category|minMaxScalerFeatures|scaledFeatures_output|
+---+--------+--------------------+---------------------+
|  0|      66|          [0.0,66.0]|            [0.0,0.0]|
|  1|      98|          [1.0,98.0]|            [0.5,1.0]|
|  2|      90|          [2.0,90.0]|           [1.0,0.75]|
+---+--------+--------------------+---------------------+

I want to get the value after scaler with their index, like the pattern "index:value" which is String type:

+---+--------+--------------------+-----------------------+
| id|category|minMaxScalerFeatures|scaledFeatures_output  |
+---+--------+--------------------+-----------------------+
|  0|      66|          [0.0,66.0]|            0:0.0,1:0.0|
|  1|      98|          [1.0,98.0]|            0:0.5,1:1.0|
|  2|      90|          [2.0,90.0]|           0:1.0,1:0.75|
+---+--------+--------------------+-----------------------+

Code to generate the data:

import org.apache.spark.ml.feature._
import org.apache.spark.sql.functions.udf
import org.apache.spark.sql.DataFrame
import org.apache.spark.sql.functions._

val df_1 = Seq((0, 66),(1, 98),(2, 90)).toDF("id", "category")

val minMax_columns = Array("id", "category")

val assembler = new VectorAssembler()
  .setInputCols(minMax_columns)
  .setOutputCol("minMaxScalerFeatures")

val scaler = new MinMaxScaler()
  .setInputCol("minMaxScalerFeatures")
  .setOutputCol("scaledFeatures_output")

val dataset = assembler.transform(df_1)

val scalerModel = scaler.fit(dataset)

val scaledData = scalerModel.transform(dataset)

Thank U very much~ :)

Body:
The question is how will you complete this task on an array. I would personnaly do that (which may not be optimal but it works) :

var s = ""
for(i <- 0 until array.length) s = s + s"$i:${a(i)}"
s = s.dropRight(1)

Now you can include that in an user defined function and it's done:

import org.apache.spark.ml.linalg.DenseVector
import org.apache.spark.sql.functions.udf
val myudf = udf((arr: DenseVector) => {
    val a = arr.toArray
    var s = ""
    for(i <- 0 until a.length) s = s + s"$i:${a(i)},"
    s.dropRight(1)
})


问:
Terraform quickest way to import multiple resources
My Terraform state file is messedup. Resources are already available on AWS. When I run terraform apply command I am getting multiple "Already Exists" error same as below.

```<code>aws_autoscaling_group.mysql-asg: Error creating AutoScaling Group: AlreadyExists: AutoScalingGroup by this name already exists - A group with the name int-mysql-asg already exists
</code>```

When I do terraform import then it goes away. but I have hundreds of resources which is giving error. What is the best way to sync terraform state and make terraform apply successful?

答:
You may want to look at Terraforming

It's a Ruby project that states "Export existing AWS resources to Terraform style (tf, tfstate)"

Body:
My Terraform state file is messedup. Resources are already available on AWS. When I run terraform apply command I am getting multiple "Already Exists" error same as below.

aws_autoscaling_group.mysql-asg: Error creating AutoScaling Group: AlreadyExists: AutoScalingGroup by this name already exists - A group with the name int-mysql-asg already exists

When I do terraform import then it goes away. but I have hundreds of resources which is giving error. What is the best way to sync terraform state and make terraform apply successful?


问:
Cypress custom command is not recognized when invoked
I've created the following custom command in my cypress/support/commands.js file.

```<code>Cypress.Commands.add("login", (username, password) => {
    cy.request({
        method: 'POST',
        form: true,
        url: '/test/login/',
        body: {'username': username, 'password': password}
    })
})
</code>```

I had tests passing and login working before moving the login functionality to this custom command. I'm invoking it in my spec with cy.login(testuser, testpwd), but I'm getting the following error message: TypeError: cy.login is not a function. The docs say that /cypress/support/commands.js is loaded before any test files are evaluated, so I assumed that simply placing a custom command in there would make the command available.  I'm running the tests through the local (GUI) test runner.

答: It may help to put a line import './commands.js' into index.js.

Body:
I've created the following custom command in my cypress/support/commands.js file.

Cypress.Commands.add("login", (username, password) => {
    cy.request({
        method: 'POST',
        form: true,
        url: '/test/login/',
        body: {'username': username, 'password': password}
    })
})

I had tests passing and login working before moving the login functionality to this custom command. I'm invoking it in my spec with cy.login(testuser, testpwd), but I'm getting the following error message: TypeError: cy.login is not a function. The docs say that /cypress/support/commands.js is loaded before any test files are evaluated, so I assumed that simply placing a custom command in there would make the command available.  I'm running the tests through the local (GUI) test runner.


问:
Flutter ListView inside a Columns is not working
I am trying to add a list view inside a column but it crashes

I have got the following Errors:

RenderFlex children have non-zero flex but incoming height constraints
  are unbounded.

RenderBox was not laid out: RenderFlex#e1a1e relayoutBoundary=up7
  NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
  'package:flutter/src/rendering/box.dart': Failed assertion: line 1687
  pos 12: 'hasSize'

The method '>' was called on null. Receiver: null

This is my Code:

```<code>import 'package:flutter/material.dart';

class CheckinAccessories extends StatefulWidget {
  @override
  _CheckinAccessoriesState createState() => _CheckinAccessoriesState();
}

class _CheckinAccessoriesState extends State<CheckinAccessories> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0XFF3a6fd8),
      body: Container(
        padding: EdgeInsets.only(top: 30.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[backButton(), welcomeText(), mainContent()],
        ),
      ),
      bottomNavigationBar: Container(
        height: 60.0,
        child: FlatButton(
          onPressed: () {},
          color: Color(0XFF3a6fd8),
          textColor: Colors.white,
          child: Text('Next', style: TextStyle(fontSize: 20.0)),
        ),
      ),
    );
  }

  Container backButton() {
    return Container(
      margin: EdgeInsets.all(10.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          RaisedButton.icon(
              color: Color(0XFF265abf),
              onPressed: () {
                Navigator.of(context).pop(true);
              },
              icon: Icon(
                Icons.arrow_back,
                color: Colors.white,
              ),
              label: Text('Back',
                  style: TextStyle(
                    color: Colors.white,
                  ))),
        ],
      ),
    );
  }

  Container welcomeText() {
    return Container(
        decoration: BoxDecoration(
            image: DecorationImage(
                image: AssetImage("assets/images/bg_car.png"),
                fit: BoxFit.contain)),
        padding: EdgeInsets.all(10.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text('Accessories',
                style: TextStyle(
                    fontSize: 40.0,
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                    height: 1.3)),
          ],
        ));
  }

  Container mainContent() {
    return Container(
      padding: EdgeInsets.all(30.0),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.only(
            topLeft: Radius.circular(50), topRight: Radius.circular(50)),
        color: Color(0XFFedeff1),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            'Accessories List',
            style: TextStyle(
                fontSize: 15.0,
                fontWeight: FontWeight.bold,
                color: Color(0XFF132758)),
          ),
          Row(
            children: <Widget>[
              CheckboxWidget()
            ],
          )

        ],
      ),
    );
  }
}

class CheckboxWidget extends StatefulWidget {
  @override
  CheckboxWidgetState createState() => new CheckboxWidgetState();
}

class CheckboxWidgetState extends State {
  Map<String, bool> values = {
    'Apple': false,
    'Banana': false,
    'Cherry': false,
    'Mango': false,
    'Orange': false,
  };

  var tmpArray = [];

  getCheckboxItems() {
    values.forEach((key, value) {
      if (value == true) {
        tmpArray.add(key);
      }
    });

    // Printing all selected items on Terminal screen.
    print(tmpArray);
    // Here you will get all your selected Checkbox items.

    // Clear array after use.
    tmpArray.clear();
  }

  @override
  Widget build(BuildContext context) {
    // return Column(
    //   children: <Widget>[
    //     Text('test')
    //   ],
    // );
    return Column(children: <Widget>[
      Text('test'),
      Expanded(
        child: ListView(

          children: values.keys.map((String key) {
            return new CheckboxListTile(
              title: new Text(key),
              value: values[key],
              activeColor: Colors.pink,
              checkColor: Colors.white,
              onChanged: (bool value) {
                setState(() {
                  values[key] = value;
                });
              },
            );
          }).toList(),
        ),
      ),
    ]);
  }
}
</code>```

答:
There's a few things you need to understand first.

Column takes as much height as it can get. Since in your case Column doesn't have a height neither does it have a parent to constrain it's height. So your column takes INFINITE height.

Further more Expanded has similar functionality as that of column in regards to the feature that Expanded is supposed to take up all the space remaining out the height of it's parent. For e.g. if you have

```<code>Container(
    height: 400,
    child: Column(children: <Widget>[
    Text('test'),
    Expanded(
      child: ...
    ),
  ]),
)
</code>```

If the Text takes up 50 then the rest of the height will be assigned to Expanded

And since in your case Column already takes INFINITE height Expanded will get the remaining except Text which again is INFINITE.

The Solution:

Wrap your Column with a container and then use any one of the two:

and give it a fixed height.

if you want dynamic height then check out the MediaQuery Widget

Body:
I am trying to add a list view inside a column but it crashes

I have got the following Errors:

RenderFlex children have non-zero flex but incoming height constraints
  are unbounded.

RenderBox was not laid out: RenderFlex#e1a1e relayoutBoundary=up7
  NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
  'package:flutter/src/rendering/box.dart': Failed assertion: line 1687
  pos 12: 'hasSize'

The method '>' was called on null. Receiver: null

This is my Code:

import 'package:flutter/material.dart';

class CheckinAccessories extends StatefulWidget {
  @override
  _CheckinAccessoriesState createState() => _CheckinAccessoriesState();
}

class _CheckinAccessoriesState extends State<CheckinAccessories> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0XFF3a6fd8),
      body: Container(
        padding: EdgeInsets.only(top: 30.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[backButton(), welcomeText(), mainContent()],
        ),
      ),
      bottomNavigationBar: Container(
        height: 60.0,
        child: FlatButton(
          onPressed: () {},
          color: Color(0XFF3a6fd8),
          textColor: Colors.white,
          child: Text('Next', style: TextStyle(fontSize: 20.0)),
        ),
      ),
    );
  }

  Container backButton() {
    return Container(
      margin: EdgeInsets.all(10.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          RaisedButton.icon(
              color: Color(0XFF265abf),
              onPressed: () {
                Navigator.of(context).pop(true);
              },
              icon: Icon(
                Icons.arrow_back,
                color: Colors.white,
              ),
              label: Text('Back',
                  style: TextStyle(
                    color: Colors.white,
                  ))),
        ],
      ),
    );
  }

  Container welcomeText() {
    return Container(
        decoration: BoxDecoration(
            image: DecorationImage(
                image: AssetImage("assets/images/bg_car.png"),
                fit: BoxFit.contain)),
        padding: EdgeInsets.all(10.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text('Accessories',
                style: TextStyle(
                    fontSize: 40.0,
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                    height: 1.3)),
          ],
        ));
  }

  Container mainContent() {
    return Container(
      padding: EdgeInsets.all(30.0),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.only(
            topLeft: Radius.circular(50), topRight: Radius.circular(50)),
        color: Color(0XFFedeff1),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            'Accessories List',
            style: TextStyle(
                fontSize: 15.0,
                fontWeight: FontWeight.bold,
                color: Color(0XFF132758)),
          ),
          Row(
            children: <Widget>[
              CheckboxWidget()
            ],
          )

        ],
      ),
    );
  }
}

class CheckboxWidget extends StatefulWidget {
  @override
  CheckboxWidgetState createState() => new CheckboxWidgetState();
}

class CheckboxWidgetState extends State {
  Map<String, bool> values = {
    'Apple': false,
    'Banana': false,
    'Cherry': false,
    'Mango': false,
    'Orange': false,
  };

  var tmpArray = [];

  getCheckboxItems() {
    values.forEach((key, value) {
      if (value == true) {
        tmpArray.add(key);
      }
    });

    // Printing all selected items on Terminal screen.
    print(tmpArray);
    // Here you will get all your selected Checkbox items.

    // Clear array after use.
    tmpArray.clear();
  }

  @override
  Widget build(BuildContext context) {
    // return Column(
    //   children: <Widget>[
    //     Text('test')
    //   ],
    // );
    return Column(children: <Widget>[
      Text('test'),
      Expanded(
        child: ListView(

          children: values.keys.map((String key) {
            return new CheckboxListTile(
              title: new Text(key),
              value: values[key],
              activeColor: Colors.pink,
              checkColor: Colors.white,
              onChanged: (bool value) {
                setState(() {
                  values[key] = value;
                });
              },
            );
          }).toList(),
        ),
      ),
    ]);
  }
}

Body:
There's a few things you need to understand first.

Column takes as much height as it can get. Since in your case Column doesn't have a height neither does it have a parent to constrain it's height. So your column takes INFINITE height.

Further more Expanded has similar functionality as that of column in regards to the feature that Expanded is supposed to take up all the space remaining out the height of it's parent. For e.g. if you have

Container(
    height: 400,
    child: Column(children: <Widget>[
    Text('test'),
    Expanded(
      child: ...
    ),
  ]),
)

If the Text takes up 50 then the rest of the height will be assigned to Expanded

And since in your case Column already takes INFINITE height Expanded will get the remaining except Text which again is INFINITE.

The Solution:

Wrap your Column with a container and then use any one of the two:

and give it a fixed height.

if you want dynamic height then check out the MediaQuery Widget