问:
looping in a doubly linked list
how to find a loop in a doubly linked list??how to eliminate the loops?</p>

答:
Looking at the previous answer and comment to this problem, I see that they use the same approach that is used for detecting the loop in a singly-linked-list. But, there is a better way to solve this for a doubly linked-list.

Here is my approach-

Detecting the Loop

In a Doubly linked-list ,while iterating we maintain a node - "last" representing the last visited node just before the current one. If there is a loop at any node then for that node the "previous" pointer( pointer to the previous node) will not same as "last" node.

On the other hand if there is no loop we will reach the end.

Removing the Loop

We simply update the 'next' of "last" to point to nothing ( NULL in C++).

Here is my C++ implementation:

```<code>#include <iostream>
using namespace std;
struct node{
    int val;
    node *next=NULL,*prev=NULL;
    node(int x):val(x){}
};
bool detectAndRemoveLoopInDLL(node* head){
    node* last = NULL;
    while(head){
        if(last && last!=head->prev){
            cout<<"Loop found at: "<<head->val<<endl;
            last->next = NULL;
            return true;
        }
        last = head;
        head = head->next;
    }
    cout<<"No loop found"<<endl;
    return false;
}
int main() {
    node* head = new node(1);
    head->next = new node(2);
    head->next->next = new node(3); head->next->prev = head;
    head->next->next->next = new node(4); head->next->next->prev = head->next;
    head->next->next->next->next = new node(5); head->next->next->next->prev = head->next->next;
    head->next->next->next->next->next = new node(6); head->next->next->next->next->prev = head->next->next->next;
    head->next->next->next->next->next->next = new node(7); head->next->next->next->next->next->prev = head->next->next->next->next;
    head->next->next->next->next->next->next->next = new node(8); head->next->next->next->next->next->next->prev = head->next->next->next->next->next;
    //comment this for no loop
    head->next->next->next->next->next->next->next->next = head->next->next;
    head->next->next->next->next->next->next->next->prev = head->next->next->next->next->next->next;
    detectAndRemoveLoopInDLL(head);
    return 0;
}
</code>```

Title: looping in a doubly linked list

Body:
Looking at the previous answer and comment to this problem, I see that they use the same approach that is used for detecting the loop in a singly-linked-list. But, there is a better way to solve this for a doubly linked-list.

Here is my approach-

Detecting the Loop

In a Doubly linked-list ,while iterating we maintain a node - "last" representing the last visited node just before the current one. If there is a loop at any node then for that node the "previous" pointer( pointer to the previous node) will not same as "last" node.

On the other hand if there is no loop we will reach the end.

Removing the Loop

We simply update the 'next' of "last" to point to nothing ( NULL in C++).

Here is my C++ implementation:

#include <iostream>
using namespace std;
struct node{
    int val;
    node *next=NULL,*prev=NULL;
    node(int x):val(x){}
};
bool detectAndRemoveLoopInDLL(node* head){
    node* last = NULL;
    while(head){
        if(last && last!=head->prev){
            cout<<"Loop found at: "<<head->val<<endl;
            last->next = NULL;
            return true;
        }
        last = head;
        head = head->next;
    }
    cout<<"No loop found"<<endl;
    return false;
}
int main() {
    node* head = new node(1);
    head->next = new node(2);
    head->next->next = new node(3); head->next->prev = head;
    head->next->next->next = new node(4); head->next->next->prev = head->next;
    head->next->next->next->next = new node(5); head->next->next->next->prev = head->next->next;
    head->next->next->next->next->next = new node(6); head->next->next->next->next->prev = head->next->next->next;
    head->next->next->next->next->next->next = new node(7); head->next->next->next->next->next->prev = head->next->next->next->next;
    head->next->next->next->next->next->next->next = new node(8); head->next->next->next->next->next->next->prev = head->next->next->next->next->next;
    //comment this for no loop
    head->next->next->next->next->next->next->next->next = head->next->next;
    head->next->next->next->next->next->next->next->prev = head->next->next->next->next->next->next;
    detectAndRemoveLoopInDLL(head);
    return 0;
}


来源: stackexchange

问:
Dissecting Number Ranges
I'm trying to figure out the most efficient way to generate a WHERE query. I asked another question earlier, which was similar, but I will get right to the point on this one.

Given a collection of number ranges, ie 1-1000, 1500-1600 it is quite simple to create a mysql where condition to select records which are between these values.

ie, you would just do:

WHERE (lft BETWEEN 1 and 1000) OR (lft BETWEEN 1500-1600). However, what if you wanted to incorporate a NOT BETWEEN as well.

For example, if you define several rules, like...

ALLOW BETWEEN 1 - 1000

ALLOW BETWEEN 1500 - 1600

ALLOW BETWEEN 1250 - 1300

DENY BETWEEN 25 - 50

How can I merge these rules in order to efficiently generate a WHERE condition.
I would like the WHERE to dissect the ALLOW BETWEEN 1 - 1000 in order to create a gap in it. So that it would become 1-24 and 51-1000. Because the DENY rule is defined after the first rule, it "overwrites" the previous rules.

As another example,
Say that you have

ALLOW BETWEEN 5 - 15

DENY BETWEEN 10 - 50

ALLOW BETWEEN 45 - 60

Then I would like to generate a WHERE condition which would allow me to do:

WHERE (lft BETWEEN 5 and 9) OR (lft BETWEEN 45 and 60).

Notes (Edits)

Also, the maximum range that would ever allowed is 1 - 5600000. (Which would be 'Earth') ie. Allow everything on Earth.

The number ranges are actually the LEFT values in a NESTED SET MODEL. These aren't unique keys.
You can read why I want to do this in this question I asked earlier.
https://stackoverflow.com/questions/6020553/generating-a-mysql-between-where-condition-based-on-an-access-ruleset

Possible important note on my number ranges I maybe shouldn't have used the sample example which I did, but one important note about the nature of the number ranges is that, the ranges should actually always entirely consume or be consumed by a previous rule. For example, I used the example above, 10-50 allow, and deny 45-60. This wouldn't actually ever happen in my data set. It would actually be, allow 10-50, then the DENY would have to either be entirely consumed by that range, ie, 34-38. OR, entirely consume the previous rule. 9-51. This is because the ranges actually represent lft and rgt values in a nested set model and you cannot have overlaps like I presented.

I didn't think to mention that when asking the question, but after seeing the working sample code below, I can see that this note is actually important.

(Edited example mysql to include OR instead of AND as per comment below)

答:
I asked on IRC and received two responses. I'm going to post them both so that other people might benefit (and so that I don't lose them since I will take a look in detail at them both shortly).

Example 1 TML

```<code>```<?php

$cond = array(
    array('a', 5, 15),
    array('a', 5, 15),
    array('d', 9, 50),
    array('a', 45, 60),
    array('a', 2, 70),
    array('d', 1, 150),
);

function buildAcl($set) {
    $allow = array();
    foreach($set as $acl) {
        $range = range($acl[1], $acl[2]);
        switch($acl[0]) {
            case 'a':
                $allow = array_unique(array_merge(array_values($allow), $range));
                break;
            case 'd':
                foreach($range as $entry) {
                    unset($allow[array_search($entry, $allow)]);
                }
        }
    }
    return $allow;
}

var_dump(buildAcl($cond));
var_dump(buildAcl(array(array('a', 5, 15), array('d', 10, 50), array('a', 45, 60))));
```

<h1>Example 2 (matslin)</h1>

```<?php
$conds = array(
    array('a', 5, 15),
    array('a', 5, 15),
    array('d', 9, 50),
    array('a', 45, 60),
    array('a', 2, 70),
    array('d', 1, 150),
);

$segments = array();

foreach($conds as $cond)
{
    print($cond[0] . ': ' . $cond[1] . ' - ' . $cond[2] . "\n");
    if ($cond[0] == 'a')
    {
        $new_segments = array();
        $inserted = false;
        $prev_segment = false;

        foreach($segments as $segment)
        {
            if ($segment['begin'] > $cond[2])
            {
                $new_segments[] = array('begin' => $cond[1], 'end' => $cond[2]);
                $new_segments[] = $segment;
                $inserted = true;
                print("begun\n");
                continue;
            }

            if ($segment['end'] < $cond[1])
            {
                print("end\n");
                $new_segments[] = $segment;
                continue;
            }

            if ($cond[1] < $segment['begin'])
            {
                $segment['begin'] = $cond[1];
            }

            if ($cond[2] > $segment['end'])
            {
                $segment['end'] = $cond[2];
            }

            $inserted = true;

            if (
                $prev_segment &&
                ($prev_segment['begin'] <= $segment['begin']) &&
                ($prev_segment['end'] >= $segment['end'])
            )
            {
                print("ignore identical\n");
                continue;
            }

            print("default\n");
            $prev_segment = $segment;
            $new_segments[] = $segment;
        }

        if (!$inserted)
        {
            print("inserted at end\n");
            $new_segments[] = array('begin' => $cond[1], 'end' => $cond[2]);
        }

        $segments = $new_segments;
        print("---\n");
    }

    if ($cond[0] == 'd')
    {
        $new_segments = array();

        foreach($segments as $segment)
        {
            # not contained in segment
            if ($segment['begin'] > $cond[2])
            {
                print("delete segment is in front\n");
                $new_segments[] = $segment;
                continue;
            }

            if ($segment['end'] < $cond[1])
            {
                print("delete segment is behind\n");
                $new_segments[] = $segment;
                continue;
            }

            # delete whole segment
            if (
                ($segment['begin'] >= $cond[1]) &&
                ($segment['end'] <= $cond[2])
            )
            {
                print("delete whole segment\n");
                continue;
            }

            # delete starts at boundary
            if ($cond[1] <= $segment['begin'])
            {
                print("delete at boundary start\n");
                $segment['begin'] = $cond[2];
                $new_segments[] = $segment;
                continue;
            }
            # delete ends at boundary
            if ($cond[2] >= $segment['end'])
            {
                print("delete at boundary end\n");
                $segment['end'] = $cond[1];
                $new_segments[] = $segment;
                continue;
            }

            # split into two segments
            print("split into two\n");
            $segment_pre = array('begin' => $segment['begin'], 'end' => $cond[1]);
            $segment_post = array('begin' => $cond[2], 'end' => $segment['end']);

            $new_segments[] = $segment_pre;
            $new_segments[] = $segment_post;
        }

        print("--\n");
        $segments = $new_segments;
    }

    print("----\n");
    var_dump($segments);
    print("----\n");
}

