问:
JS- Show html based on wrapper class
I'm using the following code to show more/show less on a page.

CSS

```<code>#more {display: none;}
.read-more-less{padding-bottom: 20px;text-align: center;display: block !important;margin:auto;width: 200px;height: 40px;font-size: 16px;margin-top: 15px;}
</code>```

JS

```<code>function myFunction() {
  var dots = document.getElementById("dots");
  var moreText = document.getElementById("more");
  var btnText = document.getElementById("myBtn");

  if (dots.style.display === "none") {
    dots.style.display = "inline";
    btnText.innerHTML = "Show more";
    moreText.style.display = "none";
  } else {
    dots.style.display = "none";
    btnText.innerHTML = "Show less";
    moreText.style.display = "inline";
  }
}
</code>```

HTML

```<code><div class="show-more">

<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</p>
<p>
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</p><span id="dots"></span><span id="more">
<p>
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
</p>
<p>
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
</span><a class="read-more-less btn" href="#"><span onclick="myFunction()" id="myBtn">Show more</span></a>
</div>
</code>```

This the jsfiddle

Now if the html block is placed within another div (like an include) where "class="change"

```<code><div class="change">
    <div class="show-more">

        <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
        </p>
        <p>
            Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
        </p><span id="dots"></span><span id="more">
            <p>
                Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
            </p>
            <p>
                Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            </p>
        </span><a class="read-more-less btn" href="#"><span onclick="myFunction()" id="myBtn">Show more</span></a>
    </div>
</div>
</code>```

Is there a way of changing the child div class class="show-more"  to class="show-none"

How could this be done?

答:
You can use CSS to do this.

It is easiest if you always print the span tag and then only display it when necessary. Also, instead of using 'show-button', it would be easier to use 'hide-button':

```<code><div class="hide-button"><!-- content is hidden -->
<span id="dots"></span><span id="more">
</div>

<div class=""><!-- content is displayed -->
<span id="dots"></span><span id="more">
</div>

<style>
.hide-button {
    display: none;
}
</style>
</code>```

EDIT (in response to edited question):

There are a couple of ways to get the element that you want to change the class for. You can use either of the following lines of code:

```<code>// Get an element using its class name
var elem = document.getElementsByClassName('show-more')[0];

// OR

// Get an element using its CSS selector
var elem = document.querySelector('.show-more');
</code>```

Once you have the element that you want to adjust the classes for, you can make the adjustments using code similar to the following:

```<code>// 'show-more' class is present
if (elem.classList.contains('show-more')) {
    elem.classList.remove('show-more');
    elem.classList.add('show-none');

// 'show-more' class is NOT present
} else {
    elem.classList.remove('show-none');
    elem.classList.add('show-more');
}
</code>```

Title: JS- Show html based on wrapper class

Body:
I'm using the following code to show more/show less on a page.

CSS

#more {display: none;}
.read-more-less{padding-bottom: 20px;text-align: center;display: block !important;margin:auto;width: 200px;height: 40px;font-size: 16px;margin-top: 15px;}

JS

function myFunction() {
  var dots = document.getElementById("dots");
  var moreText = document.getElementById("more");
  var btnText = document.getElementById("myBtn");

  if (dots.style.display === "none") {
    dots.style.display = "inline";
    btnText.innerHTML = "Show more";
    moreText.style.display = "none";
  } else {
    dots.style.display = "none";
    btnText.innerHTML = "Show less";
    moreText.style.display = "inline";
  }
}

HTML

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.

Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Show more

This the jsfiddle

Now if the html block is placed within another div (like an include) where "class="change"

            Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

            Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

                Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.

                Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

        Show more

Is there a way of changing the child div class class="show-more"  to class="show-none"

How could this be done?

Body:
You can use CSS to do this.

It is easiest if you always print the span tag and then only display it when necessary. Also, instead of using 'show-button', it would be easier to use 'hide-button':

<div class="hide-button"><!-- content is hidden -->
<span id="dots"></span><span id="more">
</div>

<div class=""><!-- content is displayed -->
<span id="dots"></span><span id="more">
</div>

<style>
.hide-button {
    display: none;
}
</style>

EDIT (in response to edited question):

There are a couple of ways to get the element that you want to change the class for. You can use either of the following lines of code:

// Get an element using its class name
var elem = document.getElementsByClassName('show-more')[0];

// OR

// Get an element using its CSS selector
var elem = document.querySelector('.show-more');

Once you have the element that you want to adjust the classes for, you can make the adjustments using code similar to the following:

// 'show-more' class is present
if (elem.classList.contains('show-more')) {
    elem.classList.remove('show-more');
    elem.classList.add('show-none');

// 'show-more' class is NOT present
} else {
    elem.classList.remove('show-none');
    elem.classList.add('show-more');
}


来源: stackexchange

问:
Ruby: combining methods into 1 line
I have an array of objects, and I want to take one of the methods to return it into 1 single line.

here is my array

```<code>def set
        @seconds = Counter.new('Seconds')
        @minutes = Counter.new('Minutes')
        @hours = Counter.new('Hours')

        @time = [@seconds, @minutes, @hours]
    end
</code>```

and here is the method I'm trying to print in the Counter class

```<code>    def count
        @counts
    end
</code>```

Here's my attempt

```<code>    def read
        reverse = @time.reverse
        @time.each do |t|
            return '%02d' %t.count.to_s.join(":")
        end
    end
</code>```

(I also want them to be in 00, 01 formats, hence the '%02d')

.join doesn't seem to work (I'm guessing it works with arrays but not methods of an array?

any help will be appreciated!

答:
You're very close!

You need to do the joining outside of your loop, and use collect instead of each. Here is an irb session that should help you figure things out:

```<code>>> seconds = 35
>> minutes = 9
>> hours = 11
>> time = [seconds, minutes, hours]
>> time.reverse.collect{|t| "%02d" % t}.join(":")
=> "11:09:35"
</code>```

The idea is that collect (called map in other languages) applies the stringification operation to each array element, turning

```<code>[11, 9, 35]
</code>```

into

```<code>["11", "09", "35"]
</code>```

then you can do the join on this array.

ContentLicense: CC BY-SA 4.0

Title: Ruby: combining methods into 1 line

Body:
I have an array of objects, and I want to take one of the methods to return it into 1 single line.

here is my array

def set
        @seconds = Counter.new('Seconds')
        @minutes = Counter.new('Minutes')
        @hours = Counter.new('Hours')

        @time = [@seconds, @minutes, @hours]
    end

and here is the method I'm trying to print in the Counter class

    def count
        @counts
    end

Here's my attempt

    def read
        reverse = @time.reverse
        @time.each do |t|
            return '%02d' %t.count.to_s.join(":")
        end
    end

(I also want them to be in 00, 01 formats, hence the '%02d')

.join doesn't seem to work (I'm guessing it works with arrays but not methods of an array?

any help will be appreciated!

Body:
You're very close!

You need to do the joining outside of your loop, and use collect instead of each. Here is an irb session that should help you figure things out:

>> seconds = 35
>> minutes = 9
>> hours = 11
>> time = [seconds, minutes, hours]
>> time.reverse.collect{|t| "%02d" % t}.join(":")
=> "11:09:35"

The idea is that collect (called map in other languages) applies the stringification operation to each array element, turning

[11, 9, 35]

into

["11", "09", "35"]

then you can do the join on this array.


问:
Flutter - Unhandled Exception: type '(dynamic) => Null' is not a subtype of type '(String, dynamic) => void' of 'f'
Not sure on reason why I am getting error " Unhandled Exception: type '(dynamic) => Null' is not a subtype of type '(String, dynamic) => void' of 'f' ". Everything seems to be done correctly but still getting error</p>

```<code>Json link: https://androidapp.factory2homes.com/api/get-shipping-address-by-user-id/3
</code>```

```<code>class ShippingAddressPage extends StatefulWidget {
  @override
  _ShippingAddressPageState createState() => _ShippingAddressPageState();
}

class _ShippingAddressPageState extends State<ShippingAddressPage> {

  List<Shipping> _shippingAddressList = List<Shipping>();

 @override
 void initState() {
   super.initState();
   _getShippingAddressByUserId();
 }

 _getShippingAddressByUserId() async {
   SharedPreferences _prefs = await SharedPreferences.getInstance();
   int _userId = _prefs.getInt('userId');
   ShippingAddressService _shippingAddressService = ShippingAddressService();
   var result = await _shippingAddressService.getShippingAddressByUserId(_userId);
   var shipping = json.decode(result.body);
   shipping.forEach((shipping){
     var model = Shipping();
     model.id = shipping['id'];
     model.name = shipping['name'];
     model.address = shipping['address'];
     setState(() {
       _shippingAddressList.add(model);
     });
   });
 }
</code>```

```<code>E/flutter (26002): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type '(dynamic) => Null' is not a subtype of type '(String, dynamic) => void' of 'f'
E/flutter (26002): #0      _ShippingAddressPageState._getShippingAddressByUserId (package:factory2homes/screens/shipping_address_page.dart:32:13)
E/flutter (26002): <asynchronous suspension>
E/flutter (26002): #1      _ShippingAddressPageState.initState (package:factory2homes/screens/shipping_address_page.dart:22:4)
</code>```

```<code>class ShippingAddressService{
  Repository _repository;

  ShippingAddressService(){
    _repository = Repository();
  }

  getShippingAddressByUserId(int userId) async {
    return await _repository.httpGetById('get-shipping-address-by-user-id', userId);
  }

}
</code>```

答:
You can copy paste run full code below

You can define return type to getShippingAddressByUserId() and _getShippingAddressByUserId()

You can check class Shipping definition and FutureBuilder in full code

code snippet

```<code>Future<http.Response> getShippingAddressByUserId(int userId) async {
    //return await _repository.httpGetById('get-shipping-address-by-user-id', userId);
    return await http.get(
        "https://androidapp.factory2homes.com/api/get-shipping-address-by-user-id/3");
  }

Future<Shipping> _getShippingAddressByUserId() async {
    //SharedPreferences _prefs = await SharedPreferences.getInstance();
    int _userId = 3; //_prefs.getInt('userId');
    ShippingAddressService _shippingAddressService = ShippingAddressService();
    var result =
        await _shippingAddressService.getShippingAddressByUserId(_userId);
    if (result.statusCode == 200) {
      return shippingFromJson(result.body);
    }
  }
</code>```

working demo

full code

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

Shipping shippingFromJson(String str) => Shipping.fromJson(json.decode(str));

