问:
Python slicing list of tuples and converting values to integers - Confusion regarding why it's possible with numpy arrays but not list of tuples
I am trying to slice the first and last values from a list of list then convert these values to integers. I found a solution but I am confused why this solution works and am wondering if there is a simpler way as it seems rather inelegant.

The two ways I found to slice a single value from a list of a list are either to use list comprehension and then slice or convert to a numpy array then slice in two dimensions. Both of these take two steps.

Question 1: is there a single step solution to slice a single value out of a list of a list?

Question 2: Why is a mixed list (some values being numbers and some letters) not made up of integers and strings vs all tuples? Do numpy arrays or another approach allow mixed lists? Sorry if I am not using the correct terminology...

List of a list slicing - list comprehension method

```<code>#Say I have a list of a list with mixed numbers and letters.

>>>a=[('1', 'T', ''), ('2', 'R', 'S'), ('3', 'E', 'S'), ('4', 'T', 'S')]
#list comprehension slice 1D
>>>b=[list[0:1] for list in a]
>>> print(b):
[('1',), ('2',), ('3',), ('4',)]

>>> start=(b[0:1])
>>> print(start):
[('1',)]
>>> end=b[len(b)-1:len(b)]
>>> print(end)
[('4',)]
</code>```

List of a list slicing - numpy array method
    #Say I have a list of a list with mixed numbers and letters.

```<code>>>>a=[('1', 'T', ''), ('2', 'R', 'S'), ('3', 'E', 'S'), ('4', 'T', 'S')]
>>> b_array=numpy.array(a)
>>> print(b_array)
array([['1', 'T', ''],
       ['2', 'R', 'S'],
       ['3', 'E', 'S'],
       ['4', 'T', 'S']], dtype='<U1')

>>>start_array = b_array[0:1,0:1]
>>>print(start_array)
array([['1']], dtype='<U1')

>>>end_array = b_array[len(b_array)-1:len(b_array),0:1]
>>>print(end_array)
array([['4']], dtype='<U1')
</code>```

Both approaches work but what confuses me is they behave differently if I call int() on them
List comprehension
If I either use list comprehension to try to turn all of b into integers

```<code>>>>b_int= [int(i) for i in b]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'
</code>```

or turn start or end into integers

```<code>>>>start=int(b[0:1])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
</code>```

I get thrown similar errors. But the second says it is a list even though it's a single value in a 1x1 list.

Alternatively if I do the same for start_array it's fine

```<code>>>>start_array=int(b_array[0:1,0:1])
>>>print(start_array)
1
</code>```

So in summary, I figured out a working solution but it feels clunky and I don't understand why this works in numpy arrays but not list of lists.

Question 3: Why can I convert values in numpy arrays into integers not list of lists?

Question 4: Is there a cleaner or easier way to do this in python?

Thanks

edit: So my misunderstanding was that I thought I was dealing with a list of lists. I was not, instead I was working with a list of tuples. I changed the title but not the body. My second problem was I was slice indexing and not scalar indexing. This resulted in not removing my elements from the list. For solutions I could either:

```<code>#List comprehension to reduce dimensionality
a=[('1', 'T', ''), ('2', 'R', 'S'), ('3', 'E', 'S'), ('4', 'T','S')]
b=[x[0] for x in a]
start=int(b[0])
end=int(b[-1])

#Directly index with a scalar
start=int(b[0][0])
end=int(b[-1][0])
</code>```

I will directly index with a scalar as it's simpler. Though if I wanted to index several numbers list comprehension would be more useful.

答:
You are indexing with slices, which returns a list (or tuple).  Indexing with a number (scalar) takes an element out of the list (or tuple):

```<code>In [8]: a=[('1', 'T', ''), ('2', 'R', 'S'), ('3', 'E', 'S'), ('4', 'T', 'S')]
In [9]: b=[x[0] for x in a]
In [10]: b
Out[10]: ['1', '2', '3', '4']
In [11]: b[0]
Out[11]: '1'
In [12]: int(b[0])
Out[12]: 1
In [13]: b[-1]
Out[13]: '4'    # int(b[-1]) works
</code>```

Similarly with an array.  Slice index retains the dimension, scalar index reduces the dimension(s):

```<code>In [14]: arr = np.array(a)
In [15]: arr
Out[15]:
array([['1', 'T', ''],
       ['2', 'R', 'S'],
       ['3', 'E', 'S'],
       ['4', 'T', 'S']], dtype='<U1')
In [16]: arr[0,:]
Out[16]: array(['1', 'T', ''], dtype='<U1')
In [17]: arr[:,0]
Out[17]: array(['1', '2', '3', '4'], dtype='<U1')
</code>```

Note the arr dtype; we can change that to int:

```<code>In [18]: arr[:,0].astype(int)
Out[18]: array([1, 2, 3, 4])
</code>```

In general you don't want to use int(b_array[0:1,0:1]).  It works for one number, but not several:

```<code>In [19]: int(arr[:,0])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-19-9c2041fff718> in <module>
----> 1 int(arr[:,0])

TypeError: only size-1 arrays can be converted to Python scalars
</code>```

The list indexing is the Python original.  numpy has extended this indexing.  numpy extensions have not been back-ported to list.

Something you may have missed is that iterating on a list takes items out of the list.

```<code>In [26]: [x for x in a[:2]]
Out[26]: [('1', 'T', ''), ('2', 'R', 'S')]
</code>```

is equivalent to indexing with a scalar:

```<code>In [27]: [a[i] for i in range(2)]
Out[27]: [('1', 'T', ''), ('2', 'R', 'S')]
</code>```

Indexing with slice 'wraps' each x in a list:

```<code>In [28]: [a[i:i+1] for i in range(2)]
Out[28]: [[('1', 'T', '')], [('2', 'R', 'S')]]
</code>```

In b=[list[0:1] for list in a], list is one of the tuples in a.  It is not a slice of a.

```<code>In [29]: a[0][0:1]         # slice of a tuple from a list
Out[29]: ('1',)
In [30]: a[0:1][0:1]       # slice of a slice
Out[30]: [('1', 'T', '')]
In [31]: a[0][0]           # element of a tuple from the list
Out[31]: '1'
</code>```

Body:
I am trying to slice the first and last values from a list of list then convert these values to integers. I found a solution but I am confused why this solution works and am wondering if there is a simpler way as it seems rather inelegant.

The two ways I found to slice a single value from a list of a list are either to use list comprehension and then slice or convert to a numpy array then slice in two dimensions. Both of these take two steps.

Question 1: is there a single step solution to slice a single value out of a list of a list?

Question 2: Why is a mixed list (some values being numbers and some letters) not made up of integers and strings vs all tuples? Do numpy arrays or another approach allow mixed lists? Sorry if I am not using the correct terminology...

List of a list slicing - list comprehension method

#Say I have a list of a list with mixed numbers and letters.

>>>a=[('1', 'T', ''), ('2', 'R', 'S'), ('3', 'E', 'S'), ('4', 'T', 'S')]
#list comprehension slice 1D
>>>b=[list[0:1] for list in a]
>>> print(b):
[('1',), ('2',), ('3',), ('4',)]

>>> start=(b[0:1])
>>> print(start):
[('1',)]
>>> end=b[len(b)-1:len(b)]
>>> print(end)
[('4',)]

List of a list slicing - numpy array method
    #Say I have a list of a list with mixed numbers and letters.

>>>a=[('1', 'T', ''), ('2', 'R', 'S'), ('3', 'E', 'S'), ('4', 'T', 'S')]
>>> b_array=numpy.array(a)
>>> print(b_array)
array([['1', 'T', ''],
       ['2', 'R', 'S'],
       ['3', 'E', 'S'],
       ['4', 'T', 'S']], dtype='<U1')

>>>start_array = b_array[0:1,0:1]
>>>print(start_array)
array([['1']], dtype='<U1')

>>>end_array = b_array[len(b_array)-1:len(b_array),0:1]
>>>print(end_array)
array([['4']], dtype='<U1')

Both approaches work but what confuses me is they behave differently if I call int() on them
List comprehension
If I either use list comprehension to try to turn all of b into integers

>>>b_int= [int(i) for i in b]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'

or turn start or end into integers

>>>start=int(b[0:1])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

I get thrown similar errors. But the second says it is a list even though it's a single value in a 1x1 list.

Alternatively if I do the same for start_array it's fine

>>>start_array=int(b_array[0:1,0:1])
>>>print(start_array)
1

So in summary, I figured out a working solution but it feels clunky and I don't understand why this works in numpy arrays but not list of lists.

Question 3: Why can I convert values in numpy arrays into integers not list of lists?

Question 4: Is there a cleaner or easier way to do this in python?

Thanks

edit: So my misunderstanding was that I thought I was dealing with a list of lists. I was not, instead I was working with a list of tuples. I changed the title but not the body. My second problem was I was slice indexing and not scalar indexing. This resulted in not removing my elements from the list. For solutions I could either:

#List comprehension to reduce dimensionality
a=[('1', 'T', ''), ('2', 'R', 'S'), ('3', 'E', 'S'), ('4', 'T','S')]
b=[x[0] for x in a]
start=int(b[0])
end=int(b[-1])

#Directly index with a scalar
start=int(b[0][0])
end=int(b[-1][0])

I will directly index with a scalar as it's simpler. Though if I wanted to index several numbers list comprehension would be more useful.

Body:
You are indexing with slices, which returns a list (or tuple).  Indexing with a number (scalar) takes an element out of the list (or tuple):

In [8]: a=[('1', 'T', ''), ('2', 'R', 'S'), ('3', 'E', 'S'), ('4', 'T', 'S')]
In [9]: b=[x[0] for x in a]
In [10]: b
Out[10]: ['1', '2', '3', '4']
In [11]: b[0]
Out[11]: '1'
In [12]: int(b[0])
Out[12]: 1
In [13]: b[-1]
Out[13]: '4'    # int(b[-1]) works

Similarly with an array.  Slice index retains the dimension, scalar index reduces the dimension(s):

In [14]: arr = np.array(a)
In [15]: arr
Out[15]:
array([['1', 'T', ''],
       ['2', 'R', 'S'],
       ['3', 'E', 'S'],
       ['4', 'T', 'S']], dtype='<U1')
In [16]: arr[0,:]
Out[16]: array(['1', 'T', ''], dtype='<U1')
In [17]: arr[:,0]
Out[17]: array(['1', '2', '3', '4'], dtype='<U1')

Note the arr dtype; we can change that to int:

In [18]: arr[:,0].astype(int)
Out[18]: array([1, 2, 3, 4])

In general you don't want to use int(b_array[0:1,0:1]).  It works for one number, but not several:

In [19]: int(arr[:,0])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-19-9c2041fff718> in <module>
----> 1 int(arr[:,0])

TypeError: only size-1 arrays can be converted to Python scalars

The list indexing is the Python original.  numpy has extended this indexing.  numpy extensions have not been back-ported to list.

Something you may have missed is that iterating on a list takes items out of the list.

In [26]: [x for x in a[:2]]
Out[26]: [('1', 'T', ''), ('2', 'R', 'S')]

is equivalent to indexing with a scalar:

In [27]: [a[i] for i in range(2)]
Out[27]: [('1', 'T', ''), ('2', 'R', 'S')]

Indexing with slice 'wraps' each x in a list:

In [28]: [a[i:i+1] for i in range(2)]
Out[28]: [[('1', 'T', '')], [('2', 'R', 'S')]]

In b=[list[0:1] for list in a], list is one of the tuples in a.  It is not a slice of a.