var_dump($segments);
```

ContentLicense: CC BY-SA 3.0

Title: Dissecting Number Ranges

Body:
I asked on IRC and received two responses. I'm going to post them both so that other people might benefit (and so that I don't lose them since I will take a look in detail at them both shortly).

Example 1 TML

<pre><?php

$cond = array(
    array('a', 5, 15),
    array('a', 5, 15),
    array('d', 9, 50),
    array('a', 45, 60),
    array('a', 2, 70),
    array('d', 1, 150),
);

function buildAcl($set) {
    $allow = array();
    foreach($set as $acl) {
        $range = range($acl[1], $acl[2]);
        switch($acl[0]) {
            case 'a':
                $allow = array_unique(array_merge(array_values($allow), $range));
                break;
            case 'd':
                foreach($range as $entry) {
                    unset($allow[array_search($entry, $allow)]);
                }
        }
    }
    return $allow;
}

var_dump(buildAcl($cond));
var_dump(buildAcl(array(array('a', 5, 15), array('d', 10, 50), array('a', 45, 60))));

Example 2 (matslin)

<?php
$conds = array(
    array('a', 5, 15),
    array('a', 5, 15),
    array('d', 9, 50),
    array('a', 45, 60),
    array('a', 2, 70),
    array('d', 1, 150),
);

$segments = array();

foreach($conds as $cond)
{
    print($cond[0] . ': ' . $cond[1] . ' - ' . $cond[2] . "\n");
    if ($cond[0] == 'a')
    {
        $new_segments = array();
        $inserted = false;
        $prev_segment = false;

        foreach($segments as $segment)
        {
            if ($segment['begin'] > $cond[2])
            {
                $new_segments[] = array('begin' => $cond[1], 'end' => $cond[2]);
                $new_segments[] = $segment;
                $inserted = true;
                print("begun\n");
                continue;
            }

            if ($segment['end'] < $cond[1])
            {
                print("end\n");
                $new_segments[] = $segment;
                continue;
            }

            if ($cond[1] < $segment['begin'])
            {
                $segment['begin'] = $cond[1];
            }

            if ($cond[2] > $segment['end'])
            {
                $segment['end'] = $cond[2];
            }

            $inserted = true;

            if (
                $prev_segment &&
                ($prev_segment['begin'] <= $segment['begin']) &&
                ($prev_segment['end'] >= $segment['end'])
            )
            {
                print("ignore identical\n");
                continue;
            }

            print("default\n");
            $prev_segment = $segment;
            $new_segments[] = $segment;
        }

        if (!$inserted)
        {
            print("inserted at end\n");
            $new_segments[] = array('begin' => $cond[1], 'end' => $cond[2]);
        }

        $segments = $new_segments;
        print("---\n");
    }

    if ($cond[0] == 'd')
    {
        $new_segments = array();

        foreach($segments as $segment)
        {
            # not contained in segment
            if ($segment['begin'] > $cond[2])
            {
                print("delete segment is in front\n");
                $new_segments[] = $segment;
                continue;
            }

            if ($segment['end'] < $cond[1])
            {
                print("delete segment is behind\n");
                $new_segments[] = $segment;
                continue;
            }

            # delete whole segment
            if (
                ($segment['begin'] >= $cond[1]) &&
                ($segment['end'] <= $cond[2])
            )
            {
                print("delete whole segment\n");
                continue;
            }

            # delete starts at boundary
            if ($cond[1] <= $segment['begin'])
            {
                print("delete at boundary start\n");
                $segment['begin'] = $cond[2];
                $new_segments[] = $segment;
                continue;
            }
            # delete ends at boundary
            if ($cond[2] >= $segment['end'])
            {
                print("delete at boundary end\n");
                $segment['end'] = $cond[1];
                $new_segments[] = $segment;
                continue;
            }

            # split into two segments
            print("split into two\n");
            $segment_pre = array('begin' => $segment['begin'], 'end' => $cond[1]);
            $segment_post = array('begin' => $cond[2], 'end' => $segment['end']);

            $new_segments[] = $segment_pre;
            $new_segments[] = $segment_post;
        }

        print("--\n");
        $segments = $new_segments;
    }

    print("----\n");
    var_dump($segments);
    print("----\n");
}

var_dump($segments);


问:
Azure DevOps Build Pipeline: How can I increment the assembly version only for the changed assemblies?
I have a build pipeline in Azure DevOps and I would like to increment the version of my assemblies with each change in the project. In the current build definition the version of the assemblies will increase with each build for all projects/assemblies.

So when I merge the dev branch to the main branch (reverse integration) the trigger runs a build on an agent and it will increase the version number for all projects in the main branch.

Project Types

The project types are .NET Framework, .NET Core, .NET Standard

Is there a way to increase the version number for the changed projects/assemblies only?

答:
Unfortunately, there is no default way to increase the assembly version only for the changed project. You could try @MartinSGill's workaround, for the situation that need to version independently you could give them their own builds. Then have a separate pipeline that collects them all into a single "release".

Here is an useful extension for your reference:

https://marketplace.visualstudio.com/items?itemName=bleddynrichards.Assembly-Info-Task

ContentLicense: CC BY-SA 4.0


问:
Numpy Array of tensorflow.keras.preprocessing.text.Tokenizer.texts_to_sequences is giving weird output, list([2]) instead of [[2]]
Numpy Array of tensorflow.keras.preprocessing.text.Tokenizer.texts_to_sequences is giving weird output for Training Labels as shown below:

```<code>(training_label_list[0:10]) = [list([1]) list([1]) list([1]) list([1]) list([1]) list([1]) list([1]) list([1]) list([1]) list([1])]
</code>```

but is printing Normal Array for the Validation Labels,

```<code>(validation_label_list[0:10]) = [[16]
 [16]
 [16]
 [16]
 [16]
 [16]
 [16]
 [16]
 [16]
 [16]]
</code>```

In other words, type(training_label_list[0]) =  <class 'list'> but

```<code>type(validation_label_list[0]) =  <class 'numpy.ndarray'>
</code>```

Consequently, while Training the Model using Keras Model.fit, it is resulting in the below Error,

```<code>ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type list).
</code>```

This is the Link of the Google Colab, to reproduce the error easily.

Complete Code to reproduce the Error is given below:

```<code>!pip install tensorflow==2.1

# For Preprocessing the Text => To Tokenize the Text
from tensorflow.keras.preprocessing.text import Tokenizer
# If the Two Articles are of different length, pad_sequences will make the length equal
from tensorflow.keras.preprocessing.sequence import pad_sequences

# Package for performing Numerical Operations
import numpy as np

Unique_Labels_List = ['India', 'USA', 'Australia', 'Germany', 'Bhutan', 'Nepal', 'New Zealand', 'Israel', 'Canada', 'France', 'Ireland', 'Poland', 'Egypt', 'Greece', 'China', 'Spain', 'Mexico']

Train_Labels = Unique_Labels_List[0:14]
#print('Train Labels = {}'.format(Train_Labels))

Val_Labels =  Unique_Labels_List[14:]
#print('Val_Labels = {}'.format(Val_Labels))

No_Of_Train_Items = [248, 200, 200, 218, 248, 248, 249, 247, 220, 200, 200, 211, 224, 209]
No_Val_Items = [212, 200, 219]

T_L = []
for Each_Label, Item in zip(Train_Labels, No_Of_Train_Items):
    T_L.append([Each_Label] * Item)

T_L = [item for sublist in T_L for item in sublist]

V_L = []
for Each_Label, Item in zip(Val_Labels, No_Val_Items):
    V_L.append([Each_Label] * Item)

V_L = [item for sublist in V_L for item in sublist]

len(T_L)

len(V_L)

label_tokenizer = Tokenizer()

label_tokenizer.fit_on_texts(Unique_Labels_List)

# Since it should be a Numpy Array, we should Convert the Sequences to Numpy Array, for both Training and
# Test Labels

training_label_list = np.array(label_tokenizer.texts_to_sequences(T_L))

validation_label_list = np.array(label_tokenizer.texts_to_sequences(V_L))

print('(training_label_list[0:10]) = {}'.format((training_label_list[0:10])))
print('(validation_label_list[0:10]) = {}'.format((validation_label_list[0:10])))

print('type(training_label_list[0]) = ', type(training_label_seq[0]))
print('type(validation_label_seq[0]) = ', type(validation_label_seq[0]))
</code>```

I will be Grateful if someone can suggest me how can I get both Training Labels and Validation Labels in same Format, as I have spent so much time on it.

答:
Your problem is that, while your are converting your training data to a numpy array, that specific numpy array consists of list elements, hence the error

ValueError: Failed to convert a NumPy array to a Tensor (Unsupported
  object type list).

The error is subtler than it appears; some have reported that they had to switch back from 2.1.0 to 2.0.0. What is the difference between Numpy's array() and asarray() functions?

I would personally try this:

Use training_label_list = np.asarray(label_tokenizer.texts_to_sequences(T_L)), instead of np.array. Tensorflow - ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type float)

According to this:

List of lists into numpy array

you will have to force the casting(although weird yet this should work):

```<code>x=[[1,2],[1,2,3],[1]]
y=numpy.array([numpy.array(xi) for xi in x])
type(y)
>>><type 'numpy.ndarray'>
type(y[0])
>>><type 'numpy.ndarray'>
</code>```

While trying to help you on this issue, I discovered an interesting fact about numpy casting:

CASE 1:

```<code>   my_list = [[1,2],[2],[3]]
   my_numpy_array = np.array(my_list)
   print(type(my_numpy_array))
   print(type(my_numpy_array[0]))
   <class 'numpy.ndarray'>
   <class 'list'>
</code>```

CASE 2:

```<code>    my_list = [[1],[2],[3]]
    my_numpy_array = np.array(my_list)
    print(type(my_numpy_array))
    print(type(my_numpy_array[0]))
    <class 'numpy.ndarray'>
    <class 'numpy.ndarray'>
</code>```

Short conclusion: If the sublists lengths differ, apparently they are left as lists and not converted to numpy arrays.

I tested on your code, now it works:

```<code>training_label_seq = np.asarray(label_tokenizer.texts_to_sequences(T_L))

training_label_seq = np.array([np.array(training_element) for training_element in training_label_seq])

validation_label_seq = np.asarray(label_tokenizer.texts_to_sequences(V_L))

print('(training_label_seq[0:10]) = {}'.format((training_label_seq[0:10])))
print('(validation_label_seq[0:10]) = {}'.format((validation_label_seq[0:10])))

print('type(training_label_list[0]) = ', type(training_label_seq[0]))
print('type(validation_label_seq[0]) = ', type(validation_label_seq[0]))

(training_label_seq[0:10]) = [array([1]) array([1]) array([1]) array([1]) array([1]) array([1])
 array([1]) array([1]) array([1]) array([1])]
(validation_label_seq[0:10]) = [[16]
 [16]
 [16]
 [16]
 [16]
 [16]
 [16]
 [16]
 [16]
 [16]]