String shippingToJson(Shipping data) => json.encode(data.toJson());

class Shipping {
  Shipping({
    this.data,
  });

  List<Datum> data;

  factory Shipping.fromJson(Map<String, dynamic> json) => Shipping(
        data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "data": List<dynamic>.from(data.map((x) => x.toJson())),
      };
}

class Datum {
  Datum({
    this.id,
    this.name,
    this.address,
    this.userId,
    this.createdAt,
    this.updatedAt,
  });

  int id;
  String name;
  String address;
  int userId;
  DateTime createdAt;
  DateTime updatedAt;

  factory Datum.fromJson(Map<String, dynamic> json) => Datum(
        id: json["id"],
        name: json["name"],
        address: json["address"],
        userId: json["user_id"],
        createdAt: DateTime.parse(json["created_at"]),
        updatedAt: DateTime.parse(json["updated_at"]),
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "name": name,
        "address": address,
        "user_id": userId,
        "created_at": createdAt.toIso8601String(),
        "updated_at": updatedAt.toIso8601String(),
      };
}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: ShippingAddressPage(title: 'Flutter Demo Home Page'),
    );
  }
}

class ShippingAddressService {
  //Repository _repository;

  ShippingAddressService() {
    //_repository = Repository();
  }

  Future<http.Response> getShippingAddressByUserId(int userId) async {
    //return await _repository.httpGetById('get-shipping-address-by-user-id', userId);
    return await http.get(
        "https://androidapp.factory2homes.com/api/get-shipping-address-by-user-id/3");
  }
}

class ShippingAddressPage extends StatefulWidget {
  ShippingAddressPage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _ShippingAddressPageState createState() => _ShippingAddressPageState();
}

class _ShippingAddressPageState extends State<ShippingAddressPage> {
  int _counter = 0;
  Future<Shipping> _future;

  Future<Shipping> _getShippingAddressByUserId() async {
    //SharedPreferences _prefs = await SharedPreferences.getInstance();
    int _userId = 3; //_prefs.getInt('userId');
    ShippingAddressService _shippingAddressService = ShippingAddressService();
    var result =
        await _shippingAddressService.getShippingAddressByUserId(_userId);
    if (result.statusCode == 200) {
      return shippingFromJson(result.body);
    }
  }

  @override
  void initState() {
    _future = _getShippingAddressByUserId();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: FutureBuilder(
            future: _future,
            builder: (context, AsyncSnapshot<Shipping> snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                  return Text('none');
                case ConnectionState.waiting:
                  return Center(child: CircularProgressIndicator());
                case ConnectionState.active:
                  return Text('');
                case ConnectionState.done:
                  if (snapshot.hasError) {
                    return Text(
                      '${snapshot.error}',
                      style: TextStyle(color: Colors.red),
                    );
                  } else {
                    return ListView.builder(
                        itemCount: snapshot.data.data.length,
                        itemBuilder: (context, index) {
                          return Card(
                              elevation: 6.0,
                              child: Padding(
                                padding: const EdgeInsets.only(
                                    top: 6.0,
                                    bottom: 6.0,
                                    left: 8.0,
                                    right: 8.0),
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text(snapshot.data.data[index].name),
                                    Spacer(),
                                    Text(snapshot.data.data[index].id
                                        .toString()),
                                  ],
                                ),
                              ));
                        });
                  }
              }
            }));
  }
}
</code>```

Body:
Not sure on reason why I am getting error " Unhandled Exception: type '(dynamic) => Null' is not a subtype of type '(String, dynamic) => void' of 'f' ". Everything seems to be done correctly but still getting error

Json link: https://androidapp.factory2homes.com/api/get-shipping-address-by-user-id/3

class ShippingAddressPage extends StatefulWidget {
  @override
  _ShippingAddressPageState createState() => _ShippingAddressPageState();
}

class _ShippingAddressPageState extends State<ShippingAddressPage> {

  List<Shipping> _shippingAddressList = List<Shipping>();

 @override
 void initState() {
   super.initState();
   _getShippingAddressByUserId();
 }

 _getShippingAddressByUserId() async {
   SharedPreferences _prefs = await SharedPreferences.getInstance();
   int _userId = _prefs.getInt('userId');
   ShippingAddressService _shippingAddressService = ShippingAddressService();
   var result = await _shippingAddressService.getShippingAddressByUserId(_userId);
   var shipping = json.decode(result.body);
   shipping.forEach((shipping){
     var model = Shipping();
     model.id = shipping['id'];
     model.name = shipping['name'];
     model.address = shipping['address'];
     setState(() {
       _shippingAddressList.add(model);
     });
   });
 }

E/flutter (26002): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type '(dynamic) => Null' is not a subtype of type '(String, dynamic) => void' of 'f'
E/flutter (26002): #0      _ShippingAddressPageState._getShippingAddressByUserId (package:factory2homes/screens/shipping_address_page.dart:32:13)
E/flutter (26002): <asynchronous suspension>
E/flutter (26002): #1      _ShippingAddressPageState.initState (package:factory2homes/screens/shipping_address_page.dart:22:4)

class ShippingAddressService{
  Repository _repository;

  ShippingAddressService(){
    _repository = Repository();
  }

  getShippingAddressByUserId(int userId) async {
    return await _repository.httpGetById('get-shipping-address-by-user-id', userId);
  }

}

Body:
You can copy paste run full code below

You can define return type to getShippingAddressByUserId() and _getShippingAddressByUserId()

You can check class Shipping definition and FutureBuilder in full code

code snippet

Future<http.Response> getShippingAddressByUserId(int userId) async {
    //return await _repository.httpGetById('get-shipping-address-by-user-id', userId);
    return await http.get(
        "https://androidapp.factory2homes.com/api/get-shipping-address-by-user-id/3");
  }

Future<Shipping> _getShippingAddressByUserId() async {
    //SharedPreferences _prefs = await SharedPreferences.getInstance();
    int _userId = 3; //_prefs.getInt('userId');
    ShippingAddressService _shippingAddressService = ShippingAddressService();
    var result =
        await _shippingAddressService.getShippingAddressByUserId(_userId);
    if (result.statusCode == 200) {
      return shippingFromJson(result.body);
    }
  }

working demo

full code

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

Shipping shippingFromJson(String str) => Shipping.fromJson(json.decode(str));

String shippingToJson(Shipping data) => json.encode(data.toJson());

class Shipping {
  Shipping({
    this.data,
  });

  List<Datum> data;

  factory Shipping.fromJson(Map<String, dynamic> json) => Shipping(
        data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "data": List<dynamic>.from(data.map((x) => x.toJson())),
      };
}

class Datum {
  Datum({
    this.id,
    this.name,
    this.address,
    this.userId,
    this.createdAt,
    this.updatedAt,
  });

  int id;
  String name;
  String address;
  int userId;
  DateTime createdAt;
  DateTime updatedAt;

  factory Datum.fromJson(Map<String, dynamic> json) => Datum(
        id: json["id"],
        name: json["name"],
        address: json["address"],
        userId: json["user_id"],
        createdAt: DateTime.parse(json["created_at"]),
        updatedAt: DateTime.parse(json["updated_at"]),
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "name": name,
        "address": address,
        "user_id": userId,
        "created_at": createdAt.toIso8601String(),
        "updated_at": updatedAt.toIso8601String(),
      };
}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: ShippingAddressPage(title: 'Flutter Demo Home Page'),
    );
  }
}

class ShippingAddressService {
  //Repository _repository;

  ShippingAddressService() {
    //_repository = Repository();
  }

  Future<http.Response> getShippingAddressByUserId(int userId) async {
    //return await _repository.httpGetById('get-shipping-address-by-user-id', userId);
    return await http.get(
        "https://androidapp.factory2homes.com/api/get-shipping-address-by-user-id/3");
  }
}

class ShippingAddressPage extends StatefulWidget {
  ShippingAddressPage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _ShippingAddressPageState createState() => _ShippingAddressPageState();
}

class _ShippingAddressPageState extends State<ShippingAddressPage> {
  int _counter = 0;
  Future<Shipping> _future;

  Future<Shipping> _getShippingAddressByUserId() async {
    //SharedPreferences _prefs = await SharedPreferences.getInstance();
    int _userId = 3; //_prefs.getInt('userId');
    ShippingAddressService _shippingAddressService = ShippingAddressService();
    var result =
        await _shippingAddressService.getShippingAddressByUserId(_userId);
    if (result.statusCode == 200) {
      return shippingFromJson(result.body);
    }
  }

  @override
  void initState() {
    _future = _getShippingAddressByUserId();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: FutureBuilder(
            future: _future,
            builder: (context, AsyncSnapshot<Shipping> snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                  return Text('none');
                case ConnectionState.waiting:
                  return Center(child: CircularProgressIndicator());
                case ConnectionState.active:
                  return Text('');
                case ConnectionState.done:
                  if (snapshot.hasError) {
                    return Text(
                      '${snapshot.error}',
                      style: TextStyle(color: Colors.red),
                    );
                  } else {
                    return ListView.builder(
                        itemCount: snapshot.data.data.length,
                        itemBuilder: (context, index) {
                          return Card(
                              elevation: 6.0,
                              child: Padding(
                                padding: const EdgeInsets.only(
                                    top: 6.0,
                                    bottom: 6.0,
                                    left: 8.0,
                                    right: 8.0),
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text(snapshot.data.data[index].name),
                                    Spacer(),
                                    Text(snapshot.data.data[index].id
                                        .toString()),
                                  ],
                                ),
                              ));
                        });
                  }
              }
            }));
  }
}


问:
Is there a way to include a library, such as Angular Material, in my own custom library?
I am trying to use storybook with this library and have a test component that uses the MatRadioModule from Material. I get the following error in my Jest unit test.

Template parse errors:
    'mat-radio-button' is not a known element:
    1. If 'mat-radio-button' is an Angular component, then verify that it is part of this module.
    2. If 'mat-radio-button' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("

My storybook and unit tests work until I try to use Material components, and then it breaks.

答:
this question has been answered here.

In general, code that your libraries depend on should be added to the peerDependencies in the package.json of that library.

Hope this helps.


问:
Connectivity issues between SqlAlchemy/PyODBC and SQL Server running in Docker
I have a flask app that uses SQLAlchemy (v1.3.17)/PyODBC (v4.0.30) to connect to a SQL Server. In my development setup, the SQL server runs inside a Docker container using mcr.microsoft.com/mssql/server:2017-latest-ubuntu image with Docker Desktop for Mac (v2.3.0.3).

It has been working with this setup for a while now (~6 months), but for the last month or so I have been running into the following error all the time

(pyodbc.OperationalError) ('08S01', '[08S01] [Microsoft][ODBC Driver 17 for SQL Server]TCP Provider: Error code 0x274C (10060)

It happens intermittently, at different places in the code, and when I rerun the same code again it doesn't occur. So I don't think it is anything fundamentally wrong with my code.

10060 appears to be a connection error, but since it is able to connect initially okay, I am thinking that something failing in pyodbc when it is trying to keep the connection alive.

Has anyone else run into something similar? Is there a timeout value that I need to set in my SQL Server config? Thankfully, on the production server (which isn't running in Docker) I am not running into this problem. But it happens every couple of minutes so is very frustrating when I am debugging.

答: Thanks Ed, Gin (feel free to post as answer if you would like me to endorse it). http://github.com/sqlalchemy/sqlalchemy/issues/5148 is the same issue and the 'pool_pre_ping' engine option suggested on there seems to have done the trick.</p>


问:
Change owner of Azure AD
How do you change the owner of an Azure AD directory? I have two accounts and see the tenant/directory I want listed as a directory. I want to transfer the ownership to the other account.

UPDATE
Ok. More information. I had one subscription and created 3 B2C directories. Each time I linked to the subscription, which is part of the process. Apparently you cannot have more than 1 B2C tenant linked to a subscription, so the other two were left "stranded" outside of a subscription. So I had to create a new subscription and associate the B2C directory with it, so it was a resource of the subscription. Then I used IAM to add the 2nd Azure account as a co-administrator of the subscription. I transferred the subscription to the 2nd Azure account.

答: The biggest authority in Azure AD is Global administrator. If you want to transfer ownership to another user, you only need to give that user Global administrator.

Title: Change owner of Azure AD


问:
Why does javascript onchange event only work in first modal from a data table
Hello and I thank you for taking the time to read my question.

This is my first post, I have tried to be as comprehensive as possible and follow the expected requirements of posting!

My set up

I have a data table populated from a mysql database, each row has an 'Edit' button.

The 'Edit' button opens a modal with the data from the row. This all works correctly.

In the modal form, I have a 'select' dropdown element with an 'onchange' event to trigger a message.

The issue

From within the first modal (opened from the first table row's 'Edit' button) the
 message is triggered no problem - in the modal window linked to the first row.

But if I click on any other row's 'Edit' button to launch it's modal - and then I change the 'select' dropdown value, the message is not displayed - as if the javascript function is not being processed.

My Research so far

Having spent time googling and searching through Stack Overflow, I think the problem could be related to non-unique IDs or Class Names - and may be they should be different for each record row?

I tried to implement this by generating ID names and Class Names dynamically by using the row's ID number - so each modal had it's own unique ID for the 'select' element - but this did not fix the issue.

I am also thinking it could be a cache issue where the script is holding on to old data, but it does not matter if I click the first row on the first time, or if I click the first row after clicking several other rows before it, it is only the first row which successfully processes the onchange event.

My files

index.php (to display the data table and 'Edit' buttons)

```<code>    <table>
    <thead>
        <th>Fruit ID</th>
        <th>Fruit Name</th>
        <th>Action</th>
    </thead>
    <tbody>
        <tr>
            <td><?php echo $row['fruitID']; ?></td>
            <td><?php echo $row['fruitName']; ?></td>
            <td>
            <a href="#edit<?php echo $row['fruitID']; ?>" data-toggle="modal" class="btn btn-warning">Edit</a>
            <?php include('button.php'); ?>
            </td>
        </tr>
    </tbody>