In [29]: a[0][0:1]         # slice of a tuple from a list
Out[29]: ('1',)
In [30]: a[0:1][0:1]       # slice of a slice
Out[30]: [('1', 'T', '')]
In [31]: a[0][0]           # element of a tuple from the list
Out[31]: '1'


来源: stackexchange

问:
Remove specific array from multiple array set using jquery
I have two checkboxes. When I check one, the code will get status and id of that checkbox and push into array, if that value is not present already

The array set become like this

```<code>  [8,0] [10,0]
</code>```

Requirements:

It is inserting [8,0] [8,0] twice if I check and then uncheck and again check it so this should not insert multiple times same values

Remove specific array from set of array so if I uncheck chkecbox then remove only [8,0] but keep  [10,0]

var positions = [];

$("body").on('click', '.check_box', function() {
  var id = $(this).attr('data-id');
  var status = $(this).attr('data-status');
  if ($(this).prop("checked") == true) { // if click on check
    if (!$.inArray(id, positions)) positions.push(id); // if id and status not in array then only push
    positions.push([id, status]); //  it will  insert  like [8,10] but geting duplicate  [8,10] [8,10]
    console.log(positions);
  } else {
    // if uncheck checkbox

    //  remove specific  value like  [8,0] or if value present [10,0] then remove this
    console.log(positions);
  }

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="check_box" data-id="8" data-status="0">

<input type="checkbox" class="check_box" data-id="10" data-status="0"></code>```

答:
I will use findIndex and splice to handle it, hope this can help you :)

$(function() {
    let positions = [];
    $("body").on('click', 'input:checkbox', function() {
        let id = $(this).attr('data-id');
        let status = $(this).attr('data-status');
        let data = [id, status];
        if ($(this).is(':checked')) {
            positions.push(data);
        } else {
            let index = positions.findIndex(c => c[0] === id);
            if (index != -1)
                positions.splice(index, 1);
        }
        $('#result').html(positions.toString());
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#result{
  width: 20rem;
  height: 1rem;
  margin-top: 2rem;
  border-width:3px;
  border-style:dashed;
  border-color:#FFAC55;
  padding: 15px 20px;
}</code>```

<!DOCTYPE html>

    <input type="checkbox" data-id="A" data-status="0">A</button>
    <input type="checkbox" data-id="B" data-status="0">B</button>

```

ContentLicense: CC BY-SA 4.0

Body:
I have two checkboxes. When I check one, the code will get status and id of that checkbox and push into array, if that value is not present already

The array set become like this

  [8,0] [10,0]

Requirements:

It is inserting [8,0] [8,0] twice if I check and then uncheck and again check it so this should not insert multiple times same values

Remove specific array from set of array so if I uncheck chkecbox then remove only [8,0] but keep  [10,0]

var positions = [];

$("body").on('click', '.check_box', function() {
  var id = $(this).attr('data-id');
  var status = $(this).attr('data-status');
  if ($(this).prop("checked") == true) { // if click on check
    if (!$.inArray(id, positions)) positions.push(id); // if id and status not in array then only push
    positions.push([id, status]); //  it will  insert  like [8,10] but geting duplicate  [8,10] [8,10]
    console.log(positions);
  } else {
    // if uncheck checkbox

    //  remove specific  value like  [8,0] or if value present [10,0] then remove this
    console.log(positions);
  }

});

<input type="checkbox" class="check_box" data-id="8" data-status="0">

<input type="checkbox" class="check_box" data-id="10" data-status="0">

Body:
I will use findIndex and splice to handle it, hope this can help you :)

$(function() {
    let positions = [];
    $("body").on('click', 'input:checkbox', function() {
        let id = $(this).attr('data-id');
        let status = $(this).attr('data-status');
        let data = [id, status];
        if ($(this).is(':checked')) {
            positions.push(data);
        } else {
            let index = positions.findIndex(c => c[0] === id);
            if (index != -1)
                positions.splice(index, 1);
        }
        $('#result').html(positions.toString());
    });
});

#result{
  width: 20rem;
  height: 1rem;
  margin-top: 2rem;
  border-width:3px;
  border-style:dashed;
  border-color:#FFAC55;
  padding: 15px 20px;
}

<!DOCTYPE html>
<html>

<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>
    <input type="checkbox" data-id="A" data-status="0">A</button>
    <input type="checkbox" data-id="B" data-status="0">B</button>
    <div id="result"></div>
</body>

</html>


问:
Check if string contains a value in array
I am trying to detect whether a string contains at least one URL that is stored in an array.

Here is my array:

```<code>$owned_urls = array('website1.com', 'website2.com', 'website3.com');
</code>```

The string is entered by the user and submitted via PHP. On the confirmation page I would like to check if the URL entered is in the array.

I have tried the following:

```<code>$string = 'my domain name is website3.com';
if (in_array($string, $owned_urls))
{
    echo "Match found";
    return true;
}
else
{
    echo "Match not found";
    return false;
}
</code>```

No matter what is inputted the return is always "Match not found".

Is this the correct way of doing things?

答:
You can concatenate the array values with implode and a separator of |
and then use preg_match to search for the value.

Here is the solution I came up with ...

```<code>$emails = array('@gmail', '@hotmail', '@outlook', '@live', '@msn', '@yahoo', '@ymail', '@aol');
$emails = implode('|', $emails);

if(!preg_match("/$emails/i", $email)){
 // do something
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to detect whether a string contains at least one URL that is stored in an array.

Here is my array:

$owned_urls = array('website1.com', 'website2.com', 'website3.com');

The string is entered by the user and submitted via PHP. On the confirmation page I would like to check if the URL entered is in the array.

I have tried the following:

$string = 'my domain name is website3.com';
if (in_array($string, $owned_urls))
{
    echo "Match found";
    return true;
}
else
{
    echo "Match not found";
    return false;
}

No matter what is inputted the return is always "Match not found".

Is this the correct way of doing things?

Body:
You can concatenate the array values with implode and a separator of |
and then use preg_match to search for the value.

Here is the solution I came up with ...

$emails = array('@gmail', '@hotmail', '@outlook', '@live', '@msn', '@yahoo', '@ymail', '@aol');
$emails = implode('|', $emails);

if(!preg_match("/$emails/i", $email)){
 // do something
}


问:
How does one add a collaborator in GitLab using the command line?
I am trying to achieve a task of creating multiple repositories(around 300-400) and each repositories is assigned to only 1 user/collaborator. Can this be automated via command line instructions or GitLab APIs.</p>

答:
Yes you could automate this using Gitlabs API.

Assuming you know the members ids beforehand: You can use the Group and project members API or directly create a project for a specific user. You need to be the admin of the group above or global admin to call these.


问:
Vaadin - GWT dependency always needed?
Is the GWT mandatory in a deployment with Vaadin framework.

I mean is the Vaadin framework builded over the GWT and then not using GWT is not possible.
I ask because some manager asked me but I was not able to answer if it can be used separately or not.

I know the GWT does not need Vaadin but what about the inverse?

答: I would refer the stackoverflow tag definition of vaadin at a first touch. Wikipedia tells the same: Vaadin is built on GWT - meaning it is on the top of GWT, GWT is not on the top of Vaadin. The top can be always removed but the underlying basis not.</p>

Title: Vaadin - GWT dependency always needed?


问:
ConnectivityManager.CONNECTIVITY_ACTION deprecated
In Android N, it is mentioned on the official website that "Apps targeting Android N do not receive CONNECTIVITY_ACTION broadcasts". And it is also mentioned that JobScheduler can be used as an alternative. But the JobScheduler doesn't provide exactly the same behavior as CONNECTIVITY_ACTION broadcast.

In my Android application, I was using this broadcast to know the network state of the device. I wanted to know if this state was CONNECTING or CONNECTED with the help of CONNECTIVITY_ACTION broadcast and it was best suited for my requirement.

Now that it is deprecated, can any one suggest me the alternative approach to get current network state?

答:
When we register a network callback using the registerNetworkCallback method sometimes it does not trigger and sometimes it does trigger false-positive:

If we start an app with internet connection the onAvailable method triggers.

But if there is no internet connection on device when we start an app nothing of the NetworkCallback is called (it's very strange because of p. 1)

If we have wifi connection but without internet connection onAvailable method triggers. And I think it's false-positive behavior because we expect internet connection observing.

As you see in below code by default internet connection is available and it triggers only if it changes. No false-positive triggers.

Just summarize this and this answers (but only for API >= 21):

```<code>class ConnectionManager @Inject constructor(
    private val connectivityManager: ConnectivityManager,
    private val disposable: CompositeDisposable,
    private val singleTransformer: SingleTransformer<*, *>
) : LiveData<Boolean>() {

    private var isNetworkAvailable = true

    private val builder = NetworkRequest.Builder()
        .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
        .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
        .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)

    private val callback = object : ConnectivityManager.NetworkCallback() {

        override fun onAvailable(network: Network) {
            ping()
        }

        override fun onLost(network: Network) {
            ping()
        }
    }

    private fun ping() {
        disposable.add(
            Single.fromCallable {
                try {
                    val timeoutMs = 1500
                    val socket = Socket()
                    val socketAddress = InetSocketAddress("8.8.8.8", 53)

                    socket.connect(socketAddress, timeoutMs)
                    socket.close()
                    true
                } catch (e: IOException) {
                    false
                }
            }
                .compose(singleTransformer as SingleTransformer<Boolean, Boolean>)
                .subscribeBy {
                    if (isNetworkAvailable != it){
                        value = it
                        isNetworkAvailable = it
                    }
                }
        )
    }

    override fun onActive() {
        ping()
        connectivityManager.registerNetworkCallback(builder.build(), callback)
    }

    override fun onInactive() {
        disposable.clear()
        connectivityManager.unregisterNetworkCallback(callback)
    }
}
</code>```

How to provide the dependencies

```<code>@Provides
fun provideTransformer(): SingleTransformer<Boolean, Boolean> {
    return SingleTransformer<Boolean, Boolean> { upstream: Single<Boolean> ->
        upstream.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
    }
}

@Singleton
@Provides
fun provideConnectivityManager(context: Context): ConnectivityManager =
        context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

@Singleton
@Provides
fun provideConnectionManager(connectivityManager: ConnectivityManager, singleTransformer: SingleTransformer<Boolean, Boolean>): ConnectionManager =
        ConnectionManager(connectivityManager, singleTransformer)
</code>```

And how to use:

```<code>@Inject
lateinit var connectionManager: ConnectionManager

//....

viewLifecycleOwner.observe(connectionManager) { isInternetAvailable ->
    // TODO
}
</code>```

Body:
When we register a network callback using the registerNetworkCallback method sometimes it does not trigger and sometimes it does trigger false-positive:

If we start an app with internet connection the onAvailable method triggers.

But if there is no internet connection on device when we start an app nothing of the NetworkCallback is called (it's very strange because of p. 1)

If we have wifi connection but without internet connection onAvailable method triggers. And I think it's false-positive behavior because we expect internet connection observing.

As you see in below code by default internet connection is available and it triggers only if it changes. No false-positive triggers.

Just summarize this and this answers (but only for API >= 21):

class ConnectionManager @Inject constructor(
    private val connectivityManager: ConnectivityManager,
    private val disposable: CompositeDisposable,
    private val singleTransformer: SingleTransformer<*, *>
) : LiveData<Boolean>() {

    private var isNetworkAvailable = true

    private val builder = NetworkRequest.Builder()
        .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
        .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
        .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)

    private val callback = object : ConnectivityManager.NetworkCallback() {

        override fun onAvailable(network: Network) {
            ping()
        }

        override fun onLost(network: Network) {
            ping()
        }
    }

    private fun ping() {
        disposable.add(
            Single.fromCallable {
                try {
                    val timeoutMs = 1500
                    val socket = Socket()
                    val socketAddress = InetSocketAddress("8.8.8.8", 53)

                    socket.connect(socketAddress, timeoutMs)
                    socket.close()
                    true
                } catch (e: IOException) {
                    false
                }
            }
                .compose(singleTransformer as SingleTransformer<Boolean, Boolean>)
                .subscribeBy {
                    if (isNetworkAvailable != it){
                        value = it
                        isNetworkAvailable = it
                    }
                }
        )
    }

    override fun onActive() {
        ping()
        connectivityManager.registerNetworkCallback(builder.build(), callback)
    }

    override fun onInactive() {
        disposable.clear()
        connectivityManager.unregisterNetworkCallback(callback)
    }
}

How to provide the dependencies

@Provides
fun provideTransformer(): SingleTransformer<Boolean, Boolean> {
    return SingleTransformer<Boolean, Boolean> { upstream: Single<Boolean> ->
        upstream.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
    }
}

@Singleton
@Provides
fun provideConnectivityManager(context: Context): ConnectivityManager =
        context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

@Singleton
@Provides
fun provideConnectionManager(connectivityManager: ConnectivityManager, singleTransformer: SingleTransformer<Boolean, Boolean>): ConnectionManager =
        ConnectionManager(connectivityManager, singleTransformer)

And how to use:

@Inject
lateinit var connectionManager: ConnectionManager

//....

viewLifecycleOwner.observe(connectionManager) { isInternetAvailable ->
    // TODO
}


问:
return count from a SwiftUI CoreData View
I have a SwiftUI view that displays the result of a CoreData query.

In it's parent view I want to display the count of the query (without querying one more time).

I tried to pass the count to the parent in a Binding, but I get the warning "Modifying state during view update, this will cause undefined behavior." an it does not work.

```<code>import SwiftUI

struct CD_Main: View {
  @State var count = 0

    var body: some View {
      VStack {
        Text("count in main: \(count)")
        CD_Query(c: $count)
      }
    }
}

struct CD_Query: View {
  @Binding var c : Int

  @Environment(\.managedObjectContext) var moc
  @FetchRequest(entity: Item.entity(), sortDescriptors: [], predicate: nil) var items: FetchedResults<Item>

  var body: some View {
  c = items.count // Produces: Modifying state during view update, this will cause undefined behavior.
    return VStack {
      Text("Count Innen: \(items.count) ")
      List(items, id: \.self) {
        item in
        Text(item.title)
      }
    }
  }
}
</code>```

Any ideas how to set the Binding correctly or how else to pass the count to the parent?

答:
Try instead the following</p>

```<code>  var body: some View {
    VStack {
      Text("Count Innen: \(items.count) ")
      .onAppear { // actually it does not matter to which view this attached
         DispatchQueue.main.async {
            self.c = items.count // update asynchronously
         }
      }
      List(items, id: \.self) {
        item in
        Text(item.title)
      }
    }
  }
</code>```

Body:
I have a SwiftUI view that displays the result of a CoreData query.

In it's parent view I want to display the count of the query (without querying one more time).

I tried to pass the count to the parent in a Binding, but I get the warning "Modifying state during view update, this will cause undefined behavior." an it does not work.

import SwiftUI

struct CD_Main: View {
  @State var count = 0

    var body: some View {
      VStack {
        Text("count in main: \(count)")
        CD_Query(c: $count)
      }
    }
}

struct CD_Query: View {
  @Binding var c : Int

  @Environment(\.managedObjectContext) var moc
  @FetchRequest(entity: Item.entity(), sortDescriptors: [], predicate: nil) var items: FetchedResults<Item>

  var body: some View {
  c = items.count // Produces: Modifying state during view update, this will cause undefined behavior.
    return VStack {
      Text("Count Innen: \(items.count) ")
      List(items, id: \.self) {
        item in
        Text(item.title)
      }
    }
  }
}

Any ideas how to set the Binding correctly or how else to pass the count to the parent?

Body:
Try instead the following

  var body: some View {
    VStack {
      Text("Count Innen: \(items.count) ")
      .onAppear { // actually it does not matter to which view this attached
         DispatchQueue.main.async {
            self.c = items.count // update asynchronously
         }
      }
      List(items, id: \.self) {
        item in
        Text(item.title)
      }
    }
  }


问:
C# JSON URL get data
Im new to System.Net with C#
I want a way to get info from this website api: https://fn-api.glitch.me/api/aes
from its json to a C# string

I have this so far

I don't know how to get each item and where to put the url (im really new to this).

I want the url in a string:

```<code>public class Data
{
    public string build { get; set; }
    public string netCL { get; set; }
    public string manifestID { get; set; }
    public string aes { get; set; }
}

public class RootObject
{
    public Data data { get; set; }
}
</code>```

答:
I'd recommend using a 3rd party library like RestSharp. It'll give you a client that's easy to work with and does the converting into objects automatically.

Alternatively you could use the WebClient and download the JSON. Using something like Json.NET allows you to deserialize the JSON into an object.

Title: C# JSON URL get data

Body:
Im new to System.Net with C#
I want a way to get info from this website api: https://fn-api.glitch.me/api/aes
from its json to a C# string

I have this so far

I don't know how to get each item and where to put the url (im really new to this).

I want the url in a string:

public class Data
{
    public string build { get; set; }
    public string netCL { get; set; }
    public string manifestID { get; set; }
    public string aes { get; set; }
}

public class RootObject
{
    public Data data { get; set; }
}


问:
Hosting a Flask-Angular app for multiple users
I have an Angular app that runs on a Python-Flask server on port 5000. Right now the app works well on local host. But now I want the app to be accessible to multiple users. Seems like I will have to create sessions (as each user will generate some temp data and I'd like this data to be stored in a directory where directory name is session id). How do I proceed with this? Also how can I test this multi user functionality on my local machine since flask only listens to one port.</p>

答:
Use gunicorn(Gunicorn.org) to run your app, it will automatically create multiple threads to handle requests from multiple users.
You can store the temp data on client side in local or session storage and send the required data with each request(**Do not store sensitive data on client side like password)</p>


答:
Easiest way to read from a URL into a string in .NET

I use JSON.Net.

Title: C# JSON URL get data


问:
I am missing elevation on the generated sidenav from angular material. Is there any to add it?
I generated a sidenav from using angular material but the elevation is missing on the sidenav. I tried adding it using mat-elevation-zx but without success. I also tried boxshadow on css still without success. Is there any work around the elevation cause the one in the toolbar is working but on the fixed sidenav is not.

The html:

```<code><mat-sidenav-container class="sidenav-container">
  <mat-sidenav class="mat-elevation-z6" #drawer class="sidenav" fixedInViewport="true"
    [attr.role]="(isHandset$ | async) ? 'dialog' : 'navigation'" [mode]="(isHandset$ | async) ? 'over' : 'side'"
    [opened]="!(isHandset$ | async)">
    <mat-toolbar class="mat-elevation-z5" color="primary"><span class="logo">Logo</span></mat-toolbar>
    <mat-divider></mat-divider>
    <mat-nav-list class="nav-list">
      <div class="nav-item">
        <a class="nav-link" mat-list-item routerLink="" routerLinkActive="active-list-item" [routerLinkActiveOptions]="{ exact: true }">
          <mat-icon class="nav-icon">dashboard</mat-icon>
          Dashboard
        </a>
      </div>
      <div class="nav-item">
        <a class="nav-link" mat-list-item routerLink="/question" routerLinkActive="active-list-item">
          <mat-icon class="nav-icon">contact_support</mat-icon>
          Questions
        </a>
      </div>
      <div class="nav-item">
        <div></div>
        <a class="nav-link" mat-list-item routerLink="/category" routerLinkActive="active-list-item">
          <mat-icon class="nav-icon">category</mat-icon>
          Categories
        </a>
      </div>
      <div class="nav-item">
        <a class="nav-link" mat-list-item routerLink="/discipline" routerLinkActive="active-list-item">
          <mat-icon class="nav-icon">book</mat-icon>
          Discipline
        </a>
      </div>
      <div class="nav-item">
        <a class="nav-link" mat-list-item routerLink="/template" routerLinkActive="active-list-item">
          <mat-icon class="nav-icon">format_align_justify</mat-icon>
          Template
        </a>
      </div>
      <div class="nav-item">
        <a class="nav-link" mat-list-item routerLink="/level" routerLinkActive="active-list-item">
          <mat-icon class="nav-icon">equalizer</mat-icon>
          Level
        </a>
      </div>
    </mat-nav-list>
  </mat-sidenav>
  <mat-sidenav-content>
    <mat-toolbar class="mat-elevation-z5" color="primary">
      <button type="button" aria-label="Toggle sidenav" mat-icon-button (click)="drawer.toggle()"
        *ngIf="isHandset$ | async">
        <mat-icon aria-label="Side nav toggle icon">menu</mat-icon>
      </button>
      <div fxFlex></div>
      <div>
        <button mat-icon-button [matMenuTriggerFor]="menu">
          <mat-icon>account_circle</mat-icon>
          <mat-icon>keyboard_arrow_down</mat-icon>
        </button>
        <mat-menu #menu="matMenu" yPosition="below">
          <p class="user-info" mat-menu-item disableRipple><span class="full-name">name surname</span></p>
          <p class="user-info" mat-menu-item disableRipple><span class="email">email</span></p>
          <mat-divider></mat-divider>
          <button class="menu-item" mat-menu-item>Profile</button>
          <mat-divider></mat-divider>
          <button mat-menu-item>Sign out</button>
        </mat-menu>
      </div>
    </mat-toolbar>
    <main>
      <router-outlet></router-outlet>
    </main>
  </mat-sidenav-content>
</mat-sidenav-container>
</code>```

The css:

```<code>.sidenav-container {
  height: 100%;
}

.sidenav {
  width: 250px;
}

.mat-toolbar.mat-primary {
  position: sticky;
  top: 0;
  z-index: 4;
}

.logo {
  margin-left: 4%;
  font-size: 30px;
}

.nav-item {
  width: 230px;
}

.nav-icon {
  margin-right: 10%;
}

.nav-link {
  width: 200px;
  margin-top: 3%;
  margin-left: 3%;
}

.user-info:hover {
  background-color: transparent;
  cursor: text;
}

.user-info {
  line-height: 100%;
  height: 90%;
}

.full-name {
  font-weight: bold;
}

.email {
  font-size: 90%;
}
</code>```

答:
Your mat-sidenav dom element has two class attributes, refactor your code like so:

<mat-sidenav-container class="sidenav-container">
  <mat-sidenav #drawer class="sidenav mat-elevation-z6" fixedInViewport="true"
    [attr.role]="(isHandset$ | async) ? 'dialog' : 'navigation'" [mode]="(isHandset$ | async) ? 'over' : 'side'"
    [opened]="!(isHandset$ | async)">
    <mat-toolbar class="mat-elevation-z5" color="primary">Logo</mat-toolbar>
    <mat-divider></mat-divider>
    <mat-nav-list class="nav-list">

          <mat-icon class="nav-icon">dashboard</mat-icon>
          Dashboard

          <mat-icon class="nav-icon">contact_support</mat-icon>
          Questions

          <mat-icon class="nav-icon">category</mat-icon>
          Categories

          <mat-icon class="nav-icon">book</mat-icon>
          Discipline

          <mat-icon class="nav-icon">format_align_justify</mat-icon>
          Template

          <mat-icon class="nav-icon">equalizer</mat-icon>
          Level

    </mat-nav-list>
  </mat-sidenav>
  <mat-sidenav-content>
    <mat-toolbar class="mat-elevation-z5" color="primary">
      <button type="button" aria-label="Toggle sidenav" mat-icon-button (click)="drawer.toggle()"
        *ngIf="isHandset$ | async">
        <mat-icon aria-label="Side nav toggle icon">menu</mat-icon>
      </button>

        <button mat-icon-button [matMenuTriggerFor]="menu">
          <mat-icon>account_circle</mat-icon>
          <mat-icon>keyboard_arrow_down</mat-icon>
        </button>
        <mat-menu #menu="matMenu" yPosition="below">

name surname

email

          <mat-divider></mat-divider>
          <button class="menu-item" mat-menu-item>Profile</button>
          <mat-divider></mat-divider>
          <button mat-menu-item>Sign out</button>
        </mat-menu>

    </mat-toolbar>

      <router-outlet></router-outlet>

  </mat-sidenav-content>
</mat-sidenav-container>```
</div>
</div>
</p>

<p>Then remove the border on the sidenav using the "sidenav" css code like so:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.sidenav {
  width: 250px;
  border: none;
}</code>```

Body:
I generated a sidenav from using angular material but the elevation is missing on the sidenav. I tried adding it using mat-elevation-zx but without success. I also tried boxshadow on css still without success. Is there any work around the elevation cause the one in the toolbar is working but on the fixed sidenav is not.

The html:

<mat-sidenav-container class="sidenav-container">
  <mat-sidenav class="mat-elevation-z6" #drawer class="sidenav" fixedInViewport="true"
    [attr.role]="(isHandset$ | async) ? 'dialog' : 'navigation'" [mode]="(isHandset$ | async) ? 'over' : 'side'"
    [opened]="!(isHandset$ | async)">
    <mat-toolbar class="mat-elevation-z5" color="primary">Logo</mat-toolbar>
    <mat-divider></mat-divider>
    <mat-nav-list class="nav-list">

          <mat-icon class="nav-icon">dashboard</mat-icon>
          Dashboard

          <mat-icon class="nav-icon">contact_support</mat-icon>
          Questions

          <mat-icon class="nav-icon">category</mat-icon>
          Categories

          <mat-icon class="nav-icon">book</mat-icon>
          Discipline

          <mat-icon class="nav-icon">format_align_justify</mat-icon>
          Template

          <mat-icon class="nav-icon">equalizer</mat-icon>
          Level

    </mat-nav-list>
  </mat-sidenav>
  <mat-sidenav-content>
    <mat-toolbar class="mat-elevation-z5" color="primary">
      <button type="button" aria-label="Toggle sidenav" mat-icon-button (click)="drawer.toggle()"
        *ngIf="isHandset$ | async">
        <mat-icon aria-label="Side nav toggle icon">menu</mat-icon>
      </button>

        <button mat-icon-button [matMenuTriggerFor]="menu">
          <mat-icon>account_circle</mat-icon>
          <mat-icon>keyboard_arrow_down</mat-icon>
        </button>
        <mat-menu #menu="matMenu" yPosition="below">

name surname

email

          <mat-divider></mat-divider>
          <button class="menu-item" mat-menu-item>Profile</button>
          <mat-divider></mat-divider>
          <button mat-menu-item>Sign out</button>
        </mat-menu>

    </mat-toolbar>

      <router-outlet></router-outlet>

  </mat-sidenav-content>
</mat-sidenav-container>

The css:

.sidenav-container {
  height: 100%;
}

.sidenav {
  width: 250px;
}

.mat-toolbar.mat-primary {
  position: sticky;
  top: 0;
  z-index: 4;
}

.logo {
  margin-left: 4%;
  font-size: 30px;
}

.nav-item {
  width: 230px;
}

.nav-icon {
  margin-right: 10%;
}

.nav-link {
  width: 200px;
  margin-top: 3%;
  margin-left: 3%;
}

.user-info:hover {
  background-color: transparent;
  cursor: text;
}

.user-info {
  line-height: 100%;
  height: 90%;
}

.full-name {
  font-weight: bold;
}

.email {
  font-size: 90%;
}

Body:
Your mat-sidenav dom element has two class attributes, refactor your code like so:

<mat-sidenav-container class="sidenav-container">
  <mat-sidenav #drawer class="sidenav mat-elevation-z6" fixedInViewport="true"
    [attr.role]="(isHandset$ | async) ? 'dialog' : 'navigation'" [mode]="(isHandset$ | async) ? 'over' : 'side'"
    [opened]="!(isHandset$ | async)">
    <mat-toolbar class="mat-elevation-z5" color="primary"><span class="logo">Logo</span></mat-toolbar>
    <mat-divider></mat-divider>
    <mat-nav-list class="nav-list">
      <div class="nav-item">
        <a class="nav-link" mat-list-item routerLink="" routerLinkActive="active-list-item" [routerLinkActiveOptions]="{ exact: true }">
          <mat-icon class="nav-icon">dashboard</mat-icon>
          Dashboard
        </a>
      </div>
      <div class="nav-item">
        <a class="nav-link" mat-list-item routerLink="/question" routerLinkActive="active-list-item">
          <mat-icon class="nav-icon">contact_support</mat-icon>
          Questions
        </a>
      </div>
      <div class="nav-item">
        <div></div>
        <a class="nav-link" mat-list-item routerLink="/category" routerLinkActive="active-list-item">
          <mat-icon class="nav-icon">category</mat-icon>
          Categories
        </a>
      </div>
      <div class="nav-item">
        <a class="nav-link" mat-list-item routerLink="/discipline" routerLinkActive="active-list-item">
          <mat-icon class="nav-icon">book</mat-icon>
          Discipline
        </a>
      </div>
      <div class="nav-item">
        <a class="nav-link" mat-list-item routerLink="/template" routerLinkActive="active-list-item">
          <mat-icon class="nav-icon">format_align_justify</mat-icon>
          Template
        </a>
      </div>
      <div class="nav-item">
        <a class="nav-link" mat-list-item routerLink="/level" routerLinkActive="active-list-item">
          <mat-icon class="nav-icon">equalizer</mat-icon>
          Level
        </a>
      </div>
    </mat-nav-list>
  </mat-sidenav>
  <mat-sidenav-content>
    <mat-toolbar class="mat-elevation-z5" color="primary">
      <button type="button" aria-label="Toggle sidenav" mat-icon-button (click)="drawer.toggle()"
        *ngIf="isHandset$ | async">
        <mat-icon aria-label="Side nav toggle icon">menu</mat-icon>
      </button>
      <div fxFlex></div>
      <div>
        <button mat-icon-button [matMenuTriggerFor]="menu">
          <mat-icon>account_circle</mat-icon>
          <mat-icon>keyboard_arrow_down</mat-icon>
        </button>
        <mat-menu #menu="matMenu" yPosition="below">
          <p class="user-info" mat-menu-item disableRipple><span class="full-name">name surname</span></p>
          <p class="user-info" mat-menu-item disableRipple><span class="email">email</span></p>
          <mat-divider></mat-divider>
          <button class="menu-item" mat-menu-item>Profile</button>
          <mat-divider></mat-divider>
          <button mat-menu-item>Sign out</button>
        </mat-menu>
      </div>
    </mat-toolbar>
    <main>
      <router-outlet></router-outlet>
    </main>
  </mat-sidenav-content>
</mat-sidenav-container>

Then remove the border on the sidenav using the "sidenav" css code like so:

.sidenav {
  width: 250px;
  border: none;
}


问:
Batch script: \MyProg was unexpected at this time
I have a simple batch script test.bat that iterates thru command-line arguments:

```<code>@echo off
set prefix=C:\Program Files\MyProg
for %%x in (%*) do (
    echo %prefix%
)
</code>```

this version of the script works without issue in cmd.exe:

```<code>C:\>test a b
C:\Program Files\MyProg
C:\Program Files\MyProg
</code>```

However, if I modify the batch file to have a different prefix value, adding (x86):

```<code>set prefix=C:\Program Files (x86)\MyProg
</code>```

the script fails:

```<code>C:\>test a b
\MyProg was unexpected at this time.
</code>```

what a disaster! How can I resolve this issue?

答:
Though you figured out that delayedexpansion fixes the issue inside of your parenthesized code block, given the example as is, you do not require the code block and can therefore get away without the parenthesis and without delayedexpansion. It is also suggested to double quote your set variable and value to eliminate possible creeping whitespace:

```<code>@echo off
set "prefix=C:\Program Files (x86)\MyProg"
for %%x in (%*) do echo %prefix%
</code>```

I am also assuming that you wanted to use %%x in a way as well, therefore:

```<code>@echo off
set "prefix=C:\Program Files (x86)\MyProg"
for %%x in (%*) do echo %prefix%\%%~x
</code>```

Body:
I have a simple batch script test.bat that iterates thru command-line arguments:

@echo off
set prefix=C:\Program Files\MyProg
for %%x in (%*) do (
    echo %prefix%
)

this version of the script works without issue in cmd.exe:

C:\>test a b
C:\Program Files\MyProg
C:\Program Files\MyProg

However, if I modify the batch file to have a different prefix value, adding (x86):

set prefix=C:\Program Files (x86)\MyProg

the script fails:

C:\>test a b
\MyProg was unexpected at this time.

what a disaster! How can I resolve this issue?

Body:
Though you figured out that delayedexpansion fixes the issue inside of your parenthesized code block, given the example as is, you do not require the code block and can therefore get away without the parenthesis and without delayedexpansion. It is also suggested to double quote your set variable and value to eliminate possible creeping whitespace:

@echo off
set "prefix=C:\Program Files (x86)\MyProg"
for %%x in (%*) do echo %prefix%

I am also assuming that you wanted to use %%x in a way as well, therefore:

@echo off
set "prefix=C:\Program Files (x86)\MyProg"
for %%x in (%*) do echo %prefix%\%%~x


问:
Windows Forms Separator Control
Where in VS2010 can I find a horizontal separator control, as can be found in Outlook settings (screenshots below)?

https://jira.atlassian.com/secure/attachment/14933/outlook+settings.jpg
http://www.keithfimreite.com/Images/OutlookSettings3.gif

Note: VB.NET preferred, but C# answers okay.

答:
If I'm not mistaken, that's just a Line control, but I don't think that control exists anymore.  Here is a workaround.</p>

```<code>label1.AutoSize = False
label1.Height = 2
label1.BorderStyle = BorderStyle.Fixed3D
</code>```

Title: Windows Forms Separator Control

Body:
If I'm not mistaken, that's just a Line control, but I don't think that control exists anymore.  Here is a workaround.

label1.AutoSize = False
label1.Height = 2
label1.BorderStyle = BorderStyle.Fixed3D


问:
Java code for getting count in the sorted ArrayList for particular range
Need to find the count of the elements in the sorted ArrayList from the given range(x,y). And the count should have count of range elements also if it is in ArrayList.

So for, I have done this by traversing the whole list and getting the count.

Pseudo-code:

```<code>count = 0;
for (i=0; i<length(list); i++)
{
if (list[i]>= startrange and list[i]<=endrange)
  {
    count = count+1;
  }
}
</code>```

Current solution is taking more time because input array size is more than 1000000. Help me to optimize the solution.

Example:

Input array looks like this [1,4,5,8,9,12,16,19,23,26,28,29,30,31,33,35,37].

Input range: (12,30)

Output should be like 8

答:
```<code>int cnt=Stream.of(arr).filter(o->(o>=12&& o<=30)).count();
</code>```

Body:
Need to find the count of the elements in the sorted ArrayList from the given range(x,y). And the count should have count of range elements also if it is in ArrayList.

So for, I have done this by traversing the whole list and getting the count.

Pseudo-code:

count = 0;
for (i=0; i<length(list); i++)
{
if (list[i]>= startrange and list[i]<=endrange)
  {
    count = count+1;
  }
}

Current solution is taking more time because input array size is more than 1000000. Help me to optimize the solution.

Example:

Input array looks like this [1,4,5,8,9,12,16,19,23,26,28,29,30,31,33,35,37].

Input range: (12,30)

Output should be like 8


问:
Getting Parent Child hierarchy
I'm trying to get ancestors of a child (dog) upto Level 5. For Example in attached picture I'll be sending "Spencer di Casa Massarelli" and in result want to have associated parents (both father and mother). In my DB structure I've used father_id and mother_id.

DB & version: 10.4.11-MariaDB

Table Script:

```<code>CREATE TABLE `dogs` (
  `dog_id` int(11) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  `father_id` int(11) DEFAULT NULL,
  `moter_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`dog_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
</code>```

```<code>INSERT INTO `dogs` VALUES ('0', null, null, null);
INSERT INTO `dogs` VALUES ('1', 'Father', null, null);
INSERT INTO `dogs` VALUES ('2', 'Mother', null, null);
INSERT INTO `dogs` VALUES ('3', 'Father1', null, null);
INSERT INTO `dogs` VALUES ('4', 'Mother2', null, null);
INSERT INTO `dogs` VALUES ('5', 'Son', '1', '2');
INSERT INTO `dogs` VALUES ('6', 'Daughter', '3', '4');
INSERT INTO `dogs` VALUES ('7', 'GrandSon', '5', '6');
</code>```

I've tried following self join query but the problem is I'm unable to get right parents i.e., parents(both father and mother) of first parent.

```<code>SELECT t1.name AS lev1,
       t2.name AS lev2Father,
       t3.name AS lev2Mother,
       t4.name AS level3Father,
       t5.name AS level3Mother,
       t6.name AS level4Father,
       t7.name AS level4Mother,
       t8.name AS level5Father,
       t9.name AS level5Mother,
       t10.name AS level6Father,
       t11.name AS level6Mother
FROM dogs AS t1
LEFT JOIN dogs AS t2 ON t2.dog_id = t1.father_id
LEFT JOIN dogs AS t3 ON t3.dog_id = t1.mother_id
LEFT JOIN dogs AS t4 ON t4.dog_id = t2.father_id
LEFT JOIN dogs AS t5 ON t5.dog_id = t2.mother_id
LEFT JOIN dogs AS t6 ON t6.dog_id = t4.father_id
LEFT JOIN dogs AS t7 ON t7.dog_id = t4.mother_id
LEFT JOIN dogs AS t8 ON t8.dog_id = t6.father_id
LEFT JOIN dogs AS t9 ON t9.dog_id = t6.mother_id
LEFT JOIN dogs AS t10 ON t10.dog_id = t8.father_id
LEFT JOIN dogs AS t11 ON t11.dog_id = t8.mother_id
WHERE t1.dog_id = 7
</code>```

答:
```<code>WITH RECURSIVE
cte AS (
SELECT *, 0 level, '      ' relation
FROM dogs
WHERE dog_id = 7

UNION ALL

SELECT dogs.*, level + 1, 'father'
FROM dogs
JOIN cte ON cte.father_id = dogs.dog_id
WHERE level < 5

UNION ALL

SELECT dogs.*, level + 1, 'mother'
FROM dogs
JOIN cte ON cte.mother_id = dogs.dog_id
WHERE level < 5
)
SELECT *
FROM cte
ORDER BY level, relation;
</code>```

fiddle

Result

```<code>dog_id | name     | father_id | mother_id | level | relation
-----: | :------- | --------: | --------: | ----: | :-------
     7 | GrandSon |         5 |         6 |     0 |
     5 | Son      |         1 |         2 |     1 | father
     6 | Daughter |         3 |         4 |     1 | mother
     1 | Father   |      null |      null |     2 | father
     3 | Father1  |      null |      null |     2 | father
     2 | Mother   |      null |      null |     2 | mother
     4 | Mother2  |      null |      null |     2 | mother
</code>```

Title: Getting Parent Child hierarchy

Body:
I'm trying to get ancestors of a child (dog) upto Level 5. For Example in attached picture I'll be sending "Spencer di Casa Massarelli" and in result want to have associated parents (both father and mother). In my DB structure I've used father_id and mother_id.

DB & version: 10.4.11-MariaDB

Table Script:

CREATE TABLE `dogs` (
  `dog_id` int(11) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  `father_id` int(11) DEFAULT NULL,
  `moter_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`dog_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT INTO `dogs` VALUES ('0', null, null, null);
INSERT INTO `dogs` VALUES ('1', 'Father', null, null);
INSERT INTO `dogs` VALUES ('2', 'Mother', null, null);
INSERT INTO `dogs` VALUES ('3', 'Father1', null, null);
INSERT INTO `dogs` VALUES ('4', 'Mother2', null, null);
INSERT INTO `dogs` VALUES ('5', 'Son', '1', '2');
INSERT INTO `dogs` VALUES ('6', 'Daughter', '3', '4');
INSERT INTO `dogs` VALUES ('7', 'GrandSon', '5', '6');

I've tried following self join query but the problem is I'm unable to get right parents i.e., parents(both father and mother) of first parent.

SELECT t1.name AS lev1,
       t2.name AS lev2Father,
       t3.name AS lev2Mother,
       t4.name AS level3Father,
       t5.name AS level3Mother,
       t6.name AS level4Father,
       t7.name AS level4Mother,
       t8.name AS level5Father,
       t9.name AS level5Mother,
       t10.name AS level6Father,
       t11.name AS level6Mother
FROM dogs AS t1
LEFT JOIN dogs AS t2 ON t2.dog_id = t1.father_id
LEFT JOIN dogs AS t3 ON t3.dog_id = t1.mother_id
LEFT JOIN dogs AS t4 ON t4.dog_id = t2.father_id
LEFT JOIN dogs AS t5 ON t5.dog_id = t2.mother_id
LEFT JOIN dogs AS t6 ON t6.dog_id = t4.father_id
LEFT JOIN dogs AS t7 ON t7.dog_id = t4.mother_id
LEFT JOIN dogs AS t8 ON t8.dog_id = t6.father_id
LEFT JOIN dogs AS t9 ON t9.dog_id = t6.mother_id
LEFT JOIN dogs AS t10 ON t10.dog_id = t8.father_id
LEFT JOIN dogs AS t11 ON t11.dog_id = t8.mother_id
WHERE t1.dog_id = 7

Body:
WITH RECURSIVE
cte AS (
SELECT *, 0 level, '      ' relation
FROM dogs
WHERE dog_id = 7

UNION ALL

SELECT dogs.*, level + 1, 'father'
FROM dogs
JOIN cte ON cte.father_id = dogs.dog_id
WHERE level < 5

UNION ALL

SELECT dogs.*, level + 1, 'mother'
FROM dogs
JOIN cte ON cte.mother_id = dogs.dog_id
WHERE level < 5
)
SELECT *
FROM cte
ORDER BY level, relation;

fiddle

Result

dog_id | name     | father_id | mother_id | level | relation
-----: | :------- | --------: | --------: | ----: | :-------
     7 | GrandSon |         5 |         6 |     0 |
     5 | Son      |         1 |         2 |     1 | father
     6 | Daughter |         3 |         4 |     1 | mother
     1 | Father   |      null |      null |     2 | father
     3 | Father1  |      null |      null |     2 | father
     2 | Mother   |      null |      null |     2 | mother
     4 | Mother2  |      null |      null |     2 | mother


问:
Python Setter and Getter Naming
I'm trying to understand how getters and setters work in python with properties, but I'm confused in the naming convention.

Is there a specific naming standard for the getter and setter?  Why do I need to set the returning name of parameter with an "_" (underscore)?  If I were to change it to just "self.color" instead of "self._color", the getter and setter no longer work.  Also, if I were to change the name of the functions the print function is no longer is executed.  Any clarification would be greatly appreciated, thanks!

```<code>class FavoriteColor:
    def __init__(self, color):
        self.color = color

    @property
    def color(self):
        print('getter method')
        return self._color

    @color.setter
    def color(self, x):
        print('setter method')
        self._color = x

obj1 = FavoriteColor('blue')

</code>```

答:
If you did this:

```<code>@color.setter
def color(self, x):
    self.color = x
</code>```

Then this setter would call itself repeatedly. There's no difference between obj1.color = 'blue' and self.color = x, they both do the same thing, which is to invoke the setter def color. So with the setter invoking itself recursively, you have an endless recursive loop which will eventually crash your program.

For that purpose you need to actually store the value on some other attribute. Using "_color" for its name is just the rather obvious solution.

Note that using this kind of setter/getter in Python is frowned upon, if your setter/getter doesn't do anything. You can remove them entirely and just plainly set self.color = 'blue' for exactly the same effect as your setter/getter pair currently has. You should only use setters/getters if they do some additional processing. Since the syntax of a plain attribute and a setter/getter are identical, you can even safely transition to using setters/getters later on if you need to (in contrast to, say, Java, where a setter/getter is foo.setBar(...), which is not identical to foo.bar = ... and cannot be transparently substituted later).

Title: Python Setter and Getter Naming

Body:
I'm trying to understand how getters and setters work in python with properties, but I'm confused in the naming convention.

Is there a specific naming standard for the getter and setter?  Why do I need to set the returning name of parameter with an "_" (underscore)?  If I were to change it to just "self.color" instead of "self._color", the getter and setter no longer work.  Also, if I were to change the name of the functions the print function is no longer is executed.  Any clarification would be greatly appreciated, thanks!

class FavoriteColor:
    def __init__(self, color):
        self.color = color

    @property
    def color(self):
        print('getter method')
        return self._color

    @color.setter
    def color(self, x):
        print('setter method')
        self._color = x

obj1 = FavoriteColor('blue')

Body:
If you did this:

@color.setter
def color(self, x):
    self.color = x

Then this setter would call itself repeatedly. There's no difference between obj1.color = 'blue' and self.color = x, they both do the same thing, which is to invoke the setter def color. So with the setter invoking itself recursively, you have an endless recursive loop which will eventually crash your program.

For that purpose you need to actually store the value on some other attribute. Using "_color" for its name is just the rather obvious solution.

Note that using this kind of setter/getter in Python is frowned upon, if your setter/getter doesn't do anything. You can remove them entirely and just plainly set self.color = 'blue' for exactly the same effect as your setter/getter pair currently has. You should only use setters/getters if they do some additional processing. Since the syntax of a plain attribute and a setter/getter are identical, you can even safely transition to using setters/getters later on if you need to (in contrast to, say, Java, where a setter/getter is foo.setBar(...), which is not identical to foo.bar = ... and cannot be transparently substituted later).


问:
Accessing NumPy array elements not in a given index list
I have a NumPy array with the shape (100, 170, 256). And I have an array consisting of indexes [0, 10, 20, 40, 70].

I can get the sub-arrays corresponding to the indexes as follows:

```<code>sub_array = array[..., index]
</code>```

This returns an array with the shape (100, 170, 5) as expected. Now, I am trying to take the complement and get the sub-array NOT corresponding to those indexes. So, I did:

```<code>sub_array = array[..., ~index]
</code>```

This still returns me an array of shape (100, 170, 5) for some reason. I wonder how to do this complement operation of these indexes in python?

[EDIT]

Also tried:

```<code>sub_array = array[..., not(index.any)]
</code>```

However, this does not do the thing I want as well (getting array of shape (100, 170, 251).

答:
The question is answered but I propose a benchmark of the three methods here.

Fastest solution is boolean mask (with small and larger index array size)

```<code>mask = np.ones(arr.size, dtype=bool)
mask[indexes] = False
result = arr[mask]
</code>```

It is 2000 times faster than the list comprehension and marginaly faster than np.delete

Code to reproduce

Three proposed solutions: list comprehension (sol1), boolean mask (sol2) or np.delete (sol3)

```<code>d = 100000
a = np.random.rand(d)
idx = np.random.randint(d, size = 10)

# list comprehension
def sol1(arr, indexes):
    return arr[[i for i in range(arr.size) if i not in indexes]]
sol1(a, idx)
# Out[30]: array([0.13044518, 0.68564961, 0.03033223, ..., 0.03796257, 0.40137137, 0.45403929])

# boolean mask
def sol2(arr, indexes):
    mask = np.ones(arr.size, dtype=bool)
    mask[indexes] = False
    return arr[mask]
sol2(a, idx)
# Out[32]: array([0.13044518, 0.68564961, 0.03033223, ..., 0.03796257, 0.40137137, 0.45403929])

# np.delete
def sol3(arr, indexes):
    return np.delete(arr, indexes)
sol3(a, idx)
# Out[36]: array([0.13044518, 0.68564961, 0.03033223, ..., 0.03796257, 0.40137137, 0.45403929])

</code>```

Results

```<code>
%timeit sol1(a, idx)
384 ms ± 2.75 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit sol2(a, idx)
154 µs ± 15.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit sol3(a, idx)
194 µs ± 18.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

idx = np.random.randint(d, size = 1000)
%timeit sol1(a, idx)
386 ms ± 7.75 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit sol2(a, idx)
171 µs ± 11.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit sol3(a, idx)
205 µs ± 10.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
</code>```

Body:
I have a NumPy array with the shape (100, 170, 256). And I have an array consisting of indexes [0, 10, 20, 40, 70].

I can get the sub-arrays corresponding to the indexes as follows:

sub_array = array[..., index]

This returns an array with the shape (100, 170, 5) as expected. Now, I am trying to take the complement and get the sub-array NOT corresponding to those indexes. So, I did:

sub_array = array[..., ~index]

This still returns me an array of shape (100, 170, 5) for some reason. I wonder how to do this complement operation of these indexes in python?

[EDIT]

Also tried:

sub_array = array[..., not(index.any)]

However, this does not do the thing I want as well (getting array of shape (100, 170, 251).

Body:
The question is answered but I propose a benchmark of the three methods here.

Fastest solution is boolean mask (with small and larger index array size)

mask = np.ones(arr.size, dtype=bool)
mask[indexes] = False
result = arr[mask]

It is 2000 times faster than the list comprehension and marginaly faster than np.delete

Code to reproduce

Three proposed solutions: list comprehension (sol1), boolean mask (sol2) or np.delete (sol3)

d = 100000
a = np.random.rand(d)
idx = np.random.randint(d, size = 10)

# list comprehension
def sol1(arr, indexes):
    return arr[[i for i in range(arr.size) if i not in indexes]]
sol1(a, idx)
# Out[30]: array([0.13044518, 0.68564961, 0.03033223, ..., 0.03796257, 0.40137137, 0.45403929])

# boolean mask
def sol2(arr, indexes):
    mask = np.ones(arr.size, dtype=bool)
    mask[indexes] = False
    return arr[mask]
sol2(a, idx)
# Out[32]: array([0.13044518, 0.68564961, 0.03033223, ..., 0.03796257, 0.40137137, 0.45403929])

# np.delete
def sol3(arr, indexes):
    return np.delete(arr, indexes)
sol3(a, idx)
# Out[36]: array([0.13044518, 0.68564961, 0.03033223, ..., 0.03796257, 0.40137137, 0.45403929])

Results

%timeit sol1(a, idx)
384 ms ± 2.75 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit sol2(a, idx)
154 µs ± 15.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit sol3(a, idx)
194 µs ± 18.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

idx = np.random.randint(d, size = 1000)
%timeit sol1(a, idx)
386 ms ± 7.75 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit sol2(a, idx)
171 µs ± 11.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit sol3(a, idx)
205 µs ± 10.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)


问:
.NET DotRas vpn connection serverAddress resolving
I'm currently trying to create VPN connection with c# using DotRas lib. Everything looks quite easy, but I just can't understand how DotRas resolves server address while creating entry.

```<code>RasEntry.CreateVpnEntry("EntryName", "ServerAddress", RasVpnStrategy.L2tpOnly, RasDevice);
</code>```

I saw that when I'm giving IP address and dialing, I'm catching exception

The remote connection was not made because the name of the remote access server did not resolve

When I'm giving unresolved server address, everything works fine !!!!

So my question is: How DotRas resolves serverAddress? I mean to what format? Why it fails when IP is given?

P.S. I've tried to dig in to the DotRas source code, but couldn't find anything.....

答:
```<code>RasDialer dialer = new RasDialer();
dialer.EntryName = "the name";
dialer.PhoneNumber = "";
//important,leave this empty,otherwise you will get the exception
RasHandle myras = dialer.Dial();
</code>```

Body:
I'm currently trying to create VPN connection with c# using DotRas lib. Everything looks quite easy, but I just can't understand how DotRas resolves server address while creating entry.

RasEntry.CreateVpnEntry("EntryName", "ServerAddress", RasVpnStrategy.L2tpOnly, RasDevice);

I saw that when I'm giving IP address and dialing, I'm catching exception

The remote connection was not made because the name of the remote access server did not resolve

When I'm giving unresolved server address, everything works fine !!!!

So my question is: How DotRas resolves serverAddress? I mean to what format? Why it fails when IP is given?

P.S. I've tried to dig in to the DotRas source code, but couldn't find anything.....


问:
Where does dev_dbg writes log to?
In a device driver source in the Linux tree,  I saw dev_dbg(...) and dev_err(...), where do I find the logged message?

One reference suggest to add #define DEBUG . The other reference involves dynamic debug and debugfs, and I got lost.

答:
you can find dev_err(...) in kernel messages. As the name implies, dev_err(...) messages are error messages, so they will definitely be printed if the execution comes to that point. dev_dbg(...) are debug messages which are more generously used in the kernel driver code and they are not printed by default. So everything you have read about dynamic_debugging comes into play with dev_dbg(...).

There are several pre-conditions to have dynamic debugging working, below 1. and 2. are general preconditions for dynamic debugging. 3. and later are for your particular driver/module/subsystem and can be .

Dynamic debugging support has to be in your kernel config CONFIG_DYNAMIC_DEBUG=y. You may check if it is the case zgrep DYNAMIC_DEBUG /proc/config.gz

debugfs has to be mounted. You can check with sudo mount | grep debugfs and if not existing, you can mount with sudo mount -t debugfs /sys/kernel/debug

refer to dynamic_debugging and enable the particular file/function/line you are interested

Title: Where does dev_dbg writes log to?


问:
how to make scrollable button in android
Hello i'm trying to make an equalizer for my app but i can't figure out how to make the buttons. I don't really know how to explain myself so here is a picture that reveals more than my words:

Do i need animations? Can you guys point me in the right direction?

Thanks in advance.

答: There's a nice tutorial here for creating an odometer widget. It's not at all the look you want, but many (most) of the same issues apply, including custom rendering, dealing with touch events, and wiring up a series of sub-widgets into a larger control. It's the first thing I thought of when I saw your graphic.</p>


问:
How to fix 431 Request Header Fields Too Large in React-Redux app
I'm working through a MERN sign up/login auth tutorial on youtube that uses Redux. When attempting to POST a test user to the server in Postman, I receive the 431 header request is too large error response.

I've read in some places that clearing the cache/history in your browser works, so I've tried that to no avail. I've also added in a "Clear-Site-Data": "*" entry to the header request (in addition to "Content-Type": "application/json") which hasn't worked, either.

Client Side Code for Sign Up

```<code>  onSubmit = e => {
    e.preventDefault();
    const { name, email, password } = this.state;

    const newUser = {
      name,
      email,
      password
    };

    this.props.register(newUser);
  };

//redux actions
export const register = ({ name, email, password }) => dispatch => {

  const config = {
    headers: {
      "Content-Type": "application/json",
      "Clear-Site-Data": "*"
    }
  };

  // Request body
  const body = JSON.stringify({ name, email, password });

  axios
    .post('/api/users', body, config)
    .then(res =>
      dispatch({
        type: REGISTER_SUCCESS,
        payload: res.data
      })
    )
    .catch(err => {
      dispatch(
        returnErrors(err.response.data, err.response.status, 'REGISTER_FAIL')
      );
      dispatch({
        type: REGISTER_FAIL
      });
    });
};

</code>```

The user sign up should be sending a name, email and password to my connected Mongo db, however, it halts me and redux hits the REGISTER_FAIL type I created returning the 431 error. Any help would be greatly appreciated. Thank you!

答:
I had similar problems with just using localhost(not limited to redux). Maybe this might help.

Put this into url: chrome://settings/?search=cache

Click on Clear Browsing data.

Tick cookies and other site data (Important since cookies is in HTTP header)
TIck cached images and files (might be optional)

Body:
I'm working through a MERN sign up/login auth tutorial on youtube that uses Redux. When attempting to POST a test user to the server in Postman, I receive the 431 header request is too large error response.

I've read in some places that clearing the cache/history in your browser works, so I've tried that to no avail. I've also added in a "Clear-Site-Data": "*" entry to the header request (in addition to "Content-Type": "application/json") which hasn't worked, either.

Client Side Code for Sign Up

  onSubmit = e => {
    e.preventDefault();
    const { name, email, password } = this.state;

    const newUser = {
      name,
      email,
      password
    };

    this.props.register(newUser);
  };

//redux actions
export const register = ({ name, email, password }) => dispatch => {

  const config = {
    headers: {
      "Content-Type": "application/json",
      "Clear-Site-Data": "*"
    }
  };

  // Request body
  const body = JSON.stringify({ name, email, password });

  axios
    .post('/api/users', body, config)
    .then(res =>
      dispatch({
        type: REGISTER_SUCCESS,
        payload: res.data
      })
    )
    .catch(err => {
      dispatch(
        returnErrors(err.response.data, err.response.status, 'REGISTER_FAIL')
      );
      dispatch({
        type: REGISTER_FAIL
      });
    });
};

The user sign up should be sending a name, email and password to my connected Mongo db, however, it halts me and redux hits the REGISTER_FAIL type I created returning the 431 error. Any help would be greatly appreciated. Thank you!


问:
How to fix Bootstrap-3 and Bootstrap-4 difference problems?
I'm learning Angular with a little-bit old tutorial because instructor uses bootstrap 3.3.7 and at the present time I've downloaded bootstrap 4.4.1 version with which I cannot follow instructor and implement some futures (glyphicons).

Can I install the old version of bootstrap in particular project- to follow the instructor to the end of course?
Or can I somehow with other way fix this problem - I mean: fix the differences in bootstrap versions?

Sorry for bad English and many thanks in advance!

答:
Bootstrap 4 is a major rewrite of boostrap-3. There are some notable changes. Therefore,  I think you should include all of boostrap-3 resources
in your project and follow you instructor. Otherwise, you may use a lot of time configuring the differences. Later on, you can easily migrate. This links may help you.

https://getbootstrap.com/docs/3.4/getting-started/

https://v4-alpha.getbootstrap.com/migration/

If you use bootstap-3, you need to remove bootstrap-4 from your html file.

In case, you stick to bootstrap-4. You can use icons like font-aswesome, featericon, and bootsrap-4 icons, because bootstrap-4 has dropped Glyphicons. This guides help you how to use icons.

https://getbootstrap.com/docs/4.0/extend/icons/

Glyphicon not working in bootstrap version 4.1 and later

Bootstrap 4 - Glyphicons migration?

https://github.com/feathericons/feather#feather


问:
How can we set chart settings for number abbreviations of Data Studio Report?
Date and number abbreviations in Data Studio Report look different on different users. In English, abbreviation of 1000 is K and abbreviation of 1,000,000,000 is B. But In Turkish, abbreviation of 1000 is B.
This causes confusion between a thousand or a billion. When examined users with different report views, we found that Google Account Language Settings are different.Is it possible set these abbreviations so that they do not change with the Google Account Language Settings?

答:
The number format is based on the language of the respective Google Account that's logged in by the viewer. To display the Report URL in a specific language (e.g. English), add the suffix:

```<code>?hl=en
</code>```

More Language Codes

1) Standard URL

https://datastudio.google.com/reporting/48900f64-2068-4331-b707-f82df114542a

2) English (US)

https://datastudio.google.com/reporting/48900f64-2068-4331-b707-f82df114542a?hl=en

3) Spanish

https://datastudio.google.com/reporting/48900f64-2068-4331-b707-f82df114542a?hl=es

Source: Google Forum Post (Nimantha 13 Jan 2020)

Body:
The number format is based on the language of the respective Google Account that's logged in by the viewer. To display the Report URL in a specific language (e.g. English), add the suffix:

?hl=en

More Language Codes

1) Standard URL

https://datastudio.google.com/reporting/48900f64-2068-4331-b707-f82df114542a

2) English (US)

https://datastudio.google.com/reporting/48900f64-2068-4331-b707-f82df114542a?hl=en

3) Spanish

https://datastudio.google.com/reporting/48900f64-2068-4331-b707-f82df114542a?hl=es

Source: Google Forum Post (Nimantha 13 Jan 2020)


问:
how to pass basic authentication in api call in react native using asynch await fetch
i want to call the basic authentication rest api in the react native.how to pass basic authentication headers.getting error - unhandled promise rejection - cant find base64 variable</p>

```<code>  getDataFromAPI=async()=>
{

  var headers = new Headers();
  headers.append("Authorization", "Basic " + base64.encode("admin:admin@123"));
  const endpoint='url'
  const res=await fetch (endpoint,{headers:headers})
  const data=await res.json()
  this.setState({items:data})
}
  _renderItem=({item,index})=>{
    let{cardText,card,cardImage}= styles
return  (
  <TouchableOpacity style={card}>
          <Text style={cardText}>{item.id} Reactor Status:  {item.ph}</Text>
  </TouchableOpacity>
)
}
</code>```

答:
Firstly, it depends on what authentication method you are using at server side but as of above code you can try below</p>

```<code>    fetch("https://www.majhgaon.com/app/supplier/add_report", {
            method: "POST",
            headers: {
              'Accept': 'application/json',
              "key-name": "kay-value",
            },
          body: JSON.stringify({
                  ....
               })
          })
</code>```

Body:
i want to call the basic authentication rest api in the react native.how to pass basic authentication headers.getting error - unhandled promise rejection - cant find base64 variable

  getDataFromAPI=async()=>
{

  var headers = new Headers();
  headers.append("Authorization", "Basic " + base64.encode("admin:admin@123"));
  const endpoint='url'
  const res=await fetch (endpoint,{headers:headers})
  const data=await res.json()
  this.setState({items:data})
}
  _renderItem=({item,index})=>{
    let{cardText,card,cardImage}= styles
return  (
  <TouchableOpacity style={card}>
          <Text style={cardText}>{item.id} Reactor Status:  {item.ph}</Text>
  </TouchableOpacity>
)
}

Body:
Firstly, it depends on what authentication method you are using at server side but as of above code you can try below

    fetch("https://www.majhgaon.com/app/supplier/add_report", {
            method: "POST",
            headers: {
              'Accept': 'application/json',
              "key-name": "kay-value",
            },
          body: JSON.stringify({
                  ....
               })
          })


问:
Can we have forests or data replication between different versions of marklogic?
Currently we are migrating from Marklogic version 8 to Marklogic version 10.

We can do replication between forests of same version Marklogic-v10 to Marklogic-v10, so i need to understand whether we can have replication between forests of ML-v8 to ML-v10 and if we can, what problems can arise if we try to do that?

答:
Flexible Replication works between MarkLogic 8 and MarkLogic 10, Database Replication as far as I know not. Where Database Replication operates on a fairly low level (it sends journal frames, and forest data across) with a configurable allowed Replication Lag, Flexible Replication operates on fairly highly level of abstraction, and uses asynchronous communication by design (master does not wait for its completion).

Database Replication allows for a certain level of consistency. Flexible Replication however can be used for instance in master-master scenarios. Each has its own use cases, but if you need to maintain different major versions of MarkLogic, Flexible Replication is the only option of the two.

Next to that, there are also ways to move data between clusters outside of MarkLogic, using tools like MLCP, Corb, or NiFi for instance. But those are usually more suited for one-time migrations in such cases.

Please note that MarkLogic 8 has reached End of Life: https://help.marklogic.com/

HTH!


问:
MigLayout JTextArea is not shrinking when used with linewrap=true
If I use a JTextArea with MigLayout like this:

```<code>MigLayout thisLayout = new MigLayout("", "[][grow]", "[]20[]");
   this.setLayout(thisLayout);
   {
jLabel1 = new JLabel();
this.add(jLabel1, "cell 0 0");
jLabel1.setText("jLabel1");
  }
  {
 jTextArea1 = new JTextArea();
this.add(jTextArea1, "cell 0 1 2 1,growx");
jTextArea1.setText("jTextArea1");
jTextArea1.setLineWrap(false);
   }
</code>```

then the JTextArea grows and shrinks perfectly when resizing the window. When I set the linewrap to true the JTextArea is not shrinking when I make the window smaller again.

答:
I just discovered that this can simply be resolved by changing the line

```<code>this.add(jTextArea1, "cell 0 1 2 1,growx");
</code>```

to

```<code>this.add(jTextArea1, "cell 0 1 2 1,growx, wmin 10");
</code>```

and no extra panels are needed. Setting an explicit minimum size is what does the trick.

Explanation: see the note under the section on padding in the MiGLayout whitepaper:

http://www.migcalendar.com/miglayout/whitepaper.html

Body:
If I use a JTextArea with MigLayout like this:

MigLayout thisLayout = new MigLayout("", "[][grow]", "[]20[]");
   this.setLayout(thisLayout);
   {
jLabel1 = new JLabel();
this.add(jLabel1, "cell 0 0");
jLabel1.setText("jLabel1");
  }
  {
 jTextArea1 = new JTextArea();
this.add(jTextArea1, "cell 0 1 2 1,growx");
jTextArea1.setText("jTextArea1");
jTextArea1.setLineWrap(false);
   }

then the JTextArea grows and shrinks perfectly when resizing the window. When I set the linewrap to true the JTextArea is not shrinking when I make the window smaller again.

Body:
I just discovered that this can simply be resolved by changing the line

this.add(jTextArea1, "cell 0 1 2 1,growx");

to

this.add(jTextArea1, "cell 0 1 2 1,growx, wmin 10");

and no extra panels are needed. Setting an explicit minimum size is what does the trick.

Explanation: see the note under the section on padding in the MiGLayout whitepaper:

http://www.migcalendar.com/miglayout/whitepaper.html


问:
How to check if today is a weekend in bash?
How to check if today is a weekend using bash or even perl?

I want to prevent certain programs to run on a weekend.

答:
printf also has date

```<code>printf -v day '%(%a)T'
case $day in
    Sat|Sun) echo "Hooray!";;
esac
</code>```

https://ideone.com/wU7C0c - demo

Body:
printf also has date

printf -v day '%(%a)T'
case $day in
    Sat|Sun) echo "Hooray!";;