type(training_label_list[0]) =  <class 'numpy.ndarray'>
type(validation_label_seq[0]) =  <class 'numpy.ndarray'>
</code>```

Body:
Numpy Array of tensorflow.keras.preprocessing.text.Tokenizer.texts_to_sequences is giving weird output for Training Labels as shown below:

(training_label_list[0:10]) = [list([1]) list([1]) list([1]) list([1]) list([1]) list([1]) list([1]) list([1]) list([1]) list([1])]

but is printing Normal Array for the Validation Labels,

(validation_label_list[0:10]) = [[16]
 [16]
 [16]
 [16]
 [16]
 [16]
 [16]
 [16]
 [16]
 [16]]

In other words, type(training_label_list[0]) =  <class 'list'> but

type(validation_label_list[0]) =  <class 'numpy.ndarray'>

Consequently, while Training the Model using Keras Model.fit, it is resulting in the below Error,

ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type list).

This is the Link of the Google Colab, to reproduce the error easily.

Complete Code to reproduce the Error is given below:

!pip install tensorflow==2.1

# For Preprocessing the Text => To Tokenize the Text
from tensorflow.keras.preprocessing.text import Tokenizer
# If the Two Articles are of different length, pad_sequences will make the length equal
from tensorflow.keras.preprocessing.sequence import pad_sequences

# Package for performing Numerical Operations
import numpy as np

Unique_Labels_List = ['India', 'USA', 'Australia', 'Germany', 'Bhutan', 'Nepal', 'New Zealand', 'Israel', 'Canada', 'France', 'Ireland', 'Poland', 'Egypt', 'Greece', 'China', 'Spain', 'Mexico']

Train_Labels = Unique_Labels_List[0:14]
#print('Train Labels = {}'.format(Train_Labels))

Val_Labels =  Unique_Labels_List[14:]
#print('Val_Labels = {}'.format(Val_Labels))

No_Of_Train_Items = [248, 200, 200, 218, 248, 248, 249, 247, 220, 200, 200, 211, 224, 209]
No_Val_Items = [212, 200, 219]

T_L = []
for Each_Label, Item in zip(Train_Labels, No_Of_Train_Items):
    T_L.append([Each_Label] * Item)

T_L = [item for sublist in T_L for item in sublist]

V_L = []
for Each_Label, Item in zip(Val_Labels, No_Val_Items):
    V_L.append([Each_Label] * Item)

V_L = [item for sublist in V_L for item in sublist]

len(T_L)

len(V_L)

label_tokenizer = Tokenizer()

label_tokenizer.fit_on_texts(Unique_Labels_List)

# Since it should be a Numpy Array, we should Convert the Sequences to Numpy Array, for both Training and
# Test Labels

training_label_list = np.array(label_tokenizer.texts_to_sequences(T_L))

validation_label_list = np.array(label_tokenizer.texts_to_sequences(V_L))

print('(training_label_list[0:10]) = {}'.format((training_label_list[0:10])))
print('(validation_label_list[0:10]) = {}'.format((validation_label_list[0:10])))

print('type(training_label_list[0]) = ', type(training_label_seq[0]))
print('type(validation_label_seq[0]) = ', type(validation_label_seq[0]))

I will be Grateful if someone can suggest me how can I get both Training Labels and Validation Labels in same Format, as I have spent so much time on it.

Body:
Your problem is that, while your are converting your training data to a numpy array, that specific numpy array consists of list elements, hence the error

ValueError: Failed to convert a NumPy array to a Tensor (Unsupported
  object type list).

The error is subtler than it appears; some have reported that they had to switch back from 2.1.0 to 2.0.0. What is the difference between Numpy's array() and asarray() functions?

I would personally try this:

Use training_label_list = np.asarray(label_tokenizer.texts_to_sequences(T_L)), instead of np.array. Tensorflow - ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type float)

According to this:

List of lists into numpy array

you will have to force the casting(although weird yet this should work):

x=[[1,2],[1,2,3],[1]]
y=numpy.array([numpy.array(xi) for xi in x])
type(y)
>>><type 'numpy.ndarray'>
type(y[0])
>>><type 'numpy.ndarray'>

While trying to help you on this issue, I discovered an interesting fact about numpy casting:

CASE 1:

   my_list = [[1,2],[2],[3]]
   my_numpy_array = np.array(my_list)
   print(type(my_numpy_array))
   print(type(my_numpy_array[0]))
   <class 'numpy.ndarray'>
   <class 'list'>

CASE 2:

    my_list = [[1],[2],[3]]
    my_numpy_array = np.array(my_list)
    print(type(my_numpy_array))
    print(type(my_numpy_array[0]))
    <class 'numpy.ndarray'>
    <class 'numpy.ndarray'>

Short conclusion: If the sublists lengths differ, apparently they are left as lists and not converted to numpy arrays.

I tested on your code, now it works:

training_label_seq = np.asarray(label_tokenizer.texts_to_sequences(T_L))

training_label_seq = np.array([np.array(training_element) for training_element in training_label_seq])

validation_label_seq = np.asarray(label_tokenizer.texts_to_sequences(V_L))

print('(training_label_seq[0:10]) = {}'.format((training_label_seq[0:10])))
print('(validation_label_seq[0:10]) = {}'.format((validation_label_seq[0:10])))

print('type(training_label_list[0]) = ', type(training_label_seq[0]))
print('type(validation_label_seq[0]) = ', type(validation_label_seq[0]))

(training_label_seq[0:10]) = [array([1]) array([1]) array([1]) array([1]) array([1]) array([1])
 array([1]) array([1]) array([1]) array([1])]
(validation_label_seq[0:10]) = [[16]
 [16]
 [16]
 [16]
 [16]
 [16]
 [16]
 [16]
 [16]
 [16]]
type(training_label_list[0]) =  <class 'numpy.ndarray'>
type(validation_label_seq[0]) =  <class 'numpy.ndarray'>


问:
How to add corner radius for UIView
I have to set some corner radius of UIView and I set it by this code:

```<code>@IBDesignable
class MyUIviewCorner: UIView {

    override func layoutSubviews() { setup() }

    func setup() {
        let r = self.bounds.size.height / 2
        let path = UIBezierPath(roundedRect: self.bounds,
        byRoundingCorners: [.topLeft, .topRight],
        cornerRadii: CGSize(width: r, height: r))
        let mask = CAShapeLayer()
        mask.backgroundColor = UIColor.clear.cgColor
        mask.path = path.cgPath
        layer.borderWidth = 1.5
        layer.borderColor = UIColor.red.cgColor
        self.layer.mask = mask
    }
}
</code>```

But I get this result:

I don't understand why is there white spaces on the top corners?

If I set bottom corner radius I get this:

答:
You shouldn't use a mask for this, you can simply use the layer.maskedCorners property.

```<code>layer.cornerRadius = r
layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
</code>```

Title: How to add corner radius for UIView

Body:
I have to set some corner radius of UIView and I set it by this code:

@IBDesignable
class MyUIviewCorner: UIView {

    override func layoutSubviews() { setup() }

    func setup() {
        let r = self.bounds.size.height / 2
        let path = UIBezierPath(roundedRect: self.bounds,
        byRoundingCorners: [.topLeft, .topRight],
        cornerRadii: CGSize(width: r, height: r))
        let mask = CAShapeLayer()
        mask.backgroundColor = UIColor.clear.cgColor
        mask.path = path.cgPath
        layer.borderWidth = 1.5
        layer.borderColor = UIColor.red.cgColor
        self.layer.mask = mask
    }
}

But I get this result:

I don't understand why is there white spaces on the top corners?

If I set bottom corner radius I get this:

Body:
You shouldn't use a mask for this, you can simply use the layer.maskedCorners property.

layer.cornerRadius = r
layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]


问:
ReactJS: onClick function executes before clicking button
The function SendCred() executes the page is loading, but I want this to be called when the user clicks the <button>. What should I do?

```<code> import React,{useState} from "react";

    export default function Signup(props){

      const sendCred=()=>{
        console.log("test")
      };

      return (
        <div className="row container">
          <button onClick={sendCred()}> Activate Laser </button>
        </div>
      );

    };
</code>```

答:
You just shouldn't call that function, just pass it directly to onClick listener

```<code> import React,{useState} from "react";

    export default function Signup(props){

      const sendCred=()=>{
        console.log("test")
      };

      return (
        <div className="row container">
          <button onClick={sendCred}> Activate Laser </button>
        </div>
      );

    };
</code>```

It can also be memoized with useCallback hook functionality(docs)

```<code>import React,{useState} from "react";

   export default function Signup(props){

     const sendCred = useCallback(() => {
       console.log("test")
     });

     return (
       <div className="row container">
         <button onClick={sendCred}> Activate Laser </button>
       </div>
     );

   };
</code>```

:)

Body:
The function SendCred() executes the page is loading, but I want this to be called when the user clicks the <button>. What should I do?

 import React,{useState} from "react";

    export default function Signup(props){

      const sendCred=()=>{
        console.log("test")
      };

      return (

          <button onClick={sendCred()}> Activate Laser </button>

      );

    };

Body:
You just shouldn't call that function, just pass it directly to onClick listener

 import React,{useState} from "react";

    export default function Signup(props){

      const sendCred=()=>{
        console.log("test")
      };

      return (
        <div className="row container">
          <button onClick={sendCred}> Activate Laser </button>
        </div>
      );

    };

It can also be memoized with useCallback hook functionality(docs)

import React,{useState} from "react";

   export default function Signup(props){

     const sendCred = useCallback(() => {
       console.log("test")
     });

     return (
       <div className="row container">
         <button onClick={sendCred}> Activate Laser </button>
       </div>
     );

   };

:)


问:
using python variable in django sql query
```<code>    @staticmethod
    def getdata(backdays):
        cursor = connections['MMY'].cursor()
        query ="Select * from temp WHERE DAY_OF_MONTH=TO_CHAR(sysdate-?,'DD')"
        cursor.execute(query,(backdays))
        rdict = namedtuplefetchall(cursor)
        return rdict
</code>```

<p>i am getting attribute error , I can see this value is getting printed when i am using print but above is failing can any one please help . it is python . Value is being passed using  axios in javascript . </p>

答: If you are doing this in the Django framework then , according to me instead of firing query in a model file, you go for using the "for loop iterations" in views.py file. </p>

Body:
    @staticmethod
    def getdata(backdays):
        cursor = connections['MMY'].cursor()
        query ="Select * from temp WHERE DAY_OF_MONTH=TO_CHAR(sysdate-?,'DD')"
        cursor.execute(query,(backdays))
        rdict = namedtuplefetchall(cursor)
        return rdict

i am getting attribute error , I can see this value is getting printed when i am using print but above is failing can any one please help . it is python . Value is being passed using  axios in javascript .


问:
ReferenceError: Jdbc is not defined, a V8 version problem?
My code has been working daily for 6 months and it appears it doesn't work anymore. I know Google App Script Runtime did an update to V8 https://developers.google.com/apps-script/guides/v8-runtime (message displayed when I open "Script editor"). I suspect the problem comes from this version change because nothing else has changed.

I use Jdbc to access an SQL database at the beginning of the code:

```<code>  var connectionName = '';
  var user = '';
  var userPwd = '';
  var db = '';
  var dbUrl = 'jdbc:mysql://'+connectionName+'/'+db;
  var conn = Jdbc.getConnection(dbUrl, user, userPwd);