</table>
</code>```

button.php (the modal content with 'select' element and message div)

```<code>    <div class="modal fade" id="edit<?php echo $row['fruitID']; ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-body">

        <div class="row">
        <div>
            <select class="mySelector" id="mySelector" name="mySelector" onchange="show_value()">
                <option value="Apple">Apple</option>
                <option value="Orange">Orange</option>
                <option value="Banana">Banana</option>
                <option value="Mango">Mango</option>
            </select>
        </div>
    </div>

    <div class="row">
        <div id="result"></div>
    </div>
</div>
</div>
</code>```

script (at the bottom of button.php to trigger the message)

```<code><script>
function show_value() {
        selected_value = document.getElementById("mySelector").value;
        document.getElementById("result").innerHTML = "Selected value is "+selected_value;
        }
</script>
</code>```

答:
you can pass the current id in javascript by just using this.id here is an example

```<code><input type="text" id="username" class="form-control" name="username"  onchange="formhelper(this.id)">
</code>```

now in your function you can use this id as you like example

```<code>function formhelper(currentID)
{

  consolele.log('the current id is ' + currentID);
}
</code>```

you can also make the id dinamically using the php tags using this example

```<code>id="<?= $value['id']?>"
</code>```

Body:
Hello and I thank you for taking the time to read my question.

This is my first post, I have tried to be as comprehensive as possible and follow the expected requirements of posting!

My set up

I have a data table populated from a mysql database, each row has an 'Edit' button.

The 'Edit' button opens a modal with the data from the row. This all works correctly.

In the modal form, I have a 'select' dropdown element with an 'onchange' event to trigger a message.

The issue

From within the first modal (opened from the first table row's 'Edit' button) the
 message is triggered no problem - in the modal window linked to the first row.

But if I click on any other row's 'Edit' button to launch it's modal - and then I change the 'select' dropdown value, the message is not displayed - as if the javascript function is not being processed.

My Research so far

Having spent time googling and searching through Stack Overflow, I think the problem could be related to non-unique IDs or Class Names - and may be they should be different for each record row?

I tried to implement this by generating ID names and Class Names dynamically by using the row's ID number - so each modal had it's own unique ID for the 'select' element - but this did not fix the issue.

I am also thinking it could be a cache issue where the script is holding on to old data, but it does not matter if I click the first row on the first time, or if I click the first row after clicking several other rows before it, it is only the first row which successfully processes the onchange event.

My files

index.php (to display the data table and 'Edit' buttons)

        Fruit ID
        Fruit Name
        Action

            <?php echo $row['fruitID']; ?>
            <?php echo $row['fruitName']; ?>

            <a href="#edit<?php echo $row['fruitID']; ?>" data-toggle="modal" class="btn btn-warning">Edit
            <?php include('button.php'); ?>

button.php (the modal content with 'select' element and message div)

    <div class="modal fade" id="edit<?php echo $row['fruitID']; ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">

            <select class="mySelector" id="mySelector" name="mySelector" onchange="show_value()">
                <option value="Apple">Apple</option>
                <option value="Orange">Orange</option>
                <option value="Banana">Banana</option>
                <option value="Mango">Mango</option>
            </select>

script (at the bottom of button.php to trigger the message)

Body:
you can pass the current id in javascript by just using this.id here is an example

<input type="text" id="username" class="form-control" name="username"  onchange="formhelper(this.id)">

now in your function you can use this id as you like example

function formhelper(currentID)
{

  consolele.log('the current id is ' + currentID);
}

you can also make the id dinamically using the php tags using this example

id="<?= $value['id']?>"


问:
Using Winforms to connect to SQL Server to easily filter data
I have a Winforms that is connecting to a SQL Server 2008 database.

I would like to be able to easily filter through data in one table.

Here is an example of what I would like:

there are 3 columns in the table, and I will have three textboxes (or any other useful control) on a form that will correspond to those three columns.

the user will be able to input a value in any one of those fields and retrieve the rest of the values pertaining to that field.

Is there already an easy solution for this?

答:
Yes you can use DataSet or DataReader.

http://msdn.microsoft.com/en-us/library/ms171897%28v=vs.80%29.aspx

http://www.dotnetperls.com/datagridview-tutorial

ContentLicense: CC BY-SA 3.0


问:
Async function don't await for result in Unity
i would like to wait with next function to finish previous one first. But i have return before it is finished. Here is code:

```<code>private async Task SetupPlayerDatabase()
{
    Task<string> signInWithPlayGames = SignIn.SignInWithPlayGames();
    userId = await signInWithPlayGames;
    Debug.Log("USER ID: " + userId);
}
</code>```

and the sceound class:

```<code>and SignInWithPlayGames:
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using Firebase.Auth;

public class SignIn : MonoBehaviour
{
    private static string userId;

    void Awake () {
        // Initialize Play Games Configuration and Activate it.
        PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder().RequestServerAuthCode(false /*forceRefresh*/).Build();
        PlayGamesPlatform.InitializeInstance(config);
        PlayGamesPlatform.Activate();
        //Debug.LogFormat("SignInOnClick: Play Games Configuration initialized");
    }

                // HERE IS THIS FUNCTION ↓ ↓ ↓ ↓ ↓ ↓

    public static async Task<string> SignInWithPlayGames () {
        await Task.Run(() => {
        Debug.LogError("SignIn.SignInWithGooglePlay Task is running");
        // Initialize Firebase Auth
        Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance; // Sign In and Get a server auth code.
        UnityEngine.Social.localUser.Authenticate((bool success) =>
        {
            if (!success) {
                Debug.LogError ("SignInOnClick: Failed to Sign into Play Games Services.");
                return;
            }
            string authCode = PlayGamesPlatform.Instance.GetServerAuthCode();
            if (string.IsNullOrEmpty(authCode))
            {
                Debug.LogError("SignInOnClick: Signed into Play Games Services but failed to get the server auth code.");
                return;
            }
            //Debug.LogFormat("SignInOnClick: Auth code is: {0}", authCode); // Use Server Auth Code to make a credential
            Firebase.Auth.Credential credential = Firebase.Auth.PlayGamesAuthProvider.GetCredential(authCode); // Sign In to Firebase with the credential
            auth.SignInWithCredentialAsync(credential).ContinueWith(task => {
            if (task.IsCanceled) {
                Debug.LogError ("SignInOnClick was canceled.");
                return;
            }
            if (task.IsFaulted) {
                Debug.LogError("SignInOnClick encountered an error: " + task.Exception);
                return;
            }
            Firebase.Auth.FirebaseUser newUser = task.Result;
            Debug.LogFormat("SignInOnClick: User signed in successfully: {0} ({1})", newUser.DisplayName, newUser.UserId);
            userId = newUser.UserId;
            // i would like to return userId here, but i cannot
            });
        });
        });
        Debug.LogError("SignIn.SignInWithGooglePlay return: " + userId);
        return userId; // here i return before it have value
    }
}
</code>```

Debugg shows me that first i had return userId; and after this i have userId = newUser.UserId;. So first i have return empty string and next userId get value.

I cannot write return userId; one line under userId = newUser.UserId; becouse it's lambda and return void.

How can i fix it to finish this function in good place and moment? To return userId after make value in this string?

答:
I have solution. I had to split authorization and method to waiting for it because authorization cannot by called from non-main thread (in Unity). Now it's works and look like this:

```<code>private async Task SetupPlayerDatabase()
{
    SignIn signIn = new SignIn();
    Task<string> checkAuthorizedCorrect = signIn.CheckAuthorizedCorrect();
    userId = await checkAuthorizedCorrect;
    Debug.Log("USER ID: " + userId);
}
</code>```

and:

```<code>using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using Firebase.Auth;