esac

https://ideone.com/wU7C0c - demo


问:
Can I call a graphql mutation inside an Error Link in the apollo client
Hi This is a part of My Apollo Client

```<code>const errorLink = onError(({ graphQLErrors, networkError, operation }) => {
  if(graphQLErrors) {
    graphQLErrors.forEach(({ message, location, path }) => {
      if (message === 'Pleage Re-Sign In') {
        cookies.remove('userToken')
        cookies.remove('hshashes')
        MoveME('/')
      }
      if (message === 'Unathorized') {
        return MoveME('/')
      }
      if (message === 'Access Denied') {
        return MoveME('/dashboard/home')
      }
      console.log(`[GraphQL Error] Message: ${message}, location: ${location}, path: ${path}`)
    })
  }

  if(networkError){
    console.log(`
      [network error ${networkError.message}] Operation: ${operation.operationName}
    `)
  }
})
</code>```

I'm wondering if I can call a Mutation to the the server to make a log in the database which I have created in the backend. Can I call the Mutation here in the app. Normally I would use "useMutation" from Apollo-React-hooks but that can only be called inside a React component . I have already done this By Moving the User to another page for example : "localhost:3000/test" which in that components I tried to use useEffect and call the mutation in useEffect with a seconde parameter of an empty array so that it calls once and then redirect the user where I want . but this is not good. is there anyother way I can do this which is best practice?