</code>```

The error message I get is "ReferenceError: Jdbc is not defined", and I don't know how to fix it.

Could someone have a solution please?

答: This is a known issue with v8 and Google has acknowledged the bug. You may follow the issue tracker for updates.</p>

Body:
My code has been working daily for 6 months and it appears it doesn't work anymore. I know Google App Script Runtime did an update to V8 https://developers.google.com/apps-script/guides/v8-runtime (message displayed when I open "Script editor"). I suspect the problem comes from this version change because nothing else has changed.

I use Jdbc to access an SQL database at the beginning of the code:

  var connectionName = '';
  var user = '';
  var userPwd = '';
  var db = '';
  var dbUrl = 'jdbc:mysql://'+connectionName+'/'+db;
  var conn = Jdbc.getConnection(dbUrl, user, userPwd);

The error message I get is "ReferenceError: Jdbc is not defined", and I don't know how to fix it.

Could someone have a solution please?


问:
ETL batch processing
I'm looking for some open source technology that will allow me to create scheduled batch processing (e.g. Query every 1 hour some SQL DB like Oracle, and insert to Kafka. It is possible that some transformation will be done to the data between). The thing is that I need to be able to transport large amount of data ("big data" - Oracle queries could return 10GB or more).

I read about Apache Airflow for example, but it does not seem to fit for large amount of data.

What other technologies can I use for that purpose?

答:
You should see all of Apache Big Data projects and the Oracle GoldenGate for BigData.
The problem is being solved by the Apache with a solution combination of Big Data tools.

And You could use the Spring Framework: Spring Batch for open source solutions.

Title: ETL batch processing


问:
How do I highlight text linked to from a separate webpage?
I have a web-page with anchor tags that are linked to specific words in another page that contain only the words.

Every single word in the words page is wrapped with an  anchor tag having a unique ID like this:

```<code><a id="a">Капитанская</a>
<a id="b">дочкаБереги</a>
<a id="c">Капитанская</a>
<a id="d">дочкаБереги</a>
</code>```

And in the web-page there are links to those words that look like this:

```<code><a href="website.com/text-page.html#a">Капитанская</a>
<a href="website.com/text-page.html#b">дочкаБереги</a>
</code>```

I need to find a way to highlight the word I'm linking to with a colored background or something like that.

I'm using JavaScript, HTML, CSS and PHP for both the webpages, and don't have the ability to use anything else.

答:
On your text page, you can just retrieve the id from your url using the hash property from the window.location read-only property and assign a background color to the text element that has that id like this:

//get the id from the URL
const link = window.location.hash.split('#')[1];

//add a class to the element that has that id
document.getElementById(link).classList.add('highlighted');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.highlighted {
  background-color: green; //add background color to that element
}</code>```

word1
word2
word3
word4
word5
word6
word7
word8```

Body:
I have a web-page with anchor tags that are linked to specific words in another page that contain only the words.

Every single word in the words page is wrapped with an  anchor tag having a unique ID like this:

Капитанская
дочкаБереги
Капитанская
дочкаБереги

And in the web-page there are links to those words that look like this:

Капитанская
дочкаБереги

I need to find a way to highlight the word I'm linking to with a colored background or something like that.

I'm using JavaScript, HTML, CSS and PHP for both the webpages, and don't have the ability to use anything else.

Body:
On your text page, you can just retrieve the id from your url using the hash property from the window.location read-only property and assign a background color to the text element that has that id like this:

//get the id from the URL
const link = window.location.hash.split('#')[1];

//add a class to the element that has that id
document.getElementById(link).classList.add('highlighted');

.highlighted {
  background-color: green; //add background color to that element
}

<a id="word1">word1</a>
<a id="word2">word2</a>
<a id="word3">word3</a>
<a id="word4">word4</a>
<a id="word5">word5</a>
<a id="word6">word6</a>
<a id="word7">word7</a>
<a id="word8">word8</a>


问:
How can I run a Svelte/Sapper app over HTTPS/SSL?
I can't seem to find anything about running Svelte apps over https. I would like to run on https for both dev and prod. I am able to change the port with --port argument in the scripts in package.json, but obviously that doesn't change the protocol from http to https.

答: This has noting to do with sapper. Just use the options of your server framework. Do you use express or polka? Follow their instructions!</p>


问:
PHP Fatal error: Allowed memory size of 2097152 bytes exhausted (tried to allocate 12288 bytes)
I know this is a repeated question, but I couldn't find a solution after trying all the answers discussed here.

When I run php bin/magento setup:upgrade command, it shows error like

PHP Fatal error:  Allowed memory size of 2097152 bytes exhausted (tried to allocate 12288 bytes) in /var/www/html/mysite/vendor/paragonie/sodium_compat/lib/sodium_compat.php on line 214

Modified memory_limit value in php.ini file, but still issue exists. Any other solutions for this problem?

答:
The simplest way to do this, without the need to change your config is to specify the memory limit when you run the command.</p>

```<code>php -dmemory_limit=-1 bin/magento setup:upgrade
</code>```

Body:
The simplest way to do this, without the need to change your config is to specify the memory limit when you run the command.

php -dmemory_limit=-1 bin/magento setup:upgrade


问:
Java wildcard strange behaviour when class is generic
I thought that i have some good understanding of Java generics.

This code DOES NOT COMPILE and I know why.

We can pass to test method only List of type Animal or its super type (like List of Objects)

```<code>package scjp.examples.generics.wildcards;

import java.util.ArrayList;
import java.util.List;

class Animal {}
class Mammal extends Animal {}
class Dog extends Mammal {}

public class Test {

    public void test(List<? super Animal> col) {
        col.add(new Animal());
        col.add(new Mammal());
        col.add(new Dog());
    }