public class SignIn : MonoBehaviour
{
    private static bool playerIsAuthorized;
    private static string userId;

    // Use this for initialization
    void Awake () {
        // Initialize Play Games Configuration and Activate it.
        PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder().RequestServerAuthCode(false /*forceRefresh*/).Build();
        PlayGamesPlatform.InitializeInstance(config);
        PlayGamesPlatform.Activate();
        Debug.LogFormat("SignInOnClick: Play Games Configuration initialized");
        SignInWithPlayGames();
    }

public async Task<string> CheckAuthorizedCorrect () {
    await Task.Run(() => {
        while (playerIsAuthorized == false)
        {
            Debug.Log("Waiting for userId");
        }
    });
    return userId;
}

public static void SignInWithPlayGames () {
        // Initialize Firebase Auth
        Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
        Debug.Log("Sign In and Get a server auth code.");
        UnityEngine.Social.localUser.Authenticate((bool success) =>
        {
            if (!success) {
                Debug.LogError ("SignInOnClick: Failed to Sign into Play Games Services.");
                return;
            }
            string authCode = PlayGamesPlatform.Instance.GetServerAuthCode();
            if (string.IsNullOrEmpty(authCode))
            {
                Debug.LogError("SignInOnClick: Signed into Play Games Services but failed to get the server auth code.");
                return;
            }
            Debug.LogFormat("SignInOnClick: Auth code is: {0}", authCode); // Use Server Auth Code to make a credential
            Firebase.Auth.Credential credential = Firebase.Auth.PlayGamesAuthProvider.GetCredential(authCode); // Sign In to Firebase with the credential
            auth.SignInWithCredentialAsync(credential).ContinueWith(task => {
            if (task.IsCanceled) {
                Debug.LogError ("SignInOnClick was canceled.");
                return;
            }
            if (task.IsFaulted) {
                Debug.LogError("SignInOnClick encountered an error: " + task.Exception);
                return;
            }
            Firebase.Auth.FirebaseUser newUser = task.Result;
            Debug.LogFormat("SignInOnClick: User signed in successfully: {0} ({1})", newUser.DisplayName, newUser.UserId);
            userId = newUser.UserId;
            playerIsAuthorized = true;
            });
        });
    }
}
</code>```

Body:
i would like to wait with next function to finish previous one first. But i have return before it is finished. Here is code:

private async Task SetupPlayerDatabase()
{
    Task<string> signInWithPlayGames = SignIn.SignInWithPlayGames();
    userId = await signInWithPlayGames;
    Debug.Log("USER ID: " + userId);
}

and the sceound class:

and SignInWithPlayGames:
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using Firebase.Auth;

public class SignIn : MonoBehaviour
{
    private static string userId;

    void Awake () {
        // Initialize Play Games Configuration and Activate it.
        PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder().RequestServerAuthCode(false /*forceRefresh*/).Build();
        PlayGamesPlatform.InitializeInstance(config);
        PlayGamesPlatform.Activate();
        //Debug.LogFormat("SignInOnClick: Play Games Configuration initialized");
    }

                // HERE IS THIS FUNCTION ↓ ↓ ↓ ↓ ↓ ↓

    public static async Task<string> SignInWithPlayGames () {
        await Task.Run(() => {
        Debug.LogError("SignIn.SignInWithGooglePlay Task is running");
        // Initialize Firebase Auth
        Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance; // Sign In and Get a server auth code.
        UnityEngine.Social.localUser.Authenticate((bool success) =>
        {
            if (!success) {
                Debug.LogError ("SignInOnClick: Failed to Sign into Play Games Services.");
                return;
            }
            string authCode = PlayGamesPlatform.Instance.GetServerAuthCode();
            if (string.IsNullOrEmpty(authCode))
            {
                Debug.LogError("SignInOnClick: Signed into Play Games Services but failed to get the server auth code.");
                return;
            }
            //Debug.LogFormat("SignInOnClick: Auth code is: {0}", authCode); // Use Server Auth Code to make a credential
            Firebase.Auth.Credential credential = Firebase.Auth.PlayGamesAuthProvider.GetCredential(authCode); // Sign In to Firebase with the credential
            auth.SignInWithCredentialAsync(credential).ContinueWith(task => {
            if (task.IsCanceled) {
                Debug.LogError ("SignInOnClick was canceled.");
                return;
            }
            if (task.IsFaulted) {
                Debug.LogError("SignInOnClick encountered an error: " + task.Exception);
                return;
            }
            Firebase.Auth.FirebaseUser newUser = task.Result;
            Debug.LogFormat("SignInOnClick: User signed in successfully: {0} ({1})", newUser.DisplayName, newUser.UserId);
            userId = newUser.UserId;
            // i would like to return userId here, but i cannot
            });
        });
        });
        Debug.LogError("SignIn.SignInWithGooglePlay return: " + userId);
        return userId; // here i return before it have value
    }
}

Debugg shows me that first i had return userId; and after this i have userId = newUser.UserId;. So first i have return empty string and next userId get value.

I cannot write return userId; one line under userId = newUser.UserId; becouse it's lambda and return void.

How can i fix it to finish this function in good place and moment? To return userId after make value in this string?

Body:
I have solution. I had to split authorization and method to waiting for it because authorization cannot by called from non-main thread (in Unity). Now it's works and look like this:

private async Task SetupPlayerDatabase()
{
    SignIn signIn = new SignIn();
    Task<string> checkAuthorizedCorrect = signIn.CheckAuthorizedCorrect();
    userId = await checkAuthorizedCorrect;
    Debug.Log("USER ID: " + userId);
}

and:

using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using Firebase.Auth;

public class SignIn : MonoBehaviour
{
    private static bool playerIsAuthorized;
    private static string userId;

    // Use this for initialization
    void Awake () {
        // Initialize Play Games Configuration and Activate it.
        PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder().RequestServerAuthCode(false /*forceRefresh*/).Build();
        PlayGamesPlatform.InitializeInstance(config);
        PlayGamesPlatform.Activate();
        Debug.LogFormat("SignInOnClick: Play Games Configuration initialized");
        SignInWithPlayGames();
    }

public async Task<string> CheckAuthorizedCorrect () {
    await Task.Run(() => {
        while (playerIsAuthorized == false)
        {
            Debug.Log("Waiting for userId");
        }
    });
    return userId;
}

public static void SignInWithPlayGames () {
        // Initialize Firebase Auth
        Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
        Debug.Log("Sign In and Get a server auth code.");
        UnityEngine.Social.localUser.Authenticate((bool success) =>
        {
            if (!success) {
                Debug.LogError ("SignInOnClick: Failed to Sign into Play Games Services.");
                return;
            }
            string authCode = PlayGamesPlatform.Instance.GetServerAuthCode();
            if (string.IsNullOrEmpty(authCode))
            {
                Debug.LogError("SignInOnClick: Signed into Play Games Services but failed to get the server auth code.");
                return;
            }
            Debug.LogFormat("SignInOnClick: Auth code is: {0}", authCode); // Use Server Auth Code to make a credential
            Firebase.Auth.Credential credential = Firebase.Auth.PlayGamesAuthProvider.GetCredential(authCode); // Sign In to Firebase with the credential
            auth.SignInWithCredentialAsync(credential).ContinueWith(task => {
            if (task.IsCanceled) {
                Debug.LogError ("SignInOnClick was canceled.");
                return;
            }
            if (task.IsFaulted) {
                Debug.LogError("SignInOnClick encountered an error: " + task.Exception);
                return;
            }
            Firebase.Auth.FirebaseUser newUser = task.Result;
            Debug.LogFormat("SignInOnClick: User signed in successfully: {0} ({1})", newUser.DisplayName, newUser.UserId);
            userId = newUser.UserId;
            playerIsAuthorized = true;
            });
        });
    }
}


问:
javascript style on click event
I am trying to do a game menu on javascript, I'm generating HTML with javascript because of practice.

I got this event listener that I should click to obtain the lhyperlink to another page, but when it appears, the hyperlink instead of getting centered by CSS stylesheet, it goes default and gets to the left.

I don't know how it's called in CSS

Here's my code:

```<code>const h1 = document.createElement("h1");
const parr1 = document.createElement("p");
const parr2 = document.createElement("p");
body.appendChild(h1);
body.appendChild(parr1);
body.appendChild(parr2);
h1.innerHTML = "Aventura D&D";
parr1.innerHTML = "Empezar Juego";
parr2.innerHTML = "Cargar juego";

parr1.addEventListener('click', (event) => {
    let a = document.createElement('a');
    let link = document.createTextNode('Juego Nuevo');
    a.appendChild(link);
    a.title = "Juego Nuevo";
    a.href = '/game1.html';
    //Here is the problem!!!!
    document.body.replaceChild(a, parr1);
});
</code>```

I went to the Element Inspector and I was able to modify the element by modifying the body tag. Why?

Here is the CSS sheet

```<code>body{

    background: black;
    color: goldenrod;
    //This is the part that is working but I wonder why if the spawned                                                                                //hyperlink should obey <a> tag
    text-align: center;
}

h1{
    font-size: 9em;
    font-family: 'Courier New', Courier, monospace;
    color: #c90000;
    text-align: center;
}

p{
    font-size: 3em;
    text-align: center;
}