sry for bad English :)

答:
Yes, Apollo-React-hooks can only be called inside a React component

Try to use apollo-boost

1.create a file index.js

```<code>import ApolloClient from 'apollo-boost';
import * as constant from 'constant';

const client = new ApolloClient({
  uri: `${constant.backendUrl}graphql`,
});

function graphqlQuery({ variables, query }) {
  return client.query({
    fetchPolicy: 'no-cache',
    variables, // your variables
    query, // your query schema
  });
}

function graphqlMutation({ variables = null, mutation }) {
  return client.mutate({
    variables,
    mutation,
  });
}

export { client as default, graphqlQuery, graphqlMutation };
</code>```

2.How to use it

```<code>import { graphqlMutation } from 'index.js';
import { gql } from 'apollo-boost';

/**
 * Create user
 * @param {Object} data
 * @param {string} data.email
 * @param {string} data.firstName
 * @param {string} data.lastName
 * @param {string} data.gender
 * @param {number} data.height
 * @param {number} data.weight
 * @param {string} data.birthDate
 */
function createUser(data) {
  const createUser = gql`
    mutation createUser($userInput: UserInput) {
      createUser(userInput: $userInput) {
        status
        message
      }
    }
  `;
  const variables = {
    userInput: data,
  };
  return graphqlMutation({ variables, mutation: createUser });
}

export { createUser };
</code>```