    public static void main(String[] args) {
        List<Animal> animalList = new ArrayList<Animal>();
        List<Mammal> mammalList = new ArrayList<Mammal>();
        List<Dog> dogList = new ArrayList<Dog>();

        new Test().test(animalList);
        new Test().test(mammalList); // Error: The method test(List<? super Animal>) in the type Test is not applicable for the arguments (List<Mammal>)
        new Test().test(dogList);    // Error: The method test(List<? super Animal>) in the type Test is not applicable for the arguments (List<Dog>)

        Dog dog = dogList.get(0);
    }
}
</code>```

But here comes the strange part (at least for me).

If we declare class Test as generic by only adding <T>, then it COMPILES! and throws java.lang.ClassCastException:

```<code>public class Test<T> {
...
}
</code>```

,

```<code>Exception in thread "main" java.lang.ClassCastException: scjp.examples.generics.wildcards.Animal cannot be cast to scjp.examples.generics.wildcards.Dog
</code>```

My question is why adding generic class type <T> (which is not used anywhere) caused class to compile and changed wildcard behaviour?

答:
You have parameterized the type by adding:

```<code>public class Test<T> {
</code>```

But then you use it as the raw type by doing:

```<code>new Test()
</code>```

So all bets are off now.  To enable interoperability with legacy code the compiler is letting it through, but it's not type checking now. It will generate a compiler warning though.

Body:
I thought that i have some good understanding of Java generics.

This code DOES NOT COMPILE and I know why.

We can pass to test method only List of type Animal or its super type (like List of Objects)

package scjp.examples.generics.wildcards;

import java.util.ArrayList;
import java.util.List;

class Animal {}
class Mammal extends Animal {}
class Dog extends Mammal {}

public class Test {

    public void test(List<? super Animal> col) {
        col.add(new Animal());
        col.add(new Mammal());
        col.add(new Dog());
    }

    public static void main(String[] args) {
        List<Animal> animalList = new ArrayList<Animal>();
        List<Mammal> mammalList = new ArrayList<Mammal>();
        List<Dog> dogList = new ArrayList<Dog>();

        new Test().test(animalList);
        new Test().test(mammalList); // Error: The method test(List<? super Animal>) in the type Test is not applicable for the arguments (List<Mammal>)
        new Test().test(dogList);    // Error: The method test(List<? super Animal>) in the type Test is not applicable for the arguments (List<Dog>)

        Dog dog = dogList.get(0);
    }
}

But here comes the strange part (at least for me).

If we declare class Test as generic by only adding <T>, then it COMPILES! and throws java.lang.ClassCastException:

public class Test<T> {
...
}

,

Exception in thread "main" java.lang.ClassCastException: scjp.examples.generics.wildcards.Animal cannot be cast to scjp.examples.generics.wildcards.Dog

My question is why adding generic class type <T> (which is not used anywhere) caused class to compile and changed wildcard behaviour?

Body:
You have parameterized the type by adding:

public class Test<T> {

But then you use it as the raw type by doing:

new Test()

So all bets are off now.  To enable interoperability with legacy code the compiler is letting it through, but it's not type checking now. It will generate a compiler warning though.


答:
The sendCred function is being called directly, when the result of your functional component is being evaluated and returned:

```<code>{/* The sendCred() function is being evaluated during render, and the
    result of sendCred is being passed to the onClick prop */
<button onClick={sendCred()}> Activate Laser </button>
</code>```

To achieve the desired behavior, consider specifying the value passed to onClick as a callback function that wraps a call to sendCred() (ie an arrow function as shown below). By doing this, the arrow function will be passed to onClick and, when a user click invokes onClick, the supplied arrow function will be called which will in turn cause sendCred() to be called:

```<code>export default function Signup(props){

  const sendCred=()=>{
    console.log("test")
  };

  return (
    <div className="row container">
      {/* Wrap sendCred() with an arrow function, and pass the arrow
          function to onClick as the callback to be invoked for user
          click events on button */}
      <button onClick={ () => sendCred() }> Activate Laser </button>
    </div>
  );
};
</code>```

Alternatively, you could also just pass the sendCred function directly to onClick - the key here is to ensure that you do not include a parenthesis pair (as you currently have done), as doing so will cause sendCred to be invoked during render:

```<code>{ /* Omit the () after sendCred */ }
<button onClick={ sendCred }> Activate Laser </button>
</code>```

Title: ReactJS: onClick function executes before clicking button

Body:
The sendCred function is being called directly, when the result of your functional component is being evaluated and returned:

{/* The sendCred() function is being evaluated during render, and the
    result of sendCred is being passed to the onClick prop */
<button onClick={sendCred()}> Activate Laser </button>

To achieve the desired behavior, consider specifying the value passed to onClick as a callback function that wraps a call to sendCred() (ie an arrow function as shown below). By doing this, the arrow function will be passed to onClick and, when a user click invokes onClick, the supplied arrow function will be called which will in turn cause sendCred() to be called:

export default function Signup(props){

  const sendCred=()=>{
    console.log("test")
  };

  return (
    <div className="row container">
      {/* Wrap sendCred() with an arrow function, and pass the arrow
          function to onClick as the callback to be invoked for user
          click events on button */}
      <button onClick={ () => sendCred() }> Activate Laser </button>
    </div>
  );
};

Alternatively, you could also just pass the sendCred function directly to onClick - the key here is to ensure that you do not include a parenthesis pair (as you currently have done), as doing so will cause sendCred to be invoked during render:

{ /* Omit the () after sendCred */ }
<button onClick={ sendCred }> Activate Laser </button>


问:
How to get IAP receipt
Our dev team are developing payment functionalities. I am responsible for Apply Pay backend purchase validation. I will call App Store's verify API:verifyReceipt: https://sandbox.itunes.apple.com/verifyReceipt to verify the receipt passed from ios client. And now, ios client is not ready for developing, so i can not get a receipt to verify. So, is there any workaround to get it?

答:
There is no way to test this without sample data and as far as I know Apple doesn't provide such. Maybe you're lucky finding someone providing valid sample sandbox receipt data otherwise you’re unfortunately dependent on your iOS developer team. If they've already added IAPs maybe they can provide you receipt data manually.

Haven't tested the answers, but here is someone with a similar question on stackoverflow and some answers with receipt data.

Title: How to get IAP receipt


问:
Hiding an Excel worksheet with VBA
I have an Excel spreadsheet with three sheets. One of the sheets contains formulas for one of the other sheets.

Is there a programmatic way to hide the sheet which contains these formulas?

答:
I would like to answer your question, as there are various methods - here I’ll talk about the code that is widely used.

So, for hiding the sheet:

```<code>Sub try()
    Worksheets("Sheet1").Visible = xlSheetHidden
End Sub
</code>```

There are other methods also if you want to learn all Methods Click here

OwnerDisplayName: Lost

Title: Hiding an Excel worksheet with VBA

Body:
I would like to answer your question, as there are various methods - here I’ll talk about the code that is widely used.

So, for hiding the sheet:

Sub try()
    Worksheets("Sheet1").Visible = xlSheetHidden
End Sub

There are other methods also if you want to learn all Methods Click here


问:
how to make a new array from an existing array in php?
let's say if I have an array like this below.

```<code>$i = array(
    'arr1'  => array(
        'a11'   => 'ar11',
        'a12'   => 'ar12',
    ),
    'arr2'  => array(
        'a21'   => 'ar21',
        'a22'   => 'ar22',
        'a23'   => 'ar23',
    ),
    'arr3'  => 'arrr3',
    'arr4'  => 'arrr4'
);
</code>```

I want a new array that created from this array like the one I mentioned below,

```<code>$j = array(
    'a11'   => 'ar11',
    'a12'   => 'ar12',
    'a21'   => 'ar21',
    'a22'   => 'ar22',
    'a23'   => 'ar23',
    'arr3'  => 'arrr3',
    'arr4'  => 'arrr4'
);
</code>```

sofar I tried extracting the last two elements which aren't arrays I mention the code below

```<code>$ii = $i;
foreach($ii as $k => $v):
    if(is_array($v)):
        unset($ii[$k]);
    endif;
endforeach;
</code>```

this returns me the last two elements. but the way i tried extracting the other elements looks wired see below.

```<code>$i1 = $i['arr1'];
$i2 = $i['arr2'];
$i3 = array_merge($i1, $i2);
$final = array_merge($i3, $j);
</code>```

this looks simple because it has small amout of elemetns but i have large amount of elements in my project, any other ways to get this output?

答:
Can you try this?

```<code>$final = [];

foreach($i as $key => $value){
    if(is_array($value){
        $final = array_merge($final, $value);

    }   else{
        $final[$key] = $value;
    }
}
</code>```

Upd.

@Magnus-Eriksson insists to explain what is going on within loop. At first we check if value is an array or not. If value is an array we merge  nested array with (new, created before loop starts) array where we putting our elements. If value isn't array we just get that value and add it to the final array. There is no magic here. But answer with array_walk_recursive() below is much more elegant but with "magic" within.

Body:
let's say if I have an array like this below.

$i = array(
    'arr1'  => array(
        'a11'   => 'ar11',
        'a12'   => 'ar12',
    ),
    'arr2'  => array(
        'a21'   => 'ar21',
        'a22'   => 'ar22',
        'a23'   => 'ar23',
    ),
    'arr3'  => 'arrr3',
    'arr4'  => 'arrr4'
);

I want a new array that created from this array like the one I mentioned below,

$j = array(
    'a11'   => 'ar11',
    'a12'   => 'ar12',
    'a21'   => 'ar21',
    'a22'   => 'ar22',
    'a23'   => 'ar23',
    'arr3'  => 'arrr3',
    'arr4'  => 'arrr4'
);

sofar I tried extracting the last two elements which aren't arrays I mention the code below

$ii = $i;
foreach($ii as $k => $v):
    if(is_array($v)):
        unset($ii[$k]);
    endif;
endforeach;

this returns me the last two elements. but the way i tried extracting the other elements looks wired see below.

$i1 = $i['arr1'];
$i2 = $i['arr2'];
$i3 = array_merge($i1, $i2);
$final = array_merge($i3, $j);

this looks simple because it has small amout of elemetns but i have large amount of elements in my project, any other ways to get this output?

Body:
Can you try this?

$final = [];

foreach($i as $key => $value){
    if(is_array($value){
        $final = array_merge($final, $value);

    }   else{
        $final[$key] = $value;
    }
}

Upd.

@Magnus-Eriksson insists to explain what is going on within loop. At first we check if value is an array or not. If value is an array we merge  nested array with (new, created before loop starts) array where we putting our elements. If value isn't array we just get that value and add it to the final array. There is no magic here. But answer with array_walk_recursive() below is much more elegant but with "magic" within.


问:
R Shiny - Build a tabsetPanel from a list from selectizeInput
I have been trying to develop this tabsetpanel for a while but without success. The goal is to assemble the tabs dynamically. After the user click the search button, the tabs will be assembled from the user's selection in selectizeInput. Each tab will have a specific content. When the user presses the search button again, the tabs must be built again with the information from selectizeInput without duplication.

I appreciate any help.

the result should be like this image:

```<code>library(shiny)

ui <- fluidPage(
    title = "Examples of DataTables",
    sidebarLayout(
        sidebarPanel(

            selectizeInput(
                'state', 'State', choices = state.name, multiple = TRUE
            ),
            actionButton("search", "Search"),

        ),
        mainPanel(
            tabsetPanel(
                id = 'dataset',
                tabPanel("tab1", verbatimTextOutput("tab1"))
            )

        )
    )
)

server <- function(input, output) {

    output$tab1 <- renderPrint({
        "tab1"
    })
}

shinyApp(ui, server)
</code>```

答: Well, I figure it out using insertUI and removeUI. To loop the tabsetPanel I used do.call method and voila!!!

Body:
I have been trying to develop this tabsetpanel for a while but without success. The goal is to assemble the tabs dynamically. After the user click the search button, the tabs will be assembled from the user's selection in selectizeInput. Each tab will have a specific content. When the user presses the search button again, the tabs must be built again with the information from selectizeInput without duplication.

I appreciate any help.

the result should be like this image:

library(shiny)

ui <- fluidPage(
    title = "Examples of DataTables",
    sidebarLayout(
        sidebarPanel(

            selectizeInput(
                'state', 'State', choices = state.name, multiple = TRUE
            ),
            actionButton("search", "Search"),

        ),
        mainPanel(
            tabsetPanel(
                id = 'dataset',
                tabPanel("tab1", verbatimTextOutput("tab1"))
            )

        )
    )
)

server <- function(input, output) {

    output$tab1 <- renderPrint({
        "tab1"
    })
}

shinyApp(ui, server)


问:
How to sort the files according to the time stamp in unix?
How to sort the files according to the time stamp in unix?
I need to sort the files and also based on time they created.</p>

答:
File modification:

```<code>ls -t
</code>```

Inode change:

```<code>ls -tc
</code>```

File access:

```<code>ls -tu
</code>```

"Newest" one at the bottom:

```<code>ls -tr
</code>```

None of this is a creation time. Most Unix filesystems don't support creation timestamps.

Body:
File modification:

ls -t

Inode change:

ls -tc

File access:

ls -tu

"Newest" one at the bottom:

ls -tr

None of this is a creation time. Most Unix filesystems don't support creation timestamps.


问:
Spark Partitionby doesn't scale as expected
INPUT:

The input data set contains 10 million transactions in multiple files stored as parquet. The size of the entire data set including all files ranges from 6 to 8GB.

PROBLEM STATEMENT:

Partition the transactions based on customer id's which would create one folder per customer id and each folder containing all the transactions done by that particular customer.

HDFS has a hard limit of 6.4 million on the number of sub directories within a root directory that can be created so using the last two digits of the customer id ranging from 00,01,02...to 99 to create top level directories and each top level directory would contain all the customer id's ending with that specific two digits.

Sample output directory structure:

00/cust_id=100900/part1.csv

00/cust_id=100800/part33.csv

01/cust_id=100801/part1.csv

03/cust_id=100803/part1.csv

CODE:

```<code>// Reading input file and storing in cache
val parquetReader = sparksession.read
  .parquet("/inputs")
  .persist(StorageLevel.MEMORY_ONLY) //No spill will occur has enough memory

// Logic to partition
var customerIdEndingPattern = 0
while (cardAccountEndingPattern < 100) {
  var idEndPattern = customerIdEndingPattern + ""
  if (customerIdEndingPattern < 10) {
    idEndPattern = "0" + customerIdEndingPattern
  }

  parquetReader
    .filter(col("customer_id").endsWith(idEndPattern))
    .repartition(945, col("customer_id"))
    .write
    .partitionBy("customer_id")
    .option("header", "true")
    .mode("append")
    .csv("/" + idEndPattern)
  customerIdEndingPattern = customerIdEndingPattern + 1
}
</code>```

Spark Configuration:
Amazon EMR 5.29.0 (Spark 2.4.4 & Hadoop 2.8.5)

1 master and 10 slaves and each of them has 96 vCores and 768GB RAM(Amazon AWS R5.24xlarge instance). Hard disks are EBS with bust of 3000 IOPS for 30 mins.

```<code>            'spark.hadoop.dfs.replication': '3',
            'spark.driver.cores':'5',
            'spark.driver.memory':'32g',
            'spark.executor.instances': '189',
            'spark.executor.memory': '32g',
            'spark.executor.cores': '5',
            'spark.executor.memoryOverhead':'8192',
            'spark.driver.memoryOverhead':'8192',
            'spark.default.parallelism':'945',
            'spark.sql.shuffle.partitions' :'945',
            'spark.serializer':'org.apache.spark.serializer.KryoSerializer',
            'spark.dynamicAllocation.enabled': 'false',
            'spark.memory.fraction':'0.8',
            'spark.hadoop.mapreduce.fileoutputcommitter.algorithm.version':'2',
            'spark.memory.storageFraction':'0.2',
            'spark.task.maxFailures': '6',
            'spark.driver.extraJavaOptions': '-XX:+UseG1GC -XX:+UnlockDiagnosticVMOptions -XX:+G1SummarizeConcMark -XX:InitiatingHeapOccupancyPercent=35 -XX:ConcGCThreads=12 -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:OnOutOfMemoryError="kill -9 %p"
            'spark.executor.extraJavaOptions': '-XX:+UseG1GC -XX:+UnlockDiagnosticVMOptions -XX:+G1SummarizeConcMark -XX:InitiatingHeapOccupancyPercent=35 -XX:ConcGCThreads=12 -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:OnOutOfMemoryError="kill -9 %p"
</code>```

SCALING ISSUES:

Experimented from 10 to all the way upto 40 slaves(adjusting the spark configs accordingly) but still the same results the job takes more than 2hrs to complete(as shown in the first pic each job takes more than a minute and the while loop runs 99 times). Also the reads from remote executors are almost non existent(which is good) most are process local.

Partition seems to work fine(refer second pic) got 5 RDD blocks per instance and 5 tasks running at all times(each instance has 5 cores and 19 instances per slave node). GC is optimized too.

Each partitionby task as written in the while loop takes a minute or more to complete.

METRICS:

Sample duration of a few jobs we have 99 jobs in total

Partition seems okay

Summary from 1 job basically one partitionby execution

Summary of a few instances after full job completion hence RDD blocks is zero and the first row is driver.

So the question is how to optimize it more and why it's not scaling up? Is there a better way to go about it? Have I reached the max performance already? Assuming I have access to more resources in terms of hardware is there anything I could do better? Any suggestions are welcome.

答:
Touching every record 100 times is very inefficient, even if data can be cached in memory and not be evicted downstream. Not to mention persisting alone is expensive

Instead you could add a virtual column

import org.apache.spark.sql.functions.substring

val df = sparksession.read
  .parquet("/inputs")
  .withColumn("partition_id", substring($"customer_id", -2, 2))
```

<p>and use it later for partitioning</p>

<pre class="lang-scala prettyprint-override"><code>df
  .write
  .partitionBy("partition_id", "customer_id")
  .option("header", "true")
  .mode("append")
  .csv("/")
</code>```

To avoid to many small files you can repartition first using longer suffix

val nParts: Int = ???
val suffixLength: Int = ???  // >= suffix length used for write partitions

df
  .repartitionByRange(
    nParts,
    substring($"customer_id", -suffixLength, suffixLength)
  .write
  .partitionBy("partition_id", "customer_id")
  .option("header", "true")
  .mode("append")
  .csv("/")
```

Such changes will allow you to process all data in a single pass without any explicit caching.

Body:
INPUT:

The input data set contains 10 million transactions in multiple files stored as parquet. The size of the entire data set including all files ranges from 6 to 8GB.

PROBLEM STATEMENT:

Partition the transactions based on customer id's which would create one folder per customer id and each folder containing all the transactions done by that particular customer.

HDFS has a hard limit of 6.4 million on the number of sub directories within a root directory that can be created so using the last two digits of the customer id ranging from 00,01,02...to 99 to create top level directories and each top level directory would contain all the customer id's ending with that specific two digits.

Sample output directory structure:

00/cust_id=100900/part1.csv

00/cust_id=100800/part33.csv

01/cust_id=100801/part1.csv

03/cust_id=100803/part1.csv

CODE:

// Reading input file and storing in cache
val parquetReader = sparksession.read
  .parquet("/inputs")
  .persist(StorageLevel.MEMORY_ONLY) //No spill will occur has enough memory

// Logic to partition
var customerIdEndingPattern = 0
while (cardAccountEndingPattern < 100) {
  var idEndPattern = customerIdEndingPattern + ""
  if (customerIdEndingPattern < 10) {
    idEndPattern = "0" + customerIdEndingPattern
  }

  parquetReader
    .filter(col("customer_id").endsWith(idEndPattern))
    .repartition(945, col("customer_id"))
    .write
    .partitionBy("customer_id")
    .option("header", "true")
    .mode("append")
    .csv("/" + idEndPattern)
  customerIdEndingPattern = customerIdEndingPattern + 1
}

Spark Configuration:
Amazon EMR 5.29.0 (Spark 2.4.4 & Hadoop 2.8.5)

1 master and 10 slaves and each of them has 96 vCores and 768GB RAM(Amazon AWS R5.24xlarge instance). Hard disks are EBS with bust of 3000 IOPS for 30 mins.

            'spark.hadoop.dfs.replication': '3',
            'spark.driver.cores':'5',
            'spark.driver.memory':'32g',
            'spark.executor.instances': '189',
            'spark.executor.memory': '32g',
            'spark.executor.cores': '5',
            'spark.executor.memoryOverhead':'8192',
            'spark.driver.memoryOverhead':'8192',
            'spark.default.parallelism':'945',
            'spark.sql.shuffle.partitions' :'945',
            'spark.serializer':'org.apache.spark.serializer.KryoSerializer',
            'spark.dynamicAllocation.enabled': 'false',
            'spark.memory.fraction':'0.8',
            'spark.hadoop.mapreduce.fileoutputcommitter.algorithm.version':'2',
            'spark.memory.storageFraction':'0.2',
            'spark.task.maxFailures': '6',
            'spark.driver.extraJavaOptions': '-XX:+UseG1GC -XX:+UnlockDiagnosticVMOptions -XX:+G1SummarizeConcMark -XX:InitiatingHeapOccupancyPercent=35 -XX:ConcGCThreads=12 -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:OnOutOfMemoryError="kill -9 %p"
            'spark.executor.extraJavaOptions': '-XX:+UseG1GC -XX:+UnlockDiagnosticVMOptions -XX:+G1SummarizeConcMark -XX:InitiatingHeapOccupancyPercent=35 -XX:ConcGCThreads=12 -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:OnOutOfMemoryError="kill -9 %p"

SCALING ISSUES:

Experimented from 10 to all the way upto 40 slaves(adjusting the spark configs accordingly) but still the same results the job takes more than 2hrs to complete(as shown in the first pic each job takes more than a minute and the while loop runs 99 times). Also the reads from remote executors are almost non existent(which is good) most are process local.

Partition seems to work fine(refer second pic) got 5 RDD blocks per instance and 5 tasks running at all times(each instance has 5 cores and 19 instances per slave node). GC is optimized too.

Each partitionby task as written in the while loop takes a minute or more to complete.

METRICS:

Sample duration of a few jobs we have 99 jobs in total

Partition seems okay

Summary from 1 job basically one partitionby execution

Summary of a few instances after full job completion hence RDD blocks is zero and the first row is driver.

So the question is how to optimize it more and why it's not scaling up? Is there a better way to go about it? Have I reached the max performance already? Assuming I have access to more resources in terms of hardware is there anything I could do better? Any suggestions are welcome.

Body:
Touching every record 100 times is very inefficient, even if data can be cached in memory and not be evicted downstream. Not to mention persisting alone is expensive

Instead you could add a virtual column

import org.apache.spark.sql.functions.substring

val df = sparksession.read
  .parquet("/inputs")
  .withColumn("partition_id", substring($"customer_id", -2, 2))

and use it later for partitioning

df
  .write
  .partitionBy("partition_id", "customer_id")
  .option("header", "true")
  .mode("append")
  .csv("/")

To avoid to many small files you can repartition first using longer suffix

val nParts: Int = ???
val suffixLength: Int = ???  // >= suffix length used for write partitions

df
  .repartitionByRange(
    nParts,
    substring($"customer_id", -suffixLength, suffixLength)
  .write
  .partitionBy("partition_id", "customer_id")
  .option("header", "true")
  .mode("append")
  .csv("/")

Such changes will allow you to process all data in a single pass without any explicit caching.


问:
How to run a program in Atom Editor?
I found Atom editor as good free alternative to Sublime text editor. Not able to find a straightforward way to run a program in Atom editor. In my case, I am trying to run a java program. Please let me know if it's possible? If yes, please describe the steps to follow. </p>

答:
You can go settings, select packages and type atom-runner there if your browser can't open this link.

To run your code do Alt+R if you're using Windows in Atom.

Title: How to run a program in Atom Editor?


问:
How to add a line across multiple plots in R
Does anyone know how to add a line across multiple plots in R. I can't think of a ways to do this.

I am trying to connect the larger blue dots in the second image which have values over 80 to the next chart by a line that goes across both.

答:
Here's a rough and dirty solution (for more fine-grained solutions, see How do you draw a line across a multiple-figure environment in R?):

DATA:

```<code>par(mfrow = c(2,1))
plot(rnorm(100))
plot(rnorm(100,50))
</code>```

SOLUTION:

Use par(xpd = NA)to clip plotting to the device region:

```<code>par(xpd = NA)
abline(v = 80)
</code>```

RESULT:

Body:
Here's a rough and dirty solution (for more fine-grained solutions, see How do you draw a line across a multiple-figure environment in R?):

DATA:

par(mfrow = c(2,1))
plot(rnorm(100))
plot(rnorm(100,50))

SOLUTION:

Use par(xpd = NA)to clip plotting to the device region:

par(xpd = NA)
abline(v = 80)

RESULT:


问:
Do I have to cast an Object object to a specific type before using it in my contains and equals method?
So I have a Hospital class and inside it, I have a method called remove(Object object) which checks what kind of Object the parameter input is. Then after finding the instance of the object I use my equals method to find the object in the ArrayList to remove. My question is, do I have to cast the object to the specific type before using it?
Something like this: .........equals((Patient) object))?</p>

```<code>public boolean remove(Object object) {
        if(object instanceof Department){
            departments.remove(object);
            return true;
        }
        if(object instanceof Patient){
            for(int i = 0; i < departments.size(); i ++){
                for(int j = 0; j < departments.size(); j ++) {
                    if (departments.get(i).getPatients().get(j).equals(object)) {
                        departments.get(i).getPatients().remove(j);
                        return true;
                    }
                }
            }
        }
        if(object instanceof Employee){
            for(int i = 0; i < departments.size(); i ++){
                for(int j = 0; j < departments.size(); j ++) {
                    if (departments.get(i).getEmployees().get(j).equals(object)) {
                        departments.get(i).getEmployees().remove(j);
                        return true;
                    }
                }
            }
        }
        return false;
    }
</code>```

答: No need to cast it. equals(object) and equals((Patient) object) resolve to the same method, if it is implemented correctly.

Body:
So I have a Hospital class and inside it, I have a method called remove(Object object) which checks what kind of Object the parameter input is. Then after finding the instance of the object I use my equals method to find the object in the ArrayList to remove. My question is, do I have to cast the object to the specific type before using it?
Something like this: .........equals((Patient) object))?

public boolean remove(Object object) {
        if(object instanceof Department){
            departments.remove(object);
            return true;
        }
        if(object instanceof Patient){
            for(int i = 0; i < departments.size(); i ++){
                for(int j = 0; j < departments.size(); j ++) {
                    if (departments.get(i).getPatients().get(j).equals(object)) {
                        departments.get(i).getPatients().remove(j);
                        return true;
                    }
                }
            }
        }
        if(object instanceof Employee){
            for(int i = 0; i < departments.size(); i ++){
                for(int j = 0; j < departments.size(); j ++) {
                    if (departments.get(i).getEmployees().get(j).equals(object)) {
                        departments.get(i).getEmployees().remove(j);
                        return true;
                    }
                }
            }
        }
        return false;
    }


问:
My TCP client does not connect to my TCP server
These are my first steps with client-server communication via TCP in C#. Server is stuck after "Waiting for Client..." message. Client shows "Error: Not Connected to server". What's wrong?

Server code:

```<code>using System;
using System.Net;
using System.Net.Sockets;

namespace MyTCPServer
{
    public class MyTCPServerClass
    {
        public static void Main(string[] args)
        {
            TcpListener listener = null;
            int servPort = 55437;

            try
            {
                listener = new TcpListener(IPAddress.Any, servPort);
                listener.Start();
            }
            catch (SocketException se)
            {
                Console.WriteLine(se.ErrorCode + ": " + se.Message);
                Environment.Exit(se.ErrorCode);
            }

            TcpClient client = null;
            NetworkStream netStream = null;

            try
            {
                Console.WriteLine("Waiting for Client...");
                client = listener.AcceptTcpClient();
                Console.WriteLine("Get Stream...");
                netStream = client.GetStream();
                Console.Write("Handling client - ");

                int bytesRcvd;
                int totalBytesEchoed = 0;
                byte[] rcvBuffer = new byte[10000];

                while ((bytesRcvd = netStream.Read(rcvBuffer, 0, rcvBuffer.Length)) > 0)
                {
                    netStream.Write(rcvBuffer, 0, bytesRcvd);
                    totalBytesEchoed += bytesRcvd;
                }
                Console.WriteLine("echoed {0} bytes.", totalBytesEchoed);

                netStream.Close();
                client.Close();

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                netStream.Close();
            }
        }
    }
}
</code>```

Client code:

```<code>using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;

namespace MyTCPClient
{
    /// <summary>
    /// Demonstration eines synchron agierenden TcpClienten.
    /// </summary>
    public class MyTCPClientClass
    {
        static void Main(string[] args)
        {
            byte[] byteBuffer = Encoding.ASCII.GetBytes("Hello World");

            //IPAddress ipAddress = IPAddress.Parse("192.168.1.16");
            IPAddress ipAddress = IPAddress.Loopback;

            int servPort = 55437;

            TcpClient client = null;
            NetworkStream netStream = null;

            try {
                client = new TcpClient(new IPEndPoint(ipAddress, servPort));

                if (!client.Connected)
                {
                    Console.WriteLine("Error: Not Connected to server");
                    throw new Exception();
                }
                else Console.WriteLine("Connected to server... sending echo string");

                netStream = client.GetStream();

                netStream.Write(byteBuffer, 0, byteBuffer.Length);

                Console.WriteLine("Sent {0} bytes to server...", byteBuffer.Length);

                int totalBytesRcvd = 0;
                int bytesRcvd = 0;

                while (totalBytesRcvd < byteBuffer.Length) {
                    if ((bytesRcvd = netStream.Read(byteBuffer, totalBytesRcvd,
                            byteBuffer.Length - totalBytesRcvd)) == 0) {
                        Console.WriteLine("Connection closed prematurely.");
                        break;
                    }
                    totalBytesRcvd += bytesRcvd;
                }

                Console.WriteLine("Received {0} bytes from server: {1}", totalBytesRcvd,
                                  Encoding.ASCII.GetString(byteBuffer, 0, totalBytesRcvd));

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally {
                if (netStream != null) netStream.Close();
                if (client != null) client.Close();
            }

            Console.ReadKey(true);
        }
    }
}
</code>```

答:
client = new TcpClient();
client.Connect(new IPEndPoint(ipAddress, servPort));
```

Body:
These are my first steps with client-server communication via TCP in C#. Server is stuck after "Waiting for Client..." message. Client shows "Error: Not Connected to server". What's wrong?

Server code:

using System;
using System.Net;
using System.Net.Sockets;

namespace MyTCPServer
{
    public class MyTCPServerClass
    {
        public static void Main(string[] args)
        {
            TcpListener listener = null;
            int servPort = 55437;

            try
            {
                listener = new TcpListener(IPAddress.Any, servPort);
                listener.Start();
            }
            catch (SocketException se)
            {
                Console.WriteLine(se.ErrorCode + ": " + se.Message);
                Environment.Exit(se.ErrorCode);
            }

            TcpClient client = null;
            NetworkStream netStream = null;

            try
            {
                Console.WriteLine("Waiting for Client...");
                client = listener.AcceptTcpClient();
                Console.WriteLine("Get Stream...");
                netStream = client.GetStream();
                Console.Write("Handling client - ");

                int bytesRcvd;
                int totalBytesEchoed = 0;
                byte[] rcvBuffer = new byte[10000];

                while ((bytesRcvd = netStream.Read(rcvBuffer, 0, rcvBuffer.Length)) > 0)
                {
                    netStream.Write(rcvBuffer, 0, bytesRcvd);
                    totalBytesEchoed += bytesRcvd;
                }
                Console.WriteLine("echoed {0} bytes.", totalBytesEchoed);

                netStream.Close();
                client.Close();

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                netStream.Close();
            }
        }
    }
}

Client code:

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;

namespace MyTCPClient
{
    ///
    /// Demonstration eines synchron agierenden TcpClienten.
    ///
    public class MyTCPClientClass
    {
        static void Main(string[] args)
        {
            byte[] byteBuffer = Encoding.ASCII.GetBytes("Hello World");

            //IPAddress ipAddress = IPAddress.Parse("192.168.1.16");
            IPAddress ipAddress = IPAddress.Loopback;

            int servPort = 55437;

            TcpClient client = null;
            NetworkStream netStream = null;

            try {
                client = new TcpClient(new IPEndPoint(ipAddress, servPort));

                if (!client.Connected)
                {
                    Console.WriteLine("Error: Not Connected to server");
                    throw new Exception();
                }
                else Console.WriteLine("Connected to server... sending echo string");

                netStream = client.GetStream();

                netStream.Write(byteBuffer, 0, byteBuffer.Length);

                Console.WriteLine("Sent {0} bytes to server...", byteBuffer.Length);

                int totalBytesRcvd = 0;
                int bytesRcvd = 0;

                while (totalBytesRcvd < byteBuffer.Length) {
                    if ((bytesRcvd = netStream.Read(byteBuffer, totalBytesRcvd,
                            byteBuffer.Length - totalBytesRcvd)) == 0) {
                        Console.WriteLine("Connection closed prematurely.");
                        break;
                    }
                    totalBytesRcvd += bytesRcvd;
                }

                Console.WriteLine("Received {0} bytes from server: {1}", totalBytesRcvd,
                                  Encoding.ASCII.GetString(byteBuffer, 0, totalBytesRcvd));

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally {
                if (netStream != null) netStream.Close();
                if (client != null) client.Close();
            }

            Console.ReadKey(true);
        }
    }
}


问:
Thread-safe uniform random number generator
I have some parallel Fortran90 code in which each thread needs to generate the same sequence of random numbers.

I have a random number generator that seems to be thread-unsafe, since, for a given seed, I'm completely unable to repeat the same results each time I run the program.

I surfed unsuccessfully (almost) the entire web looking for some code of a thread-safe RNG. Could anyone provide me with (the link to) the code of one?

Thanks in advance!

答: Most repeatable random number generators need state in some form.  Without state, they can't do what comes next.  In order to be thread safe, you need a way to hold onto the state yourself (ie, it can't be global).</p>

OwnerDisplayName: Bellman

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Eric P

OwnerDisplayName: plinth


问:
How to implement Dark mode and Light Mode in flutter?
I want to create a flutter app that has 2 light and dark mode themes that change by a switch in-app and the default theme is default android theme.

I need to pass some custom color to the fellow widget and I don't want to just config material theme.

how to detect the user device default theme?

the secend question is how to provide a theme to the whole app?

third is how change the theme with a simple switch in running time?

答:
```<code>MaterialApp(
  theme: ThemeData.light(),
  /// theme: ThemeData.dark(),
)
</code>```

Down the widget tree, you can access ThemeData simply by writing Theme.of(context). If you want to access the current ThemeData and provide your own styling for certain field, you can do for an instance:

```<code>Widget build(BuildContext context) {
  var themeData = Theme.of(context).copyWith(scaffoldBackgroundColor: darkBlue)

  return Scaffold(
    backgroundColor = themeData.scaffoldBackgroundColor,
  );
}
</code>```

But to handle the ThemeData state (changing its value), you need to implement proper state management.

Body:
MaterialApp(
  theme: ThemeData.light(),
  /// theme: ThemeData.dark(),
)

Down the widget tree, you can access ThemeData simply by writing Theme.of(context). If you want to access the current ThemeData and provide your own styling for certain field, you can do for an instance:

Widget build(BuildContext context) {
  var themeData = Theme.of(context).copyWith(scaffoldBackgroundColor: darkBlue)

  return Scaffold(
    backgroundColor = themeData.scaffoldBackgroundColor,
  );
}

But to handle the ThemeData state (changing its value), you need to implement proper state management.


问:
How to add corner radius for UIView
I have to set some corner radius of UIView and I set it by this code:

```<code>@IBDesignable
class MyUIviewCorner: UIView {

    override func layoutSubviews() { setup() }

    func setup() {
        let r = self.bounds.size.height / 2
        let path = UIBezierPath(roundedRect: self.bounds,
        byRoundingCorners: [.topLeft, .topRight],
        cornerRadii: CGSize(width: r, height: r))
        let mask = CAShapeLayer()
        mask.backgroundColor = UIColor.clear.cgColor
        mask.path = path.cgPath
        layer.borderWidth = 1.5
        layer.borderColor = UIColor.red.cgColor
        self.layer.mask = mask
    }
}
</code>```

But I get this result:

I don't understand why is there white spaces on the top corners?

If I set bottom corner radius I get this:

答:
You can kind of see why if you increase the border width:

There seems to still be a filled rectangle "on top of" the rounded rectangle drawn by the created layer, covering up the rounded corner.

You can achieve what you want by just drawing with UIBezierPaths:

```<code>override func draw(_ rect: CGRect) {
    let r = self.bounds.size.height / 2
    let path = UIBezierPath(roundedRect: self.bounds,
    byRoundingCorners: [.topLeft, .topRight],
    cornerRadii: CGSize(width: r, height: r))
    path.lineWidth = 1.5
    UIColor.red.setStroke()
    path.stroke()
}
</code>```

Title: How to add corner radius for UIView

Body:
I have to set some corner radius of UIView and I set it by this code:

@IBDesignable
class MyUIviewCorner: UIView {

    override func layoutSubviews() { setup() }

    func setup() {
        let r = self.bounds.size.height / 2
        let path = UIBezierPath(roundedRect: self.bounds,
        byRoundingCorners: [.topLeft, .topRight],
        cornerRadii: CGSize(width: r, height: r))
        let mask = CAShapeLayer()
        mask.backgroundColor = UIColor.clear.cgColor
        mask.path = path.cgPath
        layer.borderWidth = 1.5
        layer.borderColor = UIColor.red.cgColor
        self.layer.mask = mask
    }
}

But I get this result:

I don't understand why is there white spaces on the top corners?

If I set bottom corner radius I get this:

Body:
You can kind of see why if you increase the border width:

There seems to still be a filled rectangle "on top of" the rounded rectangle drawn by the created layer, covering up the rounded corner.

You can achieve what you want by just drawing with UIBezierPaths:

override func draw(_ rect: CGRect) {
    let r = self.bounds.size.height / 2
    let path = UIBezierPath(roundedRect: self.bounds,
    byRoundingCorners: [.topLeft, .topRight],
    cornerRadii: CGSize(width: r, height: r))
    path.lineWidth = 1.5
    UIColor.red.setStroke()
    path.stroke()
}


问:
Using the pdf_data function from the pdftools package efficiently
The end goal is to use the pdftools package to efficiently move through a thousand pages of pdf documents to consistently, and safely, produce a useable dataframe/tibble.  I have attempted to use the tabulizer package, and pdf_text functions, but the results were inconsistent. Therefore, started working through the pdf_data() function, which I prefer.

For those unfamiliar with the pdf_data function, it converts a pdf page into a coordinate grid, with the 0,0 coordinate being in the upper-left corner of the page.  Therefore, by arranging the x,y coordinates, then pivoting the document into a wide format, all of the information is displayed as it would on the page, only with NAs for whitespaces

Here is a simple example using the familiar mtcars dataset.

```<code>library(pdftools)
library(tidyverse)
library(janitor)

pdf_file <- "https://github.com/ropensci/tabulizer/raw/master/inst/examples/data.pdf"

mtcars_pdf_df <- pdf_data(pdf_file)[[1]]

mtcars_pdf_df%>%
  arrange(x, y)%>%
  pivot_wider(id_cols = y, names_from = x, values_from = text)%>%
  unite(col = Car_type, `154`:`215`, sep = " ", remove = TRUE,  na.rm = TRUE)%>%
  arrange(y)%>%
  rename("Page Number" = `303`)%>%
  unite(col =  mpg, `253`:`254`, sep = "", remove = TRUE, na.rm = TRUE)%>%
  unite(col = cyl, `283` : `291` , sep = "", remove = TRUE, na.rm = TRUE)%>%
  unite(col = disp, `308` : `313`, sep = "", remove = TRUE, na.rm = TRUE)
</code>```

It would be nice to not use a dozen or so unite functions in order to rename the various columns.  I used the janitor package row_to_names() function at one point to convert row 1 to column names, which worked well but maybe someone has a better thought?

The central problem; removing the NAs from the dataset through uniting multiple columns, or shifting columns over so that NAs are filled by adjacent columns.

I'm trying to make this efficient.  Possible using the purrr package?  any help with making this process more efficient would be very appreciated.

The only information I had on the pdf_data() function going into this is from here...
https://ropensci.org/technotes/2018/12/14/pdftools-20/
Any additional resources would also be greatly appreciated (apart from the pdftools package help documentation/literature).

Thanks everyone! I hope this also helps others use the pdf_data() too :)

答:
Here is one approach that could perhaps be generalised if you know the PDF is a reasonably neat table...</p>

```<code>library(pdftools)
library(tidyverse)

pdf_file <- "https://github.com/ropensci/tabulizer/raw/master/inst/examples/data.pdf"

df <- pdf_data(pdf_file)[[1]]

df <- df %>% mutate(x = round(x/3),        #reduce resolution to minimise inconsistent coordinates
                    y = round(y/3)) %>%
  arrange(y, x) %>%                        #sort in reading order
  mutate(group = cumsum(!lag(space, default = 0))) %>%  #identify text with spaces and paste
  group_by(group) %>%
  summarise(x = first(x),
            y = first(y),
            text = paste(text, collapse = " ")) %>%
  group_by(y) %>%
  mutate(colno = row_number()) %>%         #add column numbers for table data
  ungroup() %>%
  select(text, colno, y) %>%
  pivot_wider(names_from = colno, values_from = text) %>% #pivot into table format
  select(-y) %>%
  set_names(c("car", .[1,-ncol(.)])) %>%   #shift names from first row
  slice(-1, -nrow(.)) %>%                  #remove names row and page number row
  mutate_at(-1, as.numeric)

df
# A tibble: 32 x 12
   car                 mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
   <chr>             <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
 1 Mazda RX4          21       6  160    110  3.9   2.62  16.5     0     1     4     4
 2 Mazda RX4 Wag      21       6  160    110  3.9   2.88  17.0     0     1     4     4
 3 Datsun 710         22.8     4  108     93  3.85  2.32  18.6     1     1     4     1
 4 Hornet 4 Drive     21.4     6  258    110  3.08  3.22  19.4     1     0     3     1
 5 Hornet Sportabout  18.7     8  360    175  3.15  3.44  17.0     0     0     3     2
 6 Valiant            18.1     6  225    105  2.76  3.46  20.2     1     0     3     1
 7 Duster 360         14.3     8  360    245  3.21  3.57  15.8     0     0     3     4
 8 Merc 240D          24.4     4  147.    62  3.69  3.19  20       1     0     4     2
 9 Merc 230           22.8     4  141.    95  3.92  3.15  22.9     1     0     4     2
10 Merc 280           19.2     6  168.   123  3.92  3.44  18.3     1     0     4     4
# ... with 22 more rows
</code>```

Body:
The end goal is to use the pdftools package to efficiently move through a thousand pages of pdf documents to consistently, and safely, produce a useable dataframe/tibble.  I have attempted to use the tabulizer package, and pdf_text functions, but the results were inconsistent. Therefore, started working through the pdf_data() function, which I prefer.

For those unfamiliar with the pdf_data function, it converts a pdf page into a coordinate grid, with the 0,0 coordinate being in the upper-left corner of the page.  Therefore, by arranging the x,y coordinates, then pivoting the document into a wide format, all of the information is displayed as it would on the page, only with NAs for whitespaces

Here is a simple example using the familiar mtcars dataset.

library(pdftools)
library(tidyverse)
library(janitor)

pdf_file <- "https://github.com/ropensci/tabulizer/raw/master/inst/examples/data.pdf"

mtcars_pdf_df <- pdf_data(pdf_file)[[1]]

mtcars_pdf_df%>%
  arrange(x, y)%>%
  pivot_wider(id_cols = y, names_from = x, values_from = text)%>%
  unite(col = Car_type, `154`:`215`, sep = " ", remove = TRUE,  na.rm = TRUE)%>%
  arrange(y)%>%
  rename("Page Number" = `303`)%>%
  unite(col =  mpg, `253`:`254`, sep = "", remove = TRUE, na.rm = TRUE)%>%
  unite(col = cyl, `283` : `291` , sep = "", remove = TRUE, na.rm = TRUE)%>%
  unite(col = disp, `308` : `313`, sep = "", remove = TRUE, na.rm = TRUE)

It would be nice to not use a dozen or so unite functions in order to rename the various columns.  I used the janitor package row_to_names() function at one point to convert row 1 to column names, which worked well but maybe someone has a better thought?

The central problem; removing the NAs from the dataset through uniting multiple columns, or shifting columns over so that NAs are filled by adjacent columns.

I'm trying to make this efficient.  Possible using the purrr package?  any help with making this process more efficient would be very appreciated.

The only information I had on the pdf_data() function going into this is from here...
https://ropensci.org/technotes/2018/12/14/pdftools-20/
Any additional resources would also be greatly appreciated (apart from the pdftools package help documentation/literature).

Thanks everyone! I hope this also helps others use the pdf_data() too :)

Body:
Here is one approach that could perhaps be generalised if you know the PDF is a reasonably neat table...

library(pdftools)
library(tidyverse)

pdf_file <- "https://github.com/ropensci/tabulizer/raw/master/inst/examples/data.pdf"

df <- pdf_data(pdf_file)[[1]]

df <- df %>% mutate(x = round(x/3),        #reduce resolution to minimise inconsistent coordinates
                    y = round(y/3)) %>%
  arrange(y, x) %>%                        #sort in reading order
  mutate(group = cumsum(!lag(space, default = 0))) %>%  #identify text with spaces and paste
  group_by(group) %>%
  summarise(x = first(x),
            y = first(y),
            text = paste(text, collapse = " ")) %>%
  group_by(y) %>%
  mutate(colno = row_number()) %>%         #add column numbers for table data
  ungroup() %>%
  select(text, colno, y) %>%
  pivot_wider(names_from = colno, values_from = text) %>% #pivot into table format
  select(-y) %>%
  set_names(c("car", .[1,-ncol(.)])) %>%   #shift names from first row
  slice(-1, -nrow(.)) %>%                  #remove names row and page number row
  mutate_at(-1, as.numeric)

df
# A tibble: 32 x 12
   car                 mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
   <chr>             <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
 1 Mazda RX4          21       6  160    110  3.9   2.62  16.5     0     1     4     4
 2 Mazda RX4 Wag      21       6  160    110  3.9   2.88  17.0     0     1     4     4
 3 Datsun 710         22.8     4  108     93  3.85  2.32  18.6     1     1     4     1
 4 Hornet 4 Drive     21.4     6  258    110  3.08  3.22  19.4     1     0     3     1
 5 Hornet Sportabout  18.7     8  360    175  3.15  3.44  17.0     0     0     3     2
 6 Valiant            18.1     6  225    105  2.76  3.46  20.2     1     0     3     1
 7 Duster 360         14.3     8  360    245  3.21  3.57  15.8     0     0     3     4
 8 Merc 240D          24.4     4  147.    62  3.69  3.19  20       1     0     4     2
 9 Merc 230           22.8     4  141.    95  3.92  3.15  22.9     1     0     4     2
10 Merc 280           19.2     6  168.   123  3.92  3.44  18.3     1     0     4     4
# ... with 22 more rows


问:
Disable Prev Control on first slide and disable Next control on last slide
using Slick and looking for a way to have the prev control disabled and hidden until the user clicks the next arrow. Similarly I want the Next control to become disabled and hidden once the user reaches the last slide.

A good illustration of what I'm trying to accomplish is here

Does slick have an attribute already for this that I have overlooked? Is this something that maybe can be accomplished using CSS by adding a disabled class?

The only thing similar I have found is this

```<code>$('.pages .slider').slick({
    autoplay: true,
    autoplaySpeed: 5000,
    infinite: false,
    onAfterChange: function(slide, index) {
        if(index == 4){
        $('.pages .slider').slickPause();
</code>```

But its not exactly what I am looking for.

答:
Folks,

Put

```<code> arrows: false,
</code>```

in setting JSON config.
So simple!!

Body:
using Slick and looking for a way to have the prev control disabled and hidden until the user clicks the next arrow. Similarly I want the Next control to become disabled and hidden once the user reaches the last slide.

A good illustration of what I'm trying to accomplish is here

Does slick have an attribute already for this that I have overlooked? Is this something that maybe can be accomplished using CSS by adding a disabled class?

The only thing similar I have found is this

$('.pages .slider').slick({
    autoplay: true,
    autoplaySpeed: 5000,
    infinite: false,
    onAfterChange: function(slide, index) {
        if(index == 4){
        $('.pages .slider').slickPause();

But its not exactly what I am looking for.

Body:
Folks,

Put

 arrows: false,

in setting JSON config.
So simple!!