a{
    font-size: 3em;
}
</code>```

答:
I would change from where it says document.body.replaceChild(a, parr1); to say document.body.replaceChild(a, this);. There may be an issue with referencing.

For the text alight, try using a.style.textAlign = "center"; rather than a.styles.cssText('align-text: "center;')

Title: javascript style on click event

Body:
I am trying to do a game menu on javascript, I'm generating HTML with javascript because of practice.

I got this event listener that I should click to obtain the lhyperlink to another page, but when it appears, the hyperlink instead of getting centered by CSS stylesheet, it goes default and gets to the left.

I don't know how it's called in CSS

Here's my code:

const h1 = document.createElement("h1");
const parr1 = document.createElement("p");
const parr2 = document.createElement("p");
body.appendChild(h1);
body.appendChild(parr1);
body.appendChild(parr2);
h1.innerHTML = "Aventura D&D";
parr1.innerHTML = "Empezar Juego";
parr2.innerHTML = "Cargar juego";

parr1.addEventListener('click', (event) => {
    let a = document.createElement('a');
    let link = document.createTextNode('Juego Nuevo');
    a.appendChild(link);
    a.title = "Juego Nuevo";
    a.href = '/game1.html';
    //Here is the problem!!!!
    document.body.replaceChild(a, parr1);
});

I went to the Element Inspector and I was able to modify the element by modifying the body tag. Why?

Here is the CSS sheet

body{

    background: black;
    color: goldenrod;
    //This is the part that is working but I wonder why if the spawned                                                                                //hyperlink should obey  tag
    text-align: center;
}

h1{
    font-size: 9em;
    font-family: 'Courier New', Courier, monospace;
    color: #c90000;
    text-align: center;
}

p{
    font-size: 3em;
    text-align: center;
}

a{
    font-size: 3em;
}


问:
How to switch from block select
I have this happen and I'm not sure what key I pressed to set it to this mode. The block select that I'm referring to is where the typing line becomes a block and if I use the arrow keys to move it's position then it hovers ontop of a character instead of between them. This happens in Android studio and Windows randomly so any help would be great.</p>

答:
I think you have pressed the "Insert" key.

Try to repress the "Insert" key to solve the problem.

Hope it`s helpful~

Title: How to switch from block select


问:
Get comma separated string from Mysql
I'm saving a string from PHP to MySQL like this..

```<code>$groupid = "13, 14, 15, 16"
$write = mysql_query("INSERT INTO table VALUES ('','$groupid')");
</code>```

I'm then trying to extract data from the table if $a = "15"

```<code>$extract = mysql_query("SELECT * FROM table WHERE ustaffid='$ustaffid' AND groupid='$a'");
</code>```

How can I easily match what's in $groupid to $a, while extracting it? Can I do that with MySQL?

答:
I don't know if having spaces in the groupid columns would affect the find_in_set MySQL function, and as @PeeHaa notes searching inside a string is slower and is hard to optimize with indexes.

You should really consider modifying the database schema and normalize it so that instead of saving multiple values in a column, use a dependent table and relate multiple rows to the main table for each groupid value.  That's what relational databases are for.

Title: Get comma separated string from Mysql

Body:
I'm saving a string from PHP to MySQL like this..

$groupid = "13, 14, 15, 16"
$write = mysql_query("INSERT INTO table VALUES ('','$groupid')");

I'm then trying to extract data from the table if $a = "15"

$extract = mysql_query("SELECT * FROM table WHERE ustaffid='$ustaffid' AND groupid='$a'");

How can I easily match what's in $groupid to $a, while extracting it? Can I do that with MySQL?


问:
React Native Vertical Delivery Progress Bar
How can I put a Vertical progress bar on React Native

I need to make a delivery bar progress

**Example: driver is at point A and needs to go to point B ...*

答:
You better try this lib: https://github.com/oblador/react-native-progress#progressbar

Or you can create a your custom progressbar, it pretty simple in React Native. You could try

```<code><View style={{height: 50, width: '100%', flexDirection: 'row'}}>
     <View style={{height: '100%', flex: this.state.currentProgress, backgroundColor: "blue"}}/>
     <View style={{height: '100%', flex: 100 - this.state.currentProgress, backgroundColor: "grey"}}/>
</View>
</code>```

I think that it.

Body:
You better try this lib: https://github.com/oblador/react-native-progress#progressbar

Or you can create a your custom progressbar, it pretty simple in React Native. You could try

<View style={{height: 50, width: '100%', flexDirection: 'row'}}>
     <View style={{height: '100%', flex: this.state.currentProgress, backgroundColor: "blue"}}/>
     <View style={{height: '100%', flex: 100 - this.state.currentProgress, backgroundColor: "grey"}}/>
</View>

I think that it.


问:
Why cannot forward declare a scoped enum?
The title is already the question.

More details: the standard enacts:

If the enum-key is followed by a nested-name-specifier, the enum-specifier shall refer to an enumeration that
  was previously declared directly in the class or namespace to which the nested-name-specifier refers (i.e.,
  neither inherited nor introduced by a using-declaration), and the enum-specifier shall appear in a namespace
  enclosing the previous declaration.

at 7.2, paragraph 4.
For example, this prohibits to forward-declare an enum defined inside a class:

```<code>struct S{
  enum foo{A, B};
};
</code>```

now, S can be forward-declared, while S::foo not.

Question is about why. Is there a situation in which this rule can be a benefit? Why is it needed? Or, if you prefer: if the standard had not this rule, is there a situation in which the compiler would have a problem? Which one(s)?

答:
enum Enumeration; enum is not allowed to forward declare in header file.

enum class Enumeration; enum class is allowed to forward declare in header file.

Body:
The title is already the question.

More details: the standard enacts:

If the enum-key is followed by a nested-name-specifier, the enum-specifier shall refer to an enumeration that
  was previously declared directly in the class or namespace to which the nested-name-specifier refers (i.e.,
  neither inherited nor introduced by a using-declaration), and the enum-specifier shall appear in a namespace
  enclosing the previous declaration.

at 7.2, paragraph 4.
For example, this prohibits to forward-declare an enum defined inside a class:

struct S{
  enum foo{A, B};
};

now, S can be forward-declared, while S::foo not.

Question is about why. Is there a situation in which this rule can be a benefit? Why is it needed? Or, if you prefer: if the standard had not this rule, is there a situation in which the compiler would have a problem? Which one(s)?


问:
Python open() requires full path
I am writing a script to read a csv file. The csv file and script lies in the same directory. But when I tried to open the file it gives me FileNotFoundError: [Errno 2] No such file or directory: 'zipcodes.csv'. The code I used to read the file is

```<code>with open('zipcodes.csv', 'r') as zipcode_file:
    reader = csv.DictReader(zipcode_file)
</code>```

If I give the full path to the file, it will work. Why open() requires full path of the file ?

答:
I used below method and it worked fine for me.</p>

```<code>FILE_PATH = os.path.dirname(os.path.realpath(__file__))
config = ConfigParser.ConfigParser()
config.readfp(open(FILE_PATH+'/conf.properties'))
</code>```

Title: Python open() requires full path

Body:
I am writing a script to read a csv file. The csv file and script lies in the same directory. But when I tried to open the file it gives me FileNotFoundError: [Errno 2] No such file or directory: 'zipcodes.csv'. The code I used to read the file is

with open('zipcodes.csv', 'r') as zipcode_file:
    reader = csv.DictReader(zipcode_file)

If I give the full path to the file, it will work. Why open() requires full path of the file ?

Body:
I used below method and it worked fine for me.

FILE_PATH = os.path.dirname(os.path.realpath(__file__))
config = ConfigParser.ConfigParser()
config.readfp(open(FILE_PATH+'/conf.properties'))


问:
Changing Character base on the given integer?
I am trying to change the given integer to a character

for example:

```<code>N = 5;
result = +-+-+;
</code>```

Right now I am having a hard time implementing this

What I have tried so far is this

```<code>    public void Main()
    {
        int integer;

        Console.WriteLine("How many strings : ");
        integer = Convert.ToInt32(Console.ReadLine());

        ChangeCharacter(integer);
    }

    public void ChangeCharacter(int A)
    {
        string p = "+";
        string m = "-";
        Console.WriteLine("Printing : " + A + " strings");

        for(int i = 0 ; i < A ; i++)
        {
            Console.WriteLine(p,m);
        }
    }

</code>```

the result is only : + + + + + it is not including the - sign

I am just new to c# and I am taking a coding exam to build my logic more . Sorry for my bad english because it is not my mother tongue.

答:
correct  like this :</p>

```<code> for(int i = 0 ; i < A ; i++)
    {
        if(i%2==0)
           Console.Write("+");
        else
           Console.Write("-");

    }
</code>```

Body:
I am trying to change the given integer to a character

for example:

N = 5;
result = +-+-+;

Right now I am having a hard time implementing this

What I have tried so far is this

    public void Main()
    {
        int integer;

        Console.WriteLine("How many strings : ");
        integer = Convert.ToInt32(Console.ReadLine());

        ChangeCharacter(integer);
    }

    public void ChangeCharacter(int A)
    {
        string p = "+";
        string m = "-";
        Console.WriteLine("Printing : " + A + " strings");

        for(int i = 0 ; i < A ; i++)
        {
            Console.WriteLine(p,m);
        }
    }

the result is only : + + + + + it is not including the - sign

I am just new to c# and I am taking a coding exam to build my logic more . Sorry for my bad english because it is not my mother tongue.

Body:
correct  like this :

 for(int i = 0 ; i < A ; i++)
    {
        if(i%2==0)
           Console.Write("+");
        else
           Console.Write("-");

    }


问:
popup remains in the occupied area although closed
I encounter the following problem: I made a simple implementation of a popup, but when I close it and put the cusrsor on the blank area where previously was the popup, I can now click there (in the blank area) and the popup appears again. That is, it seems as if it does not close and it remains in the area which previously it was occuping. Could please someone help me because i do not understand how to make it close permantly.