Now you can use this createUser function in anywhere you want

Body:
Hi This is a part of My Apollo Client

const errorLink = onError(({ graphQLErrors, networkError, operation }) => {
  if(graphQLErrors) {
    graphQLErrors.forEach(({ message, location, path }) => {
      if (message === 'Pleage Re-Sign In') {
        cookies.remove('userToken')
        cookies.remove('hshashes')
        MoveME('/')
      }
      if (message === 'Unathorized') {
        return MoveME('/')
      }
      if (message === 'Access Denied') {
        return MoveME('/dashboard/home')
      }
      console.log(`[GraphQL Error] Message: ${message}, location: ${location}, path: ${path}`)
    })
  }

  if(networkError){
    console.log(`
      [network error ${networkError.message}] Operation: ${operation.operationName}
    `)
  }
})

I'm wondering if I can call a Mutation to the the server to make a log in the database which I have created in the backend. Can I call the Mutation here in the app. Normally I would use "useMutation" from Apollo-React-hooks but that can only be called inside a React component . I have already done this By Moving the User to another page for example : "localhost:3000/test" which in that components I tried to use useEffect and call the mutation in useEffect with a seconde parameter of an empty array so that it calls once and then redirect the user where I want . but this is not good. is there anyother way I can do this which is best practice?

sry for bad English :)

Body:
Yes, Apollo-React-hooks can only be called inside a React component

Try to use apollo-boost

1.create a file index.js

import ApolloClient from 'apollo-boost';
import * as constant from 'constant';

const client = new ApolloClient({
  uri: `${constant.backendUrl}graphql`,
});

function graphqlQuery({ variables, query }) {
  return client.query({
    fetchPolicy: 'no-cache',
    variables, // your variables
    query, // your query schema
  });
}

function graphqlMutation({ variables = null, mutation }) {
  return client.mutate({
    variables,
    mutation,
  });
}

export { client as default, graphqlQuery, graphqlMutation };

2.How to use it

import { graphqlMutation } from 'index.js';
import { gql } from 'apollo-boost';

/**
 * Create user
 * @param {Object} data
 * @param {string} data.email
 * @param {string} data.firstName
 * @param {string} data.lastName
 * @param {string} data.gender
 * @param {number} data.height
 * @param {number} data.weight
 * @param {string} data.birthDate
 */
function createUser(data) {
  const createUser = gql`
    mutation createUser($userInput: UserInput) {
      createUser(userInput: $userInput) {
        status
        message
      }
    }
  `;
  const variables = {
    userInput: data,
  };
  return graphqlMutation({ variables, mutation: createUser });
}