function fPopUp() {
  var PopUp = document.getElementById("IDPopUp");
  PopUp.classList.toggle("show");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Popup container - can be anything you want */
.popup {
    position: absolute;
    /*display: block;*/
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

/* The actual popup */
.popup .popuptext {
    visibility: hidden;
    /*display: none;*/
    width: 500px;
    background-color: grey;
    color: #fff;
    text-align: left;
    border-radius: 6px;
    padding: 8px 0;
    z-index: 1;
    bottom: 125%;
    left: 50%;
}

/* Popup arrow */
.popup .popuptext::after {
    content: "";
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -5px;
    border-width: 5px;
    border-style: solid;
    border-color: #555 transparent transparent transparent;
}

/* Toggle this class - hide and show the popup */
.popup .show {
    visibility: visible;
    -webkit-animation: fadeIn 1s;
    animation: fadeIn 1s;
}

/* Add animation (fade in the popup) */
@-webkit-keyframes fadeIn {
    from {opacity: 0;}
    to {opacity: 1;}
}

@keyframes fadeIn {
    from {opacity: 0;}
    to {opacity:1 ;}
}</code>```

<button id="bAbout" onclick="fPopUp()">PopUp</button>

  "some text"

```

答:
Using visibility: hidden will hide the element from sight but the element will still occupy its predetermined space on the document. To completely hide the element, you need to use display: none but this doesn't play well with animations.

Your code makes things much more complicated than they have to be, so allow me to make some amendments. Here are a few suggestions:

Put the id on the actual popup instead of its content. You're trying to show/hide the popup, not its text.

This is a rather simple animation, so a simple CSS transition will do just fine.

Use pointer-events: none to make your element unresponsive to mouse events. The element will still occupy the space it normally does, but nobody will know.

function fPopUp() {
  IDPopUp.classList.toggle("show");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Popup container - can be anything you want */
.popup {
    position: absolute;
    cursor: pointer;
    user-select: none;
    pointer-events: none;
    opacity: 0;
    transition: opacity 1s;
}

/* The actual popup */
.popup .popuptext {
    width: 500px;
    background-color: grey;
    color: #fff;
    text-align: left;
    border-radius: 6px;
    padding: 8px 0;
    z-index: 1;
    bottom: 125%;
    left: 50%;
}

/* Popup arrow */
.popup .popuptext::after {
    content: "";
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -5px;
    border-width: 5px;
    border-style: solid;
    border-color: #555 transparent transparent transparent;
}

/* Toggle this class - hide and show the popup */
.popup.show {
    opacity: 1;
    pointer-events: auto;
}</code>```

<button id = "bAbout" onclick = "fPopUp()">PopUp</button>

  "some text"

```

Body:
I encounter the following problem: I made a simple implementation of a popup, but when I close it and put the cusrsor on the blank area where previously was the popup, I can now click there (in the blank area) and the popup appears again. That is, it seems as if it does not close and it remains in the area which previously it was occuping. Could please someone help me because i do not understand how to make it close permantly.

function fPopUp() {
  var PopUp = document.getElementById("IDPopUp");
  PopUp.classList.toggle("show");
}

/* Popup container - can be anything you want */
.popup {
    position: absolute;
    /*display: block;*/
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

/* The actual popup */
.popup .popuptext {
    visibility: hidden;
    /*display: none;*/
    width: 500px;
    background-color: grey;
    color: #fff;
    text-align: left;
    border-radius: 6px;
    padding: 8px 0;
    z-index: 1;
    bottom: 125%;
    left: 50%;
}

/* Popup arrow */
.popup .popuptext::after {
    content: "";
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -5px;
    border-width: 5px;
    border-style: solid;
    border-color: #555 transparent transparent transparent;
}

/* Toggle this class - hide and show the popup */
.popup .show {
    visibility: visible;
    -webkit-animation: fadeIn 1s;
    animation: fadeIn 1s;
}

/* Add animation (fade in the popup) */
@-webkit-keyframes fadeIn {
    from {opacity: 0;}
    to {opacity: 1;}
}

@keyframes fadeIn {
    from {opacity: 0;}
    to {opacity:1 ;}
}

<button id="bAbout" onclick="fPopUp()">PopUp</button>

  "some text"

Body:
Using visibility: hidden will hide the element from sight but the element will still occupy its predetermined space on the document. To completely hide the element, you need to use display: none but this doesn't play well with animations.

Your code makes things much more complicated than they have to be, so allow me to make some amendments. Here are a few suggestions:

Put the id on the actual popup instead of its content. You're trying to show/hide the popup, not its text.

This is a rather simple animation, so a simple CSS transition will do just fine.

Use pointer-events: none to make your element unresponsive to mouse events. The element will still occupy the space it normally does, but nobody will know.

function fPopUp() {
  IDPopUp.classList.toggle("show");
}

/* Popup container - can be anything you want */
.popup {
    position: absolute;
    cursor: pointer;
    user-select: none;
    pointer-events: none;
    opacity: 0;
    transition: opacity 1s;
}

/* The actual popup */
.popup .popuptext {
    width: 500px;
    background-color: grey;
    color: #fff;
    text-align: left;
    border-radius: 6px;
    padding: 8px 0;
    z-index: 1;
    bottom: 125%;
    left: 50%;
}

/* Popup arrow */
.popup .popuptext::after {
    content: "";
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -5px;
    border-width: 5px;
    border-style: solid;
    border-color: #555 transparent transparent transparent;
}

/* Toggle this class - hide and show the popup */
.popup.show {
    opacity: 1;
    pointer-events: auto;
}

<button id = "bAbout" onclick = "fPopUp()">PopUp</button>

<div id = "IDPopUp" class = "popup" onclick = "fPopUp()">
  <span class = "popuptext">"some text"</span>
</div>


问:
How to update slice of struct in recursive fashion
For following code, I'm expecting output of {"NewName" [{"NewName" []}]} but it's not updating child structs. How can we make sure it updates every struct in hierarchy.

```<code>package main

import (
    "fmt"
)

type red struct {
    Name string
    Child []red
}

func (r *red) setName(nameString string){
    r.Name = nameString
    for _, child := range r.Child{
        child.setName(nameString)
    }
}

func main() {
    obj := red{Name:"NameA",Child:[]red{red{Name: "NameB"}}}
    fmt.Print(obj)
    fmt.Print("\n")

    obj.setName("NewName")
    //Expectation {"NewName" [{"NewName" []}]}
    fmt.Print(obj)
}
</code>```

答:
You should make Child be []*red instead of []red to prevent copies of red being created.

See the following tweaks(the String method is just to make the output look pretty, else we'll get memory addresses printed):

```<code>package main

import (
    "fmt"
)

type red struct {
    Name  string
    Child []*red
}

func (r *red) String() string {
    ret := fmt.Sprintf("{%s [", r.Name)
    for _, c := range r.Child {
        ret = ret + c.Name + " "
    }
    ret += "]}"
    return ret
}

func (r *red) setName(s string) {
    r.Name = s
    for _, ch := range r.Child {
        ch.setName(s)
    }
}

func main() {
    obj := red{Name: "A", Child: []*red{&red{Name: "B"}}}
    fmt.Print(obj)
    fmt.Print("\n")

    obj.setName("X")
    //Expectation {X [{X []}]}
    fmt.Print(obj)
}
</code>```

Body:
For following code, I'm expecting output of {"NewName" [{"NewName" []}]} but it's not updating child structs. How can we make sure it updates every struct in hierarchy.

package main

import (
    "fmt"
)

type red struct {
    Name string
    Child []red
}

func (r *red) setName(nameString string){
    r.Name = nameString
    for _, child := range r.Child{
        child.setName(nameString)
    }
}

func main() {
    obj := red{Name:"NameA",Child:[]red{red{Name: "NameB"}}}
    fmt.Print(obj)
    fmt.Print("\n")

    obj.setName("NewName")
    //Expectation {"NewName" [{"NewName" []}]}
    fmt.Print(obj)
}

Body:
You should make Child be []*red instead of []red to prevent copies of red being created.

See the following tweaks(the String method is just to make the output look pretty, else we'll get memory addresses printed):

package main

import (
    "fmt"
)

type red struct {
    Name  string
    Child []*red
}

func (r *red) String() string {
    ret := fmt.Sprintf("{%s [", r.Name)
    for _, c := range r.Child {
        ret = ret + c.Name + " "
    }
    ret += "]}"
    return ret
}

func (r *red) setName(s string) {
    r.Name = s
    for _, ch := range r.Child {
        ch.setName(s)
    }
}

func main() {
    obj := red{Name: "A", Child: []*red{&red{Name: "B"}}}
    fmt.Print(obj)
    fmt.Print("\n")

    obj.setName("X")
    //Expectation {X [{X []}]}
    fmt.Print(obj)
}


答:
You can do that by changing Child []red to a list of pointers: Child []*red.

Here's the full code in Go playground

```<code>package main

import (
    "fmt"
)

type red struct {
    Name string
    Child []*red
}

func (r *red) setName(s string){
    r.Name = s
    for _, ch := range r.Child{
        ch.setName(s)
    }
}

func main() {
    obj := red{Name:"A",Child:[]*red{&red{Name: "B"}}}
    fmt.Println(obj.Name)
    for _, ch := range obj.Child{
       fmt.Println(ch.Name)
    }
    fmt.Print("\n")

    obj.setName("X")
    //Expectation X \n X
    fmt.Println(obj.Name)
    for _, ch := range obj.Child{
       fmt.Println(ch.Name)
    }
}
</code>```

Title: How to update slice of struct in recursive fashion

Body:
You can do that by changing Child []red to a list of pointers: Child []*red.

Here's the full code in Go playground

package main

import (
    "fmt"
)

type red struct {
    Name string
    Child []*red
}

func (r *red) setName(s string){
    r.Name = s
    for _, ch := range r.Child{
        ch.setName(s)
    }
}

func main() {
    obj := red{Name:"A",Child:[]*red{&red{Name: "B"}}}
    fmt.Println(obj.Name)
    for _, ch := range obj.Child{
       fmt.Println(ch.Name)
    }
    fmt.Print("\n")

    obj.setName("X")
    //Expectation X \n X
    fmt.Println(obj.Name)
    for _, ch := range obj.Child{
       fmt.Println(ch.Name)
    }
}


问:
Error in render: "Error: Cannot find module './432.jpg'" in conditional rendering
I have a conditional rendering for a profile photo, if there's no picture it will render a default picture, if not, it will render a dynamic one, like this:

<v-avatar class="profile" color="grey" size="164" tile>
     <v-img v-if="card.avatar == ''" :src="require('../../../../public/img/profile/stock-1.jpg')"></v-img>
     <v-img v-else :src="require('../../../../public/img/uploads/avatars/'+card.avatar)"></v-img>
</v-avatar>
```

<p><code>card.avatar</code> is <code>432.jpg</code>, however, if I do this</p>

<pre class="lang-html prettyprint-override"><code><v-img v-else :src="require('../../../../public/img/uploads/avatars/432.jpg')"></v-img>

</code>```

It works, so the path is definitely right, however I need this one to be dynamic, why it isn't working this way?

答:
If your images are within the public folder, you don't need to use require since everything in there is bundled automatically.

Try

<v-img v-else :src="`${publicPath}img/uploads/avatars/${cart.avatar}`" />
```

<p>with</p>

<pre class="lang-js prettyprint-override"><code>data: () => ({
  publicPath: process.env.BASE_URL
})
</code>```

See https://cli.vuejs.org/guide/html-and-static-assets.html#the-public-folder

Body:
I have a conditional rendering for a profile photo, if there's no picture it will render a default picture, if not, it will render a dynamic one, like this:

<v-avatar class="profile" color="grey" size="164" tile>
     <v-img v-if="card.avatar == ''" :src="require('../../../../public/img/profile/stock-1.jpg')"></v-img>
     <v-img v-else :src="require('../../../../public/img/uploads/avatars/'+card.avatar)"></v-img>
</v-avatar>

card.avatar is 432.jpg, however, if I do this

<v-img v-else :src="require('../../../../public/img/uploads/avatars/432.jpg')"></v-img>

It works, so the path is definitely right, however I need this one to be dynamic, why it isn't working this way?

Body:
If your images are within the public folder, you don't need to use require since everything in there is bundled automatically.

Try

<v-img v-else :src="`${publicPath}img/uploads/avatars/${cart.avatar}`" />

with

data: () => ({
  publicPath: process.env.BASE_URL
})

See https://cli.vuejs.org/guide/html-and-static-assets.html#the-public-folder


答:
You can also write the path directly if you have imgs on public folder:

<v-avatar class="profile" color="grey" size="164" tile>
     <v-img v-if="card.avatar == ''" :src="'/img/profile/stock-1.jpg'"></v-img>
     <v-img v-else :src="'/img/uploads/avatars/' + card.avatar"></v-img>
</v-avatar>
```

Title: Error in render: "Error: Cannot find module './432.jpg'" in conditional rendering


问:
Mongoose unsettable properties
Is there a way I can include a property in a schema, such as a created timestamp, but forbid users from setting that value in creation (always use the default)? This is specifically for an API where I want to have a created value in the schema but want to always override the request body's value with the current timestamp. Example:

const schema = new mongoose.Schema({
  created: {
    type: Date,
    default: Date.now
  }
});
```

In this schema, how could I make it so that even if a value is passed during initialization, it is overridden with Date.now?

答:
it sounds like you want to use the "createdAt" timestamp, if it's that, you can use the immutable property:</p>

```<code>const Model = mongoose.model('Test', new Schema({
  name: String,
  createdAt: {
    type: Date,
    immutable: true // Make `createdAt` immutable
  }
}, { timestamps: true }));
</code>```

Title: Mongoose unsettable properties

Body:
Is there a way I can include a property in a schema, such as a created timestamp, but forbid users from setting that value in creation (always use the default)? This is specifically for an API where I want to have a created value in the schema but want to always override the request body's value with the current timestamp. Example:

const schema = new mongoose.Schema({
  created: {
    type: Date,
    default: Date.now
  }
});

In this schema, how could I make it so that even if a value is passed during initialization, it is overridden with Date.now?

Body:
it sounds like you want to use the "createdAt" timestamp, if it's that, you can use the immutable property:

const Model = mongoose.model('Test', new Schema({
  name: String,
  createdAt: {
    type: Date,
    immutable: true // Make `createdAt` immutable
  }
}, { timestamps: true }));


问:
socket programming in client
I wrote this program in C++ and on Linux platform.

I wrote a client and server socket program.

In that client program, I wrote socket function and immediately after that I am doing some other actions not at all depending on socket (I wrote 2 for loops for some other logic).

After that I prepared the structures required for the socket and I wrote the connect function...in that I am getting error as unable to connect because connect is returning -1..

But for the same program, if I write that for loop's logic above the socket function and immediately after that structures, and connect function, then it is working fine..

What might be the reason I am not able to get? Please help me in this aspect. Here is my code

here index1 and index 2 are simple integer variables..The configstring is a char array contains 127.0.0.1:7005(address and port number)...address and port are char array variables to store address and port number..

```<code>struct sockaddr_in s1;

for(index1=0;configstring[index1]!=':';index1++)
{
    address[index1] = configstring[index1];
}
address[index1++]='\0';

for(index2=0;configstring[index1]!='\0';index1++,index2++)
{
    port[index2] = configstring[index1];
}
port[index2++]='\0';

int port_num = changeto_int(port);

if((sock_fd = socket(AF_INET,SOCK_STREAM,0)) == -1)
{
    printf("unable to create a socket\n");
    return 0;
}

s1.sin_family=AF_INET;
s1.sin_port=htons(port_num);
s1.sin_addr.s_addr=inet_addr(address);
memset(s1.sin_zero, '\0', sizeof s1.sin_zero);
int errno;

if(connect(sock_fd,(struct sockaddr *)&s1,sizeof(s1)) == -1)
{
    printf("error:unable to connect\n");
    printf("Error in connect(): %s\n", strerror( errno));
    return -1;
}
</code>```

答:
struct sockaddr_in s1;

could you please try memset of s1, at the beginning of your program.
I have experienced some thing similar to this.

OwnerDisplayName: saiprasad reddy

LastEditorDisplayName: Jonathan Leffler

ContentLicense: CC BY-SA 2.5

Title: socket programming in client

Body:
I wrote this program in C++ and on Linux platform.

I wrote a client and server socket program.

In that client program, I wrote socket function and immediately after that I am doing some other actions not at all depending on socket (I wrote 2 for loops for some other logic).

After that I prepared the structures required for the socket and I wrote the connect function...in that I am getting error as unable to connect because connect is returning -1..

But for the same program, if I write that for loop's logic above the socket function and immediately after that structures, and connect function, then it is working fine..

What might be the reason I am not able to get? Please help me in this aspect. Here is my code

here index1 and index 2 are simple integer variables..The configstring is a char array contains 127.0.0.1:7005(address and port number)...address and port are char array variables to store address and port number..

struct sockaddr_in s1;

for(index1=0;configstring[index1]!=':';index1++)
{
    address[index1] = configstring[index1];
}
address[index1++]='\0';

for(index2=0;configstring[index1]!='\0';index1++,index2++)
{
    port[index2] = configstring[index1];
}
port[index2++]='\0';

int port_num = changeto_int(port);

if((sock_fd = socket(AF_INET,SOCK_STREAM,0)) == -1)
{
    printf("unable to create a socket\n");
    return 0;
}

s1.sin_family=AF_INET;
s1.sin_port=htons(port_num);
s1.sin_addr.s_addr=inet_addr(address);
memset(s1.sin_zero, '\0', sizeof s1.sin_zero);
int errno;

if(connect(sock_fd,(struct sockaddr *)&s1,sizeof(s1)) == -1)
{
    printf("error:unable to connect\n");
    printf("Error in connect(): %s\n", strerror( errno));
    return -1;
}

OwnerDisplayName: Vijay


问:
Simple java lib for text templating?
I need to template some email texts. Nothing fancy, just replace something like @name@ with real value. No pictures, no fancy formatting etc.

What java lib could you recommend? The simplier the better.

答: Try Apache Velocity or FreeMarker, they can be helpful, for me I am using FreeMarker </p>

Title: Simple java lib for text templating?


问:
Calculate average gap size in time series by extracting data from imputeTS functions
I need to calculate the average gap size of a univariate time-series data set. imputeTS package generates plots using this data. Is it possible to extract the 'gap size' and the 'number of occurrence' from either statsNA or ggplot_na_gapsize?
Or is there any other way to find the average size of gaps in a time-series data set?
(You could use tsNH4 data set from the imputeTS package)

(This is my first time asking questions here and I'm fairly new to 'r')

答:
At the moment you can get the average gap size only indirectly with some extra work with the CRAN version of imputeTS.

But I made a quick update to the development version on GitHub.
Now you can also get the average gap size with the statsNA function.

Therefore you have to install the new version from GitHub first (since it is not on CRAN yet):

```<code>library("devtools")
install_github("SteffenMoritz/imputeTS")
</code>```

If you do not have "devtools" installed, then also install this library at the very beginning

```<code>install.packages("devtools")
</code>```

Afterwards just use the imputeTS package as usual.

```<code>library("imputeTS")

#Example with the tsNH4 dataset
statsNA(tsNH4)
</code>```

This will now print you the following:

```<code>> statsNA(tsNH4)

[1] "Length of time series:"
[1] 4552
[1] "-------------------------"
[1] "Number of Missing Values:"
[1] 883
[1] "-------------------------"
[1] "Percentage of Missing Values:"
[1] "19.4%"
[1] "-------------------------"
[1] "Number of Gaps:"
[1] 155
[1] "-------------------------"
[1] "Average Gap Size:"
[1] 5.696774
[1] "-------------------------"
[1] "Stats for Bins"
[1] "  Bin 1 (1138 values from 1 to 1138) :      233 NAs (20.5%)"
[1] "  Bin 2 (1138 values from 1139 to 2276) :      433 NAs (38%)"
[1] "  Bin 3 (1138 values from 2277 to 3414) :      135 NAs (11.9%)"
[1] "  Bin 4 (1138 values from 3415 to 4552) :      82 NAs (7.21%)"
[1] "-------------------------"
[1] "Longest NA gap (series of consecutive NAs)"
[1] "157 in a row"
[1] "-------------------------"
[1] "Most frequent gap size (series of consecutive NA series)"
[1] "1 NA in a row (occuring 68 times)"
[1] "-------------------------"
[1] "Gap size accounting for most NAs"
[1] "157 NA in a row (occuring 1 times, making up for overall 157 NAs)"
</code>```

As you can see, 'Number of gaps' and 'Average gap size' is now newly added to the output.

You can also access the output as a variable:

```<code>library("imputeTS")

#To actually get a output object, set print_only to false

out <- statsNA(tsNH4, print_only = F)

# Average gap size
out$average_size_na_gaps

# Number of Gaps
out$number_na_gaps

#Number of NAs
out$number_NAs
</code>```

The updates will also be in the next CRAN update. (thanks for the suggestion)
Just be a little bit careful, since it is a development version - thus not so thoroughly tested as the CRAN version.

Body:
At the moment you can get the average gap size only indirectly with some extra work with the CRAN version of imputeTS.

But I made a quick update to the development version on GitHub.
Now you can also get the average gap size with the statsNA function.

Therefore you have to install the new version from GitHub first (since it is not on CRAN yet):

library("devtools")
install_github("SteffenMoritz/imputeTS")

If you do not have "devtools" installed, then also install this library at the very beginning

install.packages("devtools")

Afterwards just use the imputeTS package as usual.

library("imputeTS")

#Example with the tsNH4 dataset
statsNA(tsNH4)

This will now print you the following:

> statsNA(tsNH4)

[1] "Length of time series:"
[1] 4552
[1] "-------------------------"
[1] "Number of Missing Values:"
[1] 883
[1] "-------------------------"
[1] "Percentage of Missing Values:"
[1] "19.4%"
[1] "-------------------------"
[1] "Number of Gaps:"
[1] 155
[1] "-------------------------"
[1] "Average Gap Size:"
[1] 5.696774
[1] "-------------------------"
[1] "Stats for Bins"
[1] "  Bin 1 (1138 values from 1 to 1138) :      233 NAs (20.5%)"
[1] "  Bin 2 (1138 values from 1139 to 2276) :      433 NAs (38%)"
[1] "  Bin 3 (1138 values from 2277 to 3414) :      135 NAs (11.9%)"
[1] "  Bin 4 (1138 values from 3415 to 4552) :      82 NAs (7.21%)"
[1] "-------------------------"
[1] "Longest NA gap (series of consecutive NAs)"
[1] "157 in a row"
[1] "-------------------------"
[1] "Most frequent gap size (series of consecutive NA series)"
[1] "1 NA in a row (occuring 68 times)"
[1] "-------------------------"
[1] "Gap size accounting for most NAs"
[1] "157 NA in a row (occuring 1 times, making up for overall 157 NAs)"

As you can see, 'Number of gaps' and 'Average gap size' is now newly added to the output.

You can also access the output as a variable:

library("imputeTS")

#To actually get a output object, set print_only to false

out <- statsNA(tsNH4, print_only = F)

# Average gap size
out$average_size_na_gaps

# Number of Gaps
out$number_na_gaps

#Number of NAs
out$number_NAs

The updates will also be in the next CRAN update. (thanks for the suggestion)
Just be a little bit careful, since it is a development version - thus not so thoroughly tested as the CRAN version.


问:
Catalyst app: How do I enable com.apple.developer.default-data-protection entitlement?
I am attempting to distribute a Catalyst app for beta testing. Since there's no Test Flight for Mac, my intent is to distribute a signed archive in order to minimize the amount warnings my users receive about running the app. I did the following:

Archived for MyMac,

Selected the archive from the "macOS Apps" list in the organizer,

Clicked "Distribute App,"

Chose "Developer ID."

Selected "Upload"

Selected "Automatically manage signing"

I expected it to be submitted for notarization, but instead received an error:

Provisioning profiled failed qualification. Profile doesn't include
  the com.apple.developer.default-data-protection entitlement.

I subsequently checked the Mac OS Provisioning profile via developer.apple.com. I have a profile that's labeled "XC OSX:" (assuming that means Xcode auto-generated) with a type field of "Developer ID Application." Sure enough, although it shows iCloud, in app purchases, etc., in the "Enabled Capabilities" section it does not have Data Protection.

But, in Xcode, when I select the target and go to "Signing and Capabilities," Data Protection is already listed. When I click the information "i" button next to the MacOS provision profile, it says com.apple.developer.default-data-protection is enabled. (it actually shows that for both the IOS and the MacOS provisioning profile).

Next, I looked at the Bundle Identifier on developer.apple.com and see Data Protection listed under capabilities:

I tried removing and re-adding Data Protection in Xcode, but the error still occurs.

I tried manually creating a Developer ID profile on developer.apple.com, but the resulting profile still lacks Data Protection.

I tried removing and re-adding Data Protection under the identifier on developer.apple.com. This successfully invalidated the existing profiles (both Xcode's and the one I created). When I again attempted signing, a new profile was created but it still lacks Data Protection and the error still occurs.

What am I missing here? What else do I have to do to enable Data Protection in the provisioning profile?

答:
Burned a support ticket and found the answer. I read the message as:

You failed. You don't have Data Protection (but you need it)

But per Apple, it actually means:

You failed. You want Data Protection (because you turned it on) but
  don't have it (because it's not supported in this config).

So, the solution for "Data protection is missing" was... turn Data Protection off.


问:
Retrieving NotesDocumentCollection during QueryPaste
Is this possible in Notes? I am currently using version 11.
I have a form with an embedded view in it. This view has code in the QueryPaste function.
For example it has the code:

```<code>Sub Querypaste(Source As Notesuiview, Continue As Variant)
    Dim ndcRegel As NotesDocumentCollection
    Dim docRegel As NotesDocument

    Set ndcRegel = source.Documents
    Msgbox "1"
    Msgbox source.Documents.Count
    etc...
</code>```

When copy and pasting a document in the embedded view, it triggers Msgbox 1 first and then for the count I get the result 0. While there are documents in the embedded view.

When I am copy pasting in the view itself then it correctly works and does find a ndc collection..

Why is this so? And can this be fixed? Because I want to block my users to copy paste documents in an embedded view.

答:
Documents copied in the Notes client are placed in a local database with the file name "~clipbrd.ncf".

I can't remember where I found this information, but it was somewhere on the internet.

In a view's QueryPaste event, you can get that database, and its AllDocuments property contains the documents to be pasted.

I've only used this with Notes 8.5.x and 9.0.x clients, and for views which are not embedded, so make sure to test before relying on it.

Example code:

```<code>Sub Querypaste(Source As Notesuiview, Continue As Variant)
    Dim clipDb As New NotesDatabase("","~clipbrd.ncf")
    Dim dc As NotesDocumentCollection

    Set dc=clipDb.AllDocuments
    ' dc now contains copied documents.
End Sub
</code>```

Body:
Is this possible in Notes? I am currently using version 11.
I have a form with an embedded view in it. This view has code in the QueryPaste function.
For example it has the code:

Sub Querypaste(Source As Notesuiview, Continue As Variant)
    Dim ndcRegel As NotesDocumentCollection
    Dim docRegel As NotesDocument

    Set ndcRegel = source.Documents
    Msgbox "1"
    Msgbox source.Documents.Count
    etc...

When copy and pasting a document in the embedded view, it triggers Msgbox 1 first and then for the count I get the result 0. While there are documents in the embedded view.

When I am copy pasting in the view itself then it correctly works and does find a ndc collection..

Why is this so? And can this be fixed? Because I want to block my users to copy paste documents in an embedded view.

Body:
Documents copied in the Notes client are placed in a local database with the file name "~clipbrd.ncf".

I can't remember where I found this information, but it was somewhere on the internet.

In a view's QueryPaste event, you can get that database, and its AllDocuments property contains the documents to be pasted.

I've only used this with Notes 8.5.x and 9.0.x clients, and for views which are not embedded, so make sure to test before relying on it.

Example code:

Sub Querypaste(Source As Notesuiview, Continue As Variant)
    Dim clipDb As New NotesDatabase("","~clipbrd.ncf")
    Dim dc As NotesDocumentCollection

    Set dc=clipDb.AllDocuments
    ' dc now contains copied documents.
End Sub


问:
How to fix Unexpected token error, expected “}”
I keep on getting an error saying unexpected token but have no idea where that unexpected token is at? Please help

Code is below

```<code>import React from 'react';
import react, { Component } from 'react'
import { Plateform, StyleSheet, View,Text } from 'react-native';

function Header() {
  return (
    <div>
    <this.View style={style}/>
    <Text style={[styles.setFontSize.setColorRed]}>Welcome to the dealership!</Text>
      <header className="header">
        <div className="col1">
        </div>
        <div className="col2">
        <div className="menu">
        <h3>About</h3>
        <h3>Cars</h3>
        <h3>Contact</h3>
        <h3>Search</h3>
        <header/>
        <View/>
      </div>
      </div>

**Here is where the error seems to be happing**

  );
}
export default Header;

App = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  setFontSize: {
    fontSize: 20,
    fontWeight : 'bold'
  },
  setColorRed : {
    color: '#f44336'
  }
});
</code>```

Error is below as well

Line 37:12:  Parsing error: Unexpected token, expected "}"

35 |    36 | App = StyleSheet.create({

37 |   container: {
         |            ^   38 |     flex: 1,   39 |     justifyContent: 'center',   40 |     alignItems: 'center'

答:
You've incorrectly closed Header, i.e.  versus , and you dropped two closing div tags outside the header instead of in it, and the first div is missing its closing tag. I assume you don't want your view in the header, so I left it below it.

This is where using proper indentations and any decent IDE would help catch/identify these for you.

```<code>function Header() {
  return (
    <div>
      <this.View style={style}/>
      <Text style={[styles.setFontSize.setColorRed]}>Welcome to the dealership!</Text>
      <header className="header">
        <div className="col1"></div>
        <div className="col2">
          <div className="menu">
            <h3>About</h3>
            <h3>Cars</h3>
            <h3>Contact</h3>
            <h3>Search</h3>
          </div>
        </div>
      </header>
      <View/>
    </div>
  );
}
</code>```

Body:
I keep on getting an error saying unexpected token but have no idea where that unexpected token is at? Please help

Code is below

import React from 'react';
import react, { Component } from 'react'
import { Plateform, StyleSheet, View,Text } from 'react-native';

function Header() {
  return (

    <this.View style={style}/>
    <Text style={[styles.setFontSize.setColorRed]}>Welcome to the dealership!</Text>

About

Cars

Contact

Search

        <View/>

**Here is where the error seems to be happing**

  );
}
export default Header;

App = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  setFontSize: {
    fontSize: 20,
    fontWeight : 'bold'
  },
  setColorRed : {
    color: '#f44336'
  }
});

Error is below as well

Line 37:12:  Parsing error: Unexpected token, expected "}"

35 |    36 | App = StyleSheet.create({

37 |   container: {
         |            ^   38 |     flex: 1,   39 |     justifyContent: 'center',   40 |     alignItems: 'center'

Body:
You've incorrectly closed Header, i.e. <Header/> versus </Header>, and you dropped two closing div tags outside the header instead of in it, and the first div is missing its closing tag. I assume you don't want your view in the header, so I left it below it.

This is where using proper indentations and any decent IDE would help catch/identify these for you.

function Header() {
  return (
    <div>
      <this.View style={style}/>
      <Text style={[styles.setFontSize.setColorRed]}>Welcome to the dealership!</Text>
      <header className="header">
        <div className="col1"></div>
        <div className="col2">
          <div className="menu">
            <h3>About</h3>
            <h3>Cars</h3>
            <h3>Contact</h3>
            <h3>Search</h3>
          </div>
        </div>
      </header>
      <View/>
    </div>
  );
}