export { createUser };

Now you can use this createUser function in anywhere you want


问:
ERROR: DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=CON.CONTACT_ID, DRIVER=4.21.29
while running this query in DB2 i am getting error.could some one please suggest.

DELETE FROM INT_ADD WHERE IN_ADDR_ID IN(SELECT CON.IN_ADDR_ID FROM CONTACT LEFT JOIN USER_CONTACT UC ON UC.CONTACT_ID = CON.CONTACT_ID WHERE UC.USER_ID=12426371);

答: You forgot to assign a correlation name CON to the CONTACT table, which is used for a number of columns from this table.


问:
Row Wrap in flex-box not wrapping in Safari
A flex container has four children, each with a flex-basis of 25% an a min-width. flex-flow is set to row wrap. Browsers other then Safari handle this as expected: if the min-width is reached, it wraps the the next item to the next row. In Safari it overflow the container.

See demo here:
http://codepen.io/lbilharz/pen/aJbkI

JADE

```<code>h1 Why this ain't wrappin' in mobile-safari?
  .flex
    for i in ['one','two','three','four']
      .item
        h2=i
</code>```

Stylus

```<code>.flex
  display flex
  flex-wrap wrap
  flex-direction row
  padding 1em
  background lightyellow
  .item
    flex 1 0 25%
    padding 1em
    box-sizing border-box
    min-width 15em
</code>```

Any ideas?

答:
Please, note that not all prefixers work the same way, so there's known issues on every prefixer that puts you in need to manually add some vendor prefix. Don't rely on blind-trusting on prefixers or automated software unless you checked it works hundred percent in your project.

For detailed flex bugs, please refer:

https://caniuse.com/#feat=flexbox

https://github.com/philipwalton/flexbugs

As Joseph Hansen pointed out, including width property as third param on flex declaration is the desired workaround for flex and it should fix most of issues derived from merging flex with some declarations.

But this doesn't solve all issues on safari, or even other browsers; it sometimes will depend on childrens or some other property; in the example below, you'll see the middle box growing more than usual, even when all three elements are supposed to keep same width ON SAFARI.
If you use chrome, it will look pretty nice.

This is not a flex issue but a display interpreter one. Simply removing display: inline-table will fix the issue for safari, but, with more child elements, it will make all cards grow in height, so we'll need to fix this other behaviour derived from switching to another display property.

.flexrow {
  display: -webkit-flex;
  display: flex;
  flex-flow: row wrap;
  flex-direction: row;
  -webkit-flex-wrap: wrap;
  flex-wrap: wrap;
  margin: 0px -15px;
}
.card-container {
  display: inline-table;
}
div.card-container {
  -webkit-flex: 0 1 calc(33.3333% - 30px);
  flex: 0 1 calc(33.3333% - 30px);
  margin: 15px;
}
.card-container {
  background:green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flexrow">
  <div class="card-container">
      <div class="card">
        <p class="title">
          test test test
        </p>
      </div>
    </div>

    <div class="card-container">
      <div class="card">
        <p class="title">
          test testtesttest test test test
        </p>
      </div>
    </div>

    <div class="card-container">
      <div class="card">
        <p class="title">
          test test
        </p>
      </div>
    </div>
</div></code>```

this is only an example but i suggest to check every property that have boundaries with flexbox (i.e. display, position and more).

Here the working example:

.flexrow {
  display: -webkit-flex;
  display: flex;
  flex-flow: row wrap;
  flex-direction: row;
  -webkit-flex-wrap: wrap;
  flex-wrap: wrap;
  margin: 0px -15px;
}
.card-container {
  // display: inline-table;
}
div.card-container {
  -webkit-flex: 0 1 calc(33.3333% - 30px);
  flex: 0 1 calc(33.3333% - 30px);
  margin: 15px;
}
.card-container {
  background:green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flexrow">
  <div class="card-container">
      <div class="card">
        <p class="title">
          test test test
        </p>
      </div>
    </div>

    <div class="card-container">
      <div class="card">
        <p class="title">
          test testtesttest test test test
        </p>
      </div>
    </div>

    <div class="card-container">
      <div class="card">
        <p class="title">
          test test
        </p>
      </div>
    </div>
</div></code>```

Body:
A flex container has four children, each with a flex-basis of 25% an a min-width. flex-flow is set to row wrap. Browsers other then Safari handle this as expected: if the min-width is reached, it wraps the the next item to the next row. In Safari it overflow the container.

See demo here:
http://codepen.io/lbilharz/pen/aJbkI

JADE

h1 Why this ain't wrappin' in mobile-safari?
  .flex
    for i in ['one','two','three','four']
      .item
        h2=i

Stylus

.flex
  display flex
  flex-wrap wrap
  flex-direction row
  padding 1em
  background lightyellow
  .item
    flex 1 0 25%
    padding 1em
    box-sizing border-box
    min-width 15em

Any ideas?

Body:
Please, note that not all prefixers work the same way, so there's known issues on every prefixer that puts you in need to manually add some vendor prefix. Don't rely on blind-trusting on prefixers or automated software unless you checked it works hundred percent in your project.

For detailed flex bugs, please refer:

https://caniuse.com/#feat=flexbox

https://github.com/philipwalton/flexbugs

As Joseph Hansen pointed out, including width property as third param on flex declaration is the desired workaround for flex and it should fix most of issues derived from merging flex with some declarations.

But this doesn't solve all issues on safari, or even other browsers; it sometimes will depend on childrens or some other property; in the example below, you'll see the middle box growing more than usual, even when all three elements are supposed to keep same width ON SAFARI.
If you use chrome, it will look pretty nice.

This is not a flex issue but a display interpreter one. Simply removing display: inline-table will fix the issue for safari, but, with more child elements, it will make all cards grow in height, so we'll need to fix this other behaviour derived from switching to another display property.

.flexrow {
  display: -webkit-flex;
  display: flex;
  flex-flow: row wrap;
  flex-direction: row;
  -webkit-flex-wrap: wrap;
  flex-wrap: wrap;
  margin: 0px -15px;
}
.card-container {
  display: inline-table;
}
div.card-container {
  -webkit-flex: 0 1 calc(33.3333% - 30px);
  flex: 0 1 calc(33.3333% - 30px);
  margin: 15px;
}
.card-container {
  background:green;
}

<div class="flexrow">
  <div class="card-container">
      <div class="card">
        <p class="title">
          test test test
        </p>
      </div>
    </div>

    <div class="card-container">
      <div class="card">
        <p class="title">
          test testtesttest test test test
        </p>
      </div>
    </div>

    <div class="card-container">
      <div class="card">
        <p class="title">
          test test
        </p>
      </div>
    </div>
</div>

this is only an example but i suggest to check every property that have boundaries with flexbox (i.e. display, position and more).

Here the working example:

.flexrow {
  display: -webkit-flex;
  display: flex;
  flex-flow: row wrap;
  flex-direction: row;
  -webkit-flex-wrap: wrap;
  flex-wrap: wrap;
  margin: 0px -15px;
}
.card-container {
  // display: inline-table;
}
div.card-container {
  -webkit-flex: 0 1 calc(33.3333% - 30px);
  flex: 0 1 calc(33.3333% - 30px);
  margin: 15px;
}
.card-container {
  background:green;
}

<div class="flexrow">
  <div class="card-container">
      <div class="card">
        <p class="title">
          test test test
        </p>
      </div>
    </div>

    <div class="card-container">
      <div class="card">
        <p class="title">
          test testtesttest test test test
        </p>
      </div>
    </div>

    <div class="card-container">
      <div class="card">
        <p class="title">
          test test
        </p>
      </div>
    </div>
</div>


问:
How to insert a blank value instead of NULL in Columns other than String datatype in hive
I have a create statement like

CREATE TABLE temp_tbl (EmpId String,Salary int);

I would like to insert an employee id and a blank value into table.

So What I have done is

insert overwrite table temp_tbl select '013' as EmpId,'' as Salary from tbl;

```<code>hive> select * from temp_tbl;
OK
013     NULL
</code>```

But expected result is

```<code>hive> select * from temp_tbl;
OK
013     NULL ---> Blank instead of NULL
</code>```

Also tried with "". Still I get it as NULL instead of blank

3.Tried to create table with serialization property

```<code>CREATE TABLE temp_tbl (EmpId String,Salary int) TBLPROPERTIES ('serialization.null.format' = '');
</code>```

That too didn't change NULL value to blank.

What can be the workaround for the same.

答:
Knowing that datatype Int can be either NULL or integer , I'd think of how to work around the problem.

I have the impression that 0 can do the job. Why can it not?

If 1 is not ideal, why not create a new temp_employees_with_no_salary table?

If 2 is not ideal, can you afford to change the datatype of temp_tbl.Salary from Int to String, then use CAST(Salary AS INT) to work with it?

Body:
I have a create statement like

CREATE TABLE temp_tbl (EmpId String,Salary int);

I would like to insert an employee id and a blank value into table.

So What I have done is

insert overwrite table temp_tbl select '013' as EmpId,'' as Salary from tbl;

hive> select * from temp_tbl;
OK
013     NULL

But expected result is

hive> select * from temp_tbl;
OK
013     NULL ---> Blank instead of NULL

Also tried with "". Still I get it as NULL instead of blank

3.Tried to create table with serialization property

CREATE TABLE temp_tbl (EmpId String,Salary int) TBLPROPERTIES ('serialization.null.format' = '');

That too didn't change NULL value to blank.

What can be the workaround for the same.