问:
Error with map and string conversion in c++
I'm familiar with Python's dictionary function, and I'm assuming based on my research that C++'s map function is relatively similar. However I'm running into a "conversion" issue: </p>

```<code>std::string dictionary(std::string inquiry){
    std::map<std::string, std::string> mapK;
        mapK["12th st. Oakland City Center"]="12th";
        mapK["16th st. Mission"]="16th";

    return mapK.find(inquiry);
}
</code>```

<p>This is a string function that should receive a string and then with the corresponding key return a string back to the main. Evidently there's an issue with the return statement. </p>

```<code>error: could not convert 'mapK.std::map<_Key, _Tp, _Compare, _Alloc>::find<std::basic_string<char>, std::basic_string<char>, std::less<std::basic_string<char> >, std::allocator<std::pair<const std::basic_string<char>, std::basic_string<char> > > >((*(const key_type*)(& inquiry)))' from 'std::map<std::basic_string<char>, std::basic_string<char> >::iterator {aka std::_Rb_tree_iterator<std::pair<const std::basic_string<char>, std::basic_string<char> > >}' to 'std::string {aka std::basic_string<char>}'
  return mapK.find(inquiry);
</code>```

答:
Your problem is with the return type of find. It does not return the mapped type. Rather it returns an iterator.

The signature for find is iterator find( const Key& key ); (see here; there is also the const overload).

You should also check whether the key was found. So you could write something like

```<code>MapType::iterator i = mapK.find(inquiry);
if (i != mapK.end())
    return i->second;
else
    return ""; // or handle error some other way
</code>```

Alternatively you could use the member access operator[], but this will insert a default constructed element in the map if the key is not found.

Body:
I'm familiar with Python's dictionary function, and I'm assuming based on my research that C++'s map function is relatively similar. However I'm running into a "conversion" issue:

std::string dictionary(std::string inquiry){
    std::map<std::string, std::string> mapK;
        mapK["12th st. Oakland City Center"]="12th";
        mapK["16th st. Mission"]="16th";

    return mapK.find(inquiry);
}

This is a string function that should receive a string and then with the corresponding key return a string back to the main. Evidently there's an issue with the return statement.

error: could not convert 'mapK.std::map<_Key, _Tp, _Compare, _Alloc>::find<std::basic_string<char>, std::basic_string<char>, std::less<std::basic_string<char> >, std::allocator<std::pair<const std::basic_string<char>, std::basic_string<char> > > >((*(const key_type*)(& inquiry)))' from 'std::map<std::basic_string<char>, std::basic_string<char> >::iterator {aka std::_Rb_tree_iterator<std::pair<const std::basic_string<char>, std::basic_string<char> > >}' to 'std::string {aka std::basic_string<char>}'
  return mapK.find(inquiry);

Body:
Your problem is with the return type of find. It does not return the mapped type. Rather it returns an iterator.

The signature for find is iterator find( const Key& key ); (see here; there is also the const overload).

You should also check whether the key was found. So you could write something like

MapType::iterator i = mapK.find(inquiry);
if (i != mapK.end())
    return i->second;
else
    return ""; // or handle error some other way

Alternatively you could use the member access operator[], but this will insert a default constructed element in the map if the key is not found.


来源: stackexchange

问:
Use sed/awk to replace text in multiple lines at once
I have a very large (~60MB) text file in which I want to replace specific block lines with a predefined text. The line number of every block (3 lines) start is known and they are stored in a file:

```<code>...
11
30
42
58
...
</code>```

I know that I can use the following option in order to replace a block:

```<code>sed -i "Xs,(X+3)s/.*/REPLACEMENT/" filename.txt
</code>```

However, executing this command in a for loop like:

```<code>for line in $(cat linenumbers.txt); do
  eline=$((${line}+3))
  sed -i "Xs,(X+3)s/.*/REPLACEMENT/" filename.txt
done
</code>```

is very slow and takes a lot of time (> 10') and I have 100s of files in which I have to replace blocks.
Is there any other way to instruct sed to do that in one pass?

答:
awk to the rescue!

```<code>$ awk 'NR==FNR      {start[$1]; next}
       FNR in start {c=3}
       c&&c--       {print "replacement"; next}1' indices file
</code>```

this is a one pass process, you can save the output into a new file and overwrite the original one if you want.

ContentLicense: CC BY-SA 3.0

Body:
I have a very large (~60MB) text file in which I want to replace specific block lines with a predefined text. The line number of every block (3 lines) start is known and they are stored in a file:

...
11
30
42
58
...

I know that I can use the following option in order to replace a block:

sed -i "Xs,(X+3)s/.*/REPLACEMENT/" filename.txt

However, executing this command in a for loop like:

for line in $(cat linenumbers.txt); do
  eline=$((${line}+3))
  sed -i "Xs,(X+3)s/.*/REPLACEMENT/" filename.txt
done

is very slow and takes a lot of time (> 10') and I have 100s of files in which I have to replace blocks.
Is there any other way to instruct sed to do that in one pass?

Body:
awk to the rescue!

$ awk 'NR==FNR      {start[$1]; next}
       FNR in start {c=3}
       c&&c--       {print "replacement"; next}1' indices file

this is a one pass process, you can save the output into a new file and overwrite the original one if you want.


问:
Change Jfoenix TabbedPane Header Color
How to change jfoenix tabbedpane default header color?
jFoenix TabbedPane Header

Only tabs color changes.
Colored Tabs

答:
You can do it using css:

```<code>.tab{
-fx-background-color:red;
}

.tab-header-background{
-fx-background-color:red;
}
</code>```

So far this is all i can do for you. If you have any questions ask them.

Title: Change Jfoenix TabbedPane Header Color

Body:
You can do it using css:

.tab{
-fx-background-color:red;
}

.tab-header-background{
-fx-background-color:red;
}

So far this is all i can do for you. If you have any questions ask them.


问:
What to do with required, but empty, implementations?
I have a google map class

```<code>class MapActivity : FragmentActivity(), OnMapReadyCallback, LocationListener, GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener {
</code>```

However i only use a few of the required functions provided by the implementations.
All the unused methods i just place at the bottom of the class, like this:

```<code>override fun onConnected(p0: Bundle?) {
    checkLocationPermission()
    val mLocationProvider = FusedLocationProviderClient(this)

    mLocationProvider.lastLocation.addOnCompleteListener { task ->
        goToLocation(task.result.latitude, task.result.longitude)
    }

}

override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
    //To change body of created functions use File | Settings | File Templates.
}

override fun onProviderEnabled(provider: String?) {
    //To change body of created functions use File | Settings | File Templates.
}

override fun onProviderDisabled(provider: String?) {
    //To change body of created functions use File | Settings | File Templates.
}

override fun onConnectionSuspended(p0: Int) {
    //To change body of created functions use File | Settings | File Templates.
}

override fun onConnectionFailed(p0: ConnectionResult) {
    //To change body of created functions use File | Settings | File Templates.
}
</code>```

Is there a better way to dismiss of these unwanted required functions?

答:
You must implement all the methods of Interface.

But yes, in the case of code cleaning, you can have one extra class for implementing all methods of interface. And use that class with your original.

Click here for more info.

Body:
I have a google map class

class MapActivity : FragmentActivity(), OnMapReadyCallback, LocationListener, GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener {

However i only use a few of the required functions provided by the implementations.
All the unused methods i just place at the bottom of the class, like this:

override fun onConnected(p0: Bundle?) {
    checkLocationPermission()
    val mLocationProvider = FusedLocationProviderClient(this)

    mLocationProvider.lastLocation.addOnCompleteListener { task ->
        goToLocation(task.result.latitude, task.result.longitude)
    }

}

override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
    //To change body of created functions use File | Settings | File Templates.
}

override fun onProviderEnabled(provider: String?) {
    //To change body of created functions use File | Settings | File Templates.
}

override fun onProviderDisabled(provider: String?) {
    //To change body of created functions use File | Settings | File Templates.
}

override fun onConnectionSuspended(p0: Int) {
    //To change body of created functions use File | Settings | File Templates.
}

override fun onConnectionFailed(p0: ConnectionResult) {
    //To change body of created functions use File | Settings | File Templates.
}

Is there a better way to dismiss of these unwanted required functions?


问:
How to create checkboxes and radiobuttons with only html and css
I'm currently working on a school-project where a big part of my idea is based on radio-buttons and checkboxes. I've found a lot of codes out there on how to create them, the only problem is that I'm only allowed to use certain html-tags and no jQuery.

The tags I can use:

• html, head, body, title, meta, link

• header, section, article, footer

• div

• h1-h6

• p

• span

• ul, ol, li

• a

• img

• audio

Is there any way to create checkboxes and radio-buttons with these tags?

答:
Radiobuttons

I figured out the way to do the radiobuttons but they work only as far as one of them is focused.

.radio {
    display: inline-block;
    position: relative;
    margin-left: 1em;
    padding-left: 1.5em;
}

.radio::before {
    content: "";
    display: inline-block;
    border: 1px solid black;
    width: 1em;
    height: 1em;
    border-radius: 100%;
    position: absolute;
    left: 0;
    top: 0;
}

.radio:focus {
    outline: none;
}

.radio:focus::after {
    content: "";
    display: inline-block;
    border: 1px solid black;
    width: 0.5em;
    height: 0.5em;
    border-radius: 100%;
    position: absolute;
    background-color: black;
    left: 0.25em;
    top: 0.25em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="radio-group">
    <li tabindex="0" class="radio">Option 1</li>
    <li tabindex="0" class="radio">Option 2</li>
    <li tabindex="0" class="radio">Option 3</li>
</ul></code>```

The key element here is the tabindex in
 items that makes them focusable.

The tabindex global attribute indicates if its element can be focused, and if/where it participates in sequential keyboard navigation (usually with the Tab key, hence the name). It accepts an integer as a value, with different results depending on the integer's value: [...]

Checkboxes

I styled them but I have no clue on how to make them work without JS. (Now they behave exactly like the radios.)

.check {
    display: inline-block;
    position: relative;
    margin-left: 1em;
    padding-left: 1.5em;
}

.check::before {
    content: "";
    display: inline-block;
    border: 1px solid black;
    width: 1em;
    height: 1em;
    position: absolute;
    left: 0;
    top: 0;
}

.check:focus {
    outline: none;
}

.check:focus::after {
    content: "";
    display: inline-block;
    border-left: 3px solid black;
    border-bottom: 3px solid black;
    transform: rotate(-45deg);
    width: 1em;
    height: 0.5em;
    position: absolute;
    left: 0.1em;
    top: -0.1em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="check-boxes">
    <li tabindex="0" class="check">Option 1</li>
    <li tabindex="0" class="check">Option 2</li>
    <li tabindex="0" class="check">Option 3</li>
</ul></code>```

Hint: The only pure CSS thing that comes to my mind remotely similar of saving a state would be CSS counters, but since you can't build a selector based on counter's value...

Body:
Radiobuttons

I figured out the way to do the radiobuttons but they work only as far as one of them is focused.

.radio {
    display: inline-block;
    position: relative;
    margin-left: 1em;
    padding-left: 1.5em;
}

.radio::before {
    content: "";
    display: inline-block;
    border: 1px solid black;
    width: 1em;
    height: 1em;
    border-radius: 100%;
    position: absolute;
    left: 0;
    top: 0;
}

.radio:focus {
    outline: none;
}

.radio:focus::after {
    content: "";
    display: inline-block;
    border: 1px solid black;
    width: 0.5em;
    height: 0.5em;
    border-radius: 100%;
    position: absolute;
    background-color: black;
    left: 0.25em;
    top: 0.25em;
}

<ul class="radio-group">
    <li tabindex="0" class="radio">Option 1</li>
    <li tabindex="0" class="radio">Option 2</li>
    <li tabindex="0" class="radio">Option 3</li>
</ul>

The key element here is the tabindex in <li> items that makes them focusable.

The tabindex global attribute indicates if its element can be focused, and if/where it participates in sequential keyboard navigation (usually with the Tab key, hence the name). It accepts an integer as a value, with different results depending on the integer's value: [...]

Checkboxes

I styled them but I have no clue on how to make them work without JS. (Now they behave exactly like the radios.)

.check {
    display: inline-block;
    position: relative;
    margin-left: 1em;
    padding-left: 1.5em;
}

.check::before {
    content: "";
    display: inline-block;
    border: 1px solid black;
    width: 1em;
    height: 1em;
    position: absolute;
    left: 0;
    top: 0;
}

.check:focus {
    outline: none;
}

.check:focus::after {
    content: "";
    display: inline-block;
    border-left: 3px solid black;
    border-bottom: 3px solid black;
    transform: rotate(-45deg);
    width: 1em;
    height: 0.5em;
    position: absolute;
    left: 0.1em;
    top: -0.1em;
}

<ul class="check-boxes">
    <li tabindex="0" class="check">Option 1</li>
    <li tabindex="0" class="check">Option 2</li>
    <li tabindex="0" class="check">Option 3</li>
</ul>

Hint: The only pure CSS thing that comes to my mind remotely similar of saving a state would be CSS counters, but since you can't build a selector based on counter's value...


问:
How to link MongoDB and Superset BI and import real time data ？
I have a mongodb on a server 122.xxx.xxx.xxx. The mongodb version is 3.4.1.
I was asked to pool the real-time data from MongoDB to the superset BI to create various dashboards.

I have tried the following way:

Use a Foreign Data Wrapper mongodb + multicorn + yam_fdw o create a foreign table in postgresql

In Postgresql console:

```<code>CREATE EXTENSION multicorn;

CREATE SERVER mongodb_proxy_server FOREIGN DATA WRAPPER multicorn OPTIONS (wrapper 'yam_fdw.Yamfdw');

CREATE FOREIGN TABLE event_warnings (
"_id" varchar OPTIONS (type 'ObjectId'),
"ID" varchar, "Point" varchar,
"Start_Time" timestamptz, "Stop_Time" timestamptz, "Area" varchar,
"Value" float, "Station" varchar, "Device" varchar, "Warning_Type" varchar,
"Warning_Upper_Limit" float, "Warning_Lower_Limit" float,
"Warning_Method" int
)

SERVER mongodb_proxy_server OPTIONS (
db 'XXX', collection 'event_warnings',
host '122.XXX.XXX.XXX', port '27017', user 'username', password 'password'
);
</code>```

In superset

Successfully load the data

But the foreign table only appears in the slices section. In the SQL lab tab,

No foreign table appears

Anyone knows how to make the foreign table appears in the SQL lab tab ?

OS: Mac 64 bit

答:
Another solution would be to synchronize your data to a PostgreSQL database.

We assembled an open-source platform to do that here https://github.com/pajachiet/mongo_sql_analytics_platform

Body:
I have a mongodb on a server 122.xxx.xxx.xxx. The mongodb version is 3.4.1.
I was asked to pool the real-time data from MongoDB to the superset BI to create various dashboards.

I have tried the following way:

Use a Foreign Data Wrapper mongodb + multicorn + yam_fdw o create a foreign table in postgresql

In Postgresql console:

CREATE EXTENSION multicorn;

CREATE SERVER mongodb_proxy_server FOREIGN DATA WRAPPER multicorn OPTIONS (wrapper 'yam_fdw.Yamfdw');

CREATE FOREIGN TABLE event_warnings (
"_id" varchar OPTIONS (type 'ObjectId'),
"ID" varchar, "Point" varchar,
"Start_Time" timestamptz, "Stop_Time" timestamptz, "Area" varchar,
"Value" float, "Station" varchar, "Device" varchar, "Warning_Type" varchar,
"Warning_Upper_Limit" float, "Warning_Lower_Limit" float,
"Warning_Method" int
)

SERVER mongodb_proxy_server OPTIONS (
db 'XXX', collection 'event_warnings',
host '122.XXX.XXX.XXX', port '27017', user 'username', password 'password'
);

In superset

Successfully load the data

But the foreign table only appears in the slices section. In the SQL lab tab,

No foreign table appears

Anyone knows how to make the foreign table appears in the SQL lab tab ?

OS: Mac 64 bit


问:
How to get random value of attribute of Enum on each iteration?
I have created such Enum object:

```<code>class Gender(Enum):
    FEMALE = 'female'
    MALE = 'male'
    RANDOM = random.choice([FEMALE, MALE])
</code>```

and i want to get really random value each time, but it does not work:

```<code>>>> class Gender(Enum):
...    MALE = 'male'
...    FEMALE = 'female'
...    RANDOM = choice([MALE, FEMALE])
...
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>
</code>```

I have also tried use lambda, but it's looks not so good, although it works:

```<code>Gender.RANDOM()
</code>```

Are there other way to get random values each time, without using lambda expressions?

We use this enum object as default value of the argument of the some method that's why it should be an attribute, not a function, because when we use Gender.FEMALE it is not a function, it's an attribute and Gender.RANDOM should be an attribute too:

```<code>def full_name(gender=Gender.FEMALE):
    ...

def full_name(gender=Gender.RANDOM):
    ...
</code>```

答:
As others have said, the best way is to just make random() be a method on your enum class to make it clear that RANDOM is not a member.

However, since I like puzzles:

```<code>from enum import Enum
import random

class enumproperty(object):
    "like property, but on an enum class"

    def __init__(self, fget):
        self.fget = fget

    def __get__(self, instance, ownerclass=None):
        if ownerclass is None:
            ownerclass = instance.__class__
        return self.fget(ownerclass)

    def __set__(self, instance, value):
        raise AttributeError("can't set pseudo-member %r" % self.name)

    def __delete__(self, instance):
        raise AttributeError("can't delete pseudo-member %r" % self.name)

class Gender(Enum):
    FEMALE = 'female'
    MALE = 'male'
    @enumproperty
    def RANDOM(cls):
        return random.choice(list(cls.__members__.values()))
</code>```

In your full_name definition, using Gender.RANDOM as a default value will not get you what you want.  The standard for such is:

```<code>def full_name(gender=None):
    if gender is None:
        gender = Gender.RANDOM   # we get `MALE` or `FEMALE`, not `RANDOM`
</code>```

Which is going to be confusing to the reader.  This is much better using a normal method:

```<code>def full_name(gender=None):
    if gender is None:
        gender = Gender.random()
</code>```

Body:
I have created such Enum object:

class Gender(Enum):
    FEMALE = 'female'
    MALE = 'male'
    RANDOM = random.choice([FEMALE, MALE])

and i want to get really random value each time, but it does not work:

>>> class Gender(Enum):
...    MALE = 'male'
...    FEMALE = 'female'
...    RANDOM = choice([MALE, FEMALE])
...
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>

I have also tried use lambda, but it's looks not so good, although it works:

Gender.RANDOM()

Are there other way to get random values each time, without using lambda expressions?

We use this enum object as default value of the argument of the some method that's why it should be an attribute, not a function, because when we use Gender.FEMALE it is not a function, it's an attribute and Gender.RANDOM should be an attribute too:

def full_name(gender=Gender.FEMALE):
    ...

def full_name(gender=Gender.RANDOM):
    ...

Body:
As others have said, the best way is to just make random() be a method on your enum class to make it clear that RANDOM is not a member.

However, since I like puzzles:

from enum import Enum
import random

class enumproperty(object):
    "like property, but on an enum class"

    def __init__(self, fget):
        self.fget = fget

    def __get__(self, instance, ownerclass=None):
        if ownerclass is None:
            ownerclass = instance.__class__
        return self.fget(ownerclass)

    def __set__(self, instance, value):
        raise AttributeError("can't set pseudo-member %r" % self.name)

    def __delete__(self, instance):
        raise AttributeError("can't delete pseudo-member %r" % self.name)

class Gender(Enum):
    FEMALE = 'female'
    MALE = 'male'
    @enumproperty
    def RANDOM(cls):
        return random.choice(list(cls.__members__.values()))

In your full_name definition, using Gender.RANDOM as a default value will not get you what you want.  The standard for such is:

def full_name(gender=None):
    if gender is None:
        gender = Gender.RANDOM   # we get `MALE` or `FEMALE`, not `RANDOM`

Which is going to be confusing to the reader.  This is much better using a normal method:

def full_name(gender=None):
    if gender is None:
        gender = Gender.random()

ContentLicense: CC BY-SA 4.0


问:
Why function can return array of chars, but can't return array of other types?
```<code>const char* myf()
 {
  return "string";
 }
</code>```

but it'sn't work with arrays. Its looks as special ugly language design limitation.

答:
Litteral strings are special animals in C++. They behave as is they were pointers to static const arrays. As you function is declared to return a const char * you get a perfectly defined behaviour.

But the same can be done with any other array, provided it is static:

```<code>const int * myintfunc() {
    static const int arr[] = { 1, 2, 3};
    return arr;
}
</code>```

Will have the same defined behaviour and will return on each call a pointer to the (first element of the) same array containing the integers 1, 2 and 3.

If it was not const, the behaviour would be perfectly defined too, and each call would return a pointer to the first element of the same array. Simply the content of the array could be modified.

If the array had automatic storage, the function would still return a pointer to its first element, but the array would be destroyed when the function returns and the returned pointer would be a dangling one (pointing to an object that has reached its end of life), and using it is Undefined Behaviour.

Body:
const char* myf()
 {
  return "string";
 }

but it'sn't work with arrays. Its looks as special ugly language design limitation.

Body:
Litteral strings are special animals in C++. They behave as is they were pointers to static const arrays. As you function is declared to return a const char * you get a perfectly defined behaviour.

But the same can be done with any other array, provided it is static:

const int * myintfunc() {
    static const int arr[] = { 1, 2, 3};
    return arr;
}

Will have the same defined behaviour and will return on each call a pointer to the (first element of the) same array containing the integers 1, 2 and 3.

If it was not const, the behaviour would be perfectly defined too, and each call would return a pointer to the first element of the same array. Simply the content of the array could be modified.

If the array had automatic storage, the function would still return a pointer to its first element, but the array would be destroyed when the function returns and the returned pointer would be a dangling one (pointing to an object that has reached its end of life), and using it is Undefined Behaviour.


问:
Elastic Search 5+ query multiple exact values
i am using python 3.5 and elasicsearch 5.6.3:

```<code>deplist = ['A', 'B']
body = {"query": {
            "bool": {
                "must": {
                    "terms": {
                        "Department": deplist}}}}}
res = es.search(index=self.index, doc_type='data', body=body)
</code>```

but i dont have results, If i do i have results:

```<code>body = {"query": {
            "bool": {
                "must": {
                    "match": {
                        "Department": 'A'}}}}}
res = es.search(index=self.index, doc_type='data', body=body)
</code>```

答: Convert the query into JSON encoding before searching. Use json.dumps(body).

Body:
i am using python 3.5 and elasicsearch 5.6.3:

deplist = ['A', 'B']
body = {"query": {
            "bool": {
                "must": {
                    "terms": {
                        "Department": deplist}}}}}
res = es.search(index=self.index, doc_type='data', body=body)

but i dont have results, If i do i have results:

body = {"query": {
            "bool": {
                "must": {
                    "match": {
                        "Department": 'A'}}}}}
res = es.search(index=self.index, doc_type='data', body=body)


问:
Printing certain values using Collections.frequency()
I have an array as follows:

```<code>int[] array = {11, 14, 17, 11, 48, 33, 29, 11, 17, 22, 11, 48, 18};
</code>```

What I wanted to do was to find the duplicate values, and print them.

So my way of doing this was to convert to ArrayList, then to Set and use a stream on the Set.

```<code>ArrayList<Integer> list = new ArrayList<>(array.length);
for (int i = 0; i < array.length; i++) {
    list.add(array[i]);
}

Set<Integer> dup = new HashSet<>(list);
</code>```

I then used a stream to loop through it and print the values using Collections.frequency.

```<code>dup.stream().forEach((key) -> {
            System.out.println(key + ": " + Collections.frequency(list, key));
        });
</code>```

Which will of course print them all, even if the count is one.

I thought adding in if(key > 1) but it's the value I want not the key.

How can I get the value in this instance to print only where value > 2.

I could probably put in:

```<code>int check = Collections.frequency(list, key);
            if (check > 1) {
</code>```

but this then duplicates Collections.frequency(list, key) in the stream and is quite ugly.

答:
To implement the desired functionality, we can facilitate Java Streams, in particular, the Stream.collect method:

```<code><R> R collect(Supplier<R> supplier,
    BiConsumer<R,? super T> accumulator,
    BiConsumer<R,R> combiner)
</code>```

Please consider the following draft implementation:

```<code>import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;

public class Program {
    public static void main(final String[] args) {
        // Input.
        final int[] inputArray = {11, 14, 17, 11, 48, 33, 29, 11, 17, 22, 11, 48, 18};

        // Processing.
        final DuplicateCounter<Integer> duplicateCounter = Arrays.stream(inputArray)
            .collect(
                DuplicateCounter<Integer>::new,
                DuplicateCounter<Integer>::accept,
                DuplicateCounter<Integer>::combine
            );

        // Output.
        System.out.println(duplicateCounter.getDuplicateCountMap());
    }

    private static final class DuplicateCounter<T> implements Consumer<T> {
        private final Map<T, Integer> countMap = new HashMap<>();

        public void accept(final T obj) {
            this.incrementCounter(obj, 1);
        }

        public void combine(final DuplicateCounter<T> other) {
            other.countMap.entrySet()
                .forEach(entry -> this.incrementCounter(entry.getKey(), entry.getValue()));
        }

        public Map<T, Integer> getDuplicateCountMap() {
            return this.countMap.entrySet()
                .stream()
                .filter(entry -> entry.getValue() > 1)
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        }

        private void incrementCounter(final T obj, int increment) {
            final Integer counter = this.countMap.getOrDefault(obj, 0);
            this.countMap.put(obj, counter + increment);
        }
    }
}
</code>```

It outputs:

{48=2, 17=2, 11=4}

Additional references:

Reduction (The Java™ Tutorials > Collections > Aggregate Operations).

Java 8 Streams - collect vs reduce.

Body:
I have an array as follows:

int[] array = {11, 14, 17, 11, 48, 33, 29, 11, 17, 22, 11, 48, 18};

What I wanted to do was to find the duplicate values, and print them.

So my way of doing this was to convert to ArrayList, then to Set and use a stream on the Set.

ArrayList<Integer> list = new ArrayList<>(array.length);
for (int i = 0; i < array.length; i++) {
    list.add(array[i]);
}

Set<Integer> dup = new HashSet<>(list);

I then used a stream to loop through it and print the values using Collections.frequency.

dup.stream().forEach((key) -> {
            System.out.println(key + ": " + Collections.frequency(list, key));
        });

Which will of course print them all, even if the count is one.

I thought adding in if(key > 1) but it's the value I want not the key.

How can I get the value in this instance to print only where value > 2.

I could probably put in:

int check = Collections.frequency(list, key);
            if (check > 1) {

but this then duplicates Collections.frequency(list, key) in the stream and is quite ugly.

Body:
To implement the desired functionality, we can facilitate Java Streams, in particular, the Stream.collect method:

<R> R collect(Supplier<R> supplier,
    BiConsumer<R,? super T> accumulator,
    BiConsumer<R,R> combiner)

Please consider the following draft implementation:

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;

public class Program {
    public static void main(final String[] args) {
        // Input.
        final int[] inputArray = {11, 14, 17, 11, 48, 33, 29, 11, 17, 22, 11, 48, 18};

        // Processing.
        final DuplicateCounter<Integer> duplicateCounter = Arrays.stream(inputArray)
            .collect(
                DuplicateCounter<Integer>::new,
                DuplicateCounter<Integer>::accept,
                DuplicateCounter<Integer>::combine
            );

        // Output.
        System.out.println(duplicateCounter.getDuplicateCountMap());
    }

    private static final class DuplicateCounter<T> implements Consumer<T> {
        private final Map<T, Integer> countMap = new HashMap<>();

        public void accept(final T obj) {
            this.incrementCounter(obj, 1);
        }

        public void combine(final DuplicateCounter<T> other) {
            other.countMap.entrySet()
                .forEach(entry -> this.incrementCounter(entry.getKey(), entry.getValue()));
        }

        public Map<T, Integer> getDuplicateCountMap() {
            return this.countMap.entrySet()
                .stream()
                .filter(entry -> entry.getValue() > 1)
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        }

        private void incrementCounter(final T obj, int increment) {
            final Integer counter = this.countMap.getOrDefault(obj, 0);
            this.countMap.put(obj, counter + increment);
        }
    }
}

It outputs:

{48=2, 17=2, 11=4}

Additional references:

Reduction (The Java™ Tutorials > Collections > Aggregate Operations).

Java 8 Streams - collect vs reduce.


问:
sqrt: ValueError: math domain error
I'm facing a problem with "distance ValueError: math domain error" when using sqrt function in python.

Here is my code:

```<code>from math import sqrt

def distance(x1,y1,x2,y2):
    x3 = x2-x1
    xFinal = x3^2
    y3 = y2-y1
    yFinal = y3^2
    final = xFinal + yFinal
    d = sqrt(final)
    return d
</code>```

答: The power function in Python is **, not ^ (which is bit-wise xor).  So use x3**2 etc.

ContentLicense: CC BY-SA 2.5

Title: sqrt: ValueError: math domain error

Body:
I'm facing a problem with "distance ValueError: math domain error" when using sqrt function in python.

Here is my code:

from math import sqrt

def distance(x1,y1,x2,y2):
    x3 = x2-x1
    xFinal = x3^2
    y3 = y2-y1
    yFinal = y3^2
    final = xFinal + yFinal
    d = sqrt(final)
    return d


问:
RecyclerView isn't scrolling
I'm making an app, which contains a recyclerView with some items in it. The app uses a BottomNavigationView, and three other fragments to show some content.
Now, one of those fragments contains just a RecyclerView and isn't scrolling.

I already tried some things, like changing the height of the RecyclerView from match_parent to wrap_content, wrapping it with a LinearLayout, using a NestedScrollView or regular ScrollView, adding app:layout_behavior and even android:scrollbars. Nothing worked though.

The XML file of the layout with the list which isn't scrolling in it:

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="55dp">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_users"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</FrameLayout>
</code>```

I set the ConstrainedLayout below as the parent of the other Fragment, this also contains the BottomNavigationView (this is generated by Android Studio when I created the project btw):

```<code><android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_container"
android:layout_width="match_parent"
android:layout_height="match_parent">

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="0dp"
        android:layout_marginStart="0dp"
        android:background="@color/colorPrimary"
        app:itemIconTint="@drawable/bottom_nav_selector"
        app:itemTextColor="@drawable/bottom_nav_selector"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/navigation" />

</android.support.constraint.ConstraintLayout>
</code>```

Finally, this is inside the Fragment's class, where I set the RecyclerView:

```<code>    adapter = new UserListAdapter(list, getContext(), getLayoutInflater(), container);
    RecyclerView recyclerView = v.findViewById(R.id.rv_users);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

    recyclerView.setAdapter(adapter);
</code>```

I hope one of you guys can help me!

答: Have you enough data to list on recycler for scrolling?</p>

Title: RecyclerView isn't scrolling

Body:
I'm making an app, which contains a recyclerView with some items in it. The app uses a BottomNavigationView, and three other fragments to show some content.
Now, one of those fragments contains just a RecyclerView and isn't scrolling.

I already tried some things, like changing the height of the RecyclerView from match_parent to wrap_content, wrapping it with a LinearLayout, using a NestedScrollView or regular ScrollView, adding app:layout_behavior and even android:scrollbars. Nothing worked though.

The XML file of the layout with the list which isn't scrolling in it:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="55dp">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_users"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</FrameLayout>

I set the ConstrainedLayout below as the parent of the other Fragment, this also contains the BottomNavigationView (this is generated by Android Studio when I created the project btw):

<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_container"
android:layout_width="match_parent"
android:layout_height="match_parent">

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="0dp"
        android:layout_marginStart="0dp"
        android:background="@color/colorPrimary"
        app:itemIconTint="@drawable/bottom_nav_selector"
        app:itemTextColor="@drawable/bottom_nav_selector"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/navigation" />

</android.support.constraint.ConstraintLayout>

Finally, this is inside the Fragment's class, where I set the RecyclerView:

    adapter = new UserListAdapter(list, getContext(), getLayoutInflater(), container);
    RecyclerView recyclerView = v.findViewById(R.id.rv_users);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

    recyclerView.setAdapter(adapter);

I hope one of you guys can help me!


问:
jQuery - wait for image to load before changing background
There are lots of example of similar functionality on-line, but none seem to work for me. What I currently have is

```<code><img id="sample_image" src="sample_image.png" alt="">
<script>
$('#sample_image').on('load',function(){
    $("#sample_image").css("background", "#ff0000");
});
</script>
</code>```

I expected the image to load/show before the background color is changed, but what happens is you see the red background before the image is loaded.

I tried setting the src using jQuery...

```<code><img id="sample_image" src="" alt="">
<script>
$('#sample_image').attr("src", "sample_image.png").on('load',function(){
    $("#sample_image").css("background", "<%=strRGB%>");
});
</script>
</code>```

But this did the same.

What am I doing wrong?

Thanks

答:
In docs ( https://api.jquery.com/load-event/ ) they got:

```<code><img src="book.png" alt="Book" id="book">
...
$( "#book" ).load(function() {
  // Handler for .load() called.
});
</code>```

And sure, you can use vanilla:

```<code>var img = new Image()
img.src = "book.png";
img.onload = function(){ ... };
</code>```

Body:
There are lots of example of similar functionality on-line, but none seem to work for me. What I currently have is

I expected the image to load/show before the background color is changed, but what happens is you see the red background before the image is loaded.

I tried setting the src using jQuery...

But this did the same.

What am I doing wrong?

Thanks

Body:
In docs ( https://api.jquery.com/load-event/ ) they got:

<img src="book.png" alt="Book" id="book">
...
$( "#book" ).load(function() {
  // Handler for .load() called.
});

And sure, you can use vanilla:

var img = new Image()
img.src = "book.png";
img.onload = function(){ ... };


问:
An extender can't be in a different UpdatePanel than the control it extends asp.net
I am getting this error "An extender can't be in a different UpdatePanel than the control it extends". what could be the reason and how to tackle this problem.</p>

答: Check for controls with extenders that are have the same  ID especially if you copy pasted from another form</p>


问:
Bash - heredoc with variable expansion, preserving newlines
I am trying to generate the mail text for the send mail client ssmtp within a bash script (instead of putting it in a file).

Using heredocs I came up with this:

```<code>MAILTO=me@mydomain.com
FROM=admin@mydomain.com
SUBJ="$HOSTNAME: Daemon not running"

read -d '' msg <<EOF
    To: $MAILTO
    From: $FROM
    Subject: $SUBJ

    Please check $HOSTNAME.
    Daemon has stopped running.

    -Admin
EOF

echo $msg | ssmtp $MAILTO
</code>```

(This does not work. ssmtp does not send the mail, because the text does not preserve the newlines.)

If I echo $msg, then I see that the newlines in the heredoc are not preserved. How can I accomplish that?

Also: Where is the difference btw this

```<code>{
  echo "To: $MAILTO"
  echo "From: $FROM"
  echo "Subject: $SUBJ"
  echo
  echo "Please check $HOSTNAME"
} | ssmtp $MAILTO
</code>```

and the first example? Are all echo commands executed and the result piped to ssmtp? Isn't this working in my first example? Can't I echo a text and pipe echo's output to a command?

答:
First, you don't need read for this:

```<code>msg="\
To: $MAILTO
From: $FROM
Subject: $SUBJ

Please check $HOSTNAME.
Daemon has stopped running.

-Admin"
</code>```

Second, you should always quote parameter expansions; you'll know when doing so isn't what you want, and such cases are rare.

```<code>echo "$msg" | ssmtp "$MAILTO"
</code>```

Finally, consider whether you need msg in the first place:

```<code>ssmtp "$MAILTO" <<EOF
To: $MAILTO
From: $FROM
Subject: $SUBJ

Please check $HOSTNAME.
Daemon has stopped running.

-Admin
EOF
</code>```

Body:
I am trying to generate the mail text for the send mail client ssmtp within a bash script (instead of putting it in a file).

Using heredocs I came up with this:

MAILTO=me@mydomain.com
FROM=admin@mydomain.com
SUBJ="$HOSTNAME: Daemon not running"

read -d '' msg <<EOF
    To: $MAILTO
    From: $FROM
    Subject: $SUBJ

    Please check $HOSTNAME.
    Daemon has stopped running.

    -Admin
EOF

echo $msg | ssmtp $MAILTO

(This does not work. ssmtp does not send the mail, because the text does not preserve the newlines.)

If I echo $msg, then I see that the newlines in the heredoc are not preserved. How can I accomplish that?

Also: Where is the difference btw this

{
  echo "To: $MAILTO"
  echo "From: $FROM"
  echo "Subject: $SUBJ"
  echo
  echo "Please check $HOSTNAME"
} | ssmtp $MAILTO

and the first example? Are all echo commands executed and the result piped to ssmtp? Isn't this working in my first example? Can't I echo a text and pipe echo's output to a command?

Body:
First, you don't need read for this:

msg="\
To: $MAILTO
From: $FROM
Subject: $SUBJ

Please check $HOSTNAME.
Daemon has stopped running.

-Admin"

Second, you should always quote parameter expansions; you'll know when doing so isn't what you want, and such cases are rare.

echo "$msg" | ssmtp "$MAILTO"

Finally, consider whether you need msg in the first place:

ssmtp "$MAILTO" <<EOF
To: $MAILTO
From: $FROM
Subject: $SUBJ

Please check $HOSTNAME.
Daemon has stopped running.

-Admin
EOF


问:
Ethernet adapter broken after VMWare deinstallation
Unfortunately I cannot connect over LAN anymore after i deinstalled the VMWare Workstation Player.
The error just says "network cable unplugged". Which is obviously wrong.

What I've already did:

Rebooting

Updating the ethernet driver

Removing the adapter with and without the driver

Resetting all network settings

I'm pretty clueless at the moment.

答:
Thanks for the downvotes ;)

I fixed it by booting into linux. It somehow re-initiated the ethernet port.


问:
Calculating the average difference in purchase dates by customer id
Was wondering how I would use R to calculate the below.

Assuming a CSV with the following purchase data:

```<code>| Customer ID  | Purchase Date |
| 1            | 01/01/2017    |
| 2            | 01/01/2017    |
| 3            | 01/01/2017    |
| 4            | 01/01/2017    |
| 1            | 02/01/2017    |
| 2            | 03/01/2017    |
| 2            | 07/01/2017    |
</code>```

I want to figure out the average time between repurchases by customer.

The math would  be like the one below:

```<code>| Customer ID  | AVG repurchase |
| 1            | 30 days        | = (02/01 - 01/01 / 1 order
| 2            | 90 days        | = ( (03/01 - 01/01) + (07 - 3/1) ) /2 orders
| 3            | n/a            |
| 4            | n/a            |
</code>```

The output would be the total average across customers -- so: 60 days = (30 avg for customer1 + 90 avg for customer2) / 2 customers.

答:
Here's another solution with dplyr + lubridate:

```<code>library(dplyr)
library(lubridate)

df %>%
  mutate(Purchase_Date = mdy(Purchase_Date)) %>%
  group_by(Customer_ID) %>%
  summarize(AVG_Repurchase = sum(difftime(Purchase_Date,
                                          lag(Purchase_Date), units = "days"),
                                 na.rm=TRUE)/(n()-1))
</code>```

or with data.table:

```<code>library(data.table)

setDT(df)[, Purchase_Date := mdy(Purchase_Date)]

df[, .(AVG_Repurchase = sum(difftime(Purchase_Date,
                                     shift(Purchase_Date), units = "days"),
                            na.rm=TRUE)/(.N-1)), by = "Customer_ID"]
</code>```

Result:

```<code># A tibble: 4 x 2
  Customer_ID AVG_Repurchase
        <dbl>         <time>
1           1      31.0 days
2           2      90.5 days
3           3       NaN days
4           4       NaN days

   Customer_ID AVG_Repurchase
1:           1      31.0 days
2:           2      90.5 days
3:           3       NaN days
4:           4       NaN days
</code>```

Note:

I first converted Purchase_Date to mmddyyyy format, then group_by Customer_ID. Final for each Customer_ID, I calculated the mean of the days difference between Purchase_Date and it's lag.

Data:

```<code>df = structure(list(Customer_ID = c(1, 2, 3, 4, 1, 2, 2), Purchase_Date = c(" 01/01/2017",
" 01/01/2017", " 01/01/2017", " 01/01/2017", " 02/01/2017", " 03/01/2017",
" 07/01/2017")), .Names = c("Customer_ID", "Purchase_Date"), class = "data.frame", row.names = c(NA,
-7L))
</code>```

Body:
Was wondering how I would use R to calculate the below.

Assuming a CSV with the following purchase data:

| Customer ID  | Purchase Date |
| 1            | 01/01/2017    |
| 2            | 01/01/2017    |
| 3            | 01/01/2017    |
| 4            | 01/01/2017    |
| 1            | 02/01/2017    |
| 2            | 03/01/2017    |
| 2            | 07/01/2017    |

I want to figure out the average time between repurchases by customer.

The math would  be like the one below:

| Customer ID  | AVG repurchase |
| 1            | 30 days        | = (02/01 - 01/01 / 1 order
| 2            | 90 days        | = ( (03/01 - 01/01) + (07 - 3/1) ) /2 orders
| 3            | n/a            |
| 4            | n/a            |

The output would be the total average across customers -- so: 60 days = (30 avg for customer1 + 90 avg for customer2) / 2 customers.

Body:
Here's another solution with dplyr + lubridate:

library(dplyr)
library(lubridate)

df %>%
  mutate(Purchase_Date = mdy(Purchase_Date)) %>%
  group_by(Customer_ID) %>%
  summarize(AVG_Repurchase = sum(difftime(Purchase_Date,
                                          lag(Purchase_Date), units = "days"),
                                 na.rm=TRUE)/(n()-1))

or with data.table:

library(data.table)

setDT(df)[, Purchase_Date := mdy(Purchase_Date)]

df[, .(AVG_Repurchase = sum(difftime(Purchase_Date,
                                     shift(Purchase_Date), units = "days"),
                            na.rm=TRUE)/(.N-1)), by = "Customer_ID"]

Result:

# A tibble: 4 x 2
  Customer_ID AVG_Repurchase
        <dbl>         <time>
1           1      31.0 days
2           2      90.5 days
3           3       NaN days
4           4       NaN days

   Customer_ID AVG_Repurchase
1:           1      31.0 days
2:           2      90.5 days
3:           3       NaN days
4:           4       NaN days

Note:

I first converted Purchase_Date to mmddyyyy format, then group_by Customer_ID. Final for each Customer_ID, I calculated the mean of the days difference between Purchase_Date and it's lag.

Data:

df = structure(list(Customer_ID = c(1, 2, 3, 4, 1, 2, 2), Purchase_Date = c(" 01/01/2017",
" 01/01/2017", " 01/01/2017", " 01/01/2017", " 02/01/2017", " 03/01/2017",
" 07/01/2017")), .Names = c("Customer_ID", "Purchase_Date"), class = "data.frame", row.names = c(NA,
-7L))


问:
disable ordering by default for django_tables2 Tables
I use django_tables2 to render my tables. For one table, I only want to see the most recent 5 entries. Therefore, I need to order my queryset before passing it to the table object:

```<code>qset = myObject.objects.order_by('-start_time').all()[:5]
table = MyTableClass(qset, template='path/to/template.html')
</code>```

This yields the following error message:

```<code>AssertionError: Cannot reorder a query once a slice has been taken.
</code>```

I could set orderable=False for every django_tables.Column, but since MyTableClass inherits from another table class, I would like to avoid this.

Thanks in advance

答:
From: http://django-tables2.readthedocs.io/en/latest/pages/api-reference.html#table-meta

orderable (bool): Default value for column’s orderable attribute.

If the table and column don’t specify a value, a column’s orderable value will fallback to this. This provides an easy mechanism to disable ordering on an entire table, without adding orderable=False to each column in a table.

So this solves my Problem:

```<code>class MyTableClass(django_tables2.Table):
    class Meta:
        orderable = False
    ...
</code>```

Update:
As mentioned by @Jieter in the comments, passing it as an argument should also work (didn't check that):

```<code>table = MyTable(data, orderable=False)
</code>```

Body:
I use django_tables2 to render my tables. For one table, I only want to see the most recent 5 entries. Therefore, I need to order my queryset before passing it to the table object:

qset = myObject.objects.order_by('-start_time').all()[:5]
table = MyTableClass(qset, template='path/to/template.html')

This yields the following error message:

AssertionError: Cannot reorder a query once a slice has been taken.

I could set orderable=False for every django_tables.Column, but since MyTableClass inherits from another table class, I would like to avoid this.

Thanks in advance

Body:
From: http://django-tables2.readthedocs.io/en/latest/pages/api-reference.html#table-meta

orderable (bool): Default value for column’s orderable attribute.

If the table and column don’t specify a value, a column’s orderable value will fallback to this. This provides an easy mechanism to disable ordering on an entire table, without adding orderable=False to each column in a table.

So this solves my Problem:

class MyTableClass(django_tables2.Table):
    class Meta:
        orderable = False
    ...

Update:
As mentioned by @Jieter in the comments, passing it as an argument should also work (didn't check that):

table = MyTable(data, orderable=False)


问:
String Benchmarks in C# - Refactoring for Speed/Maintainability
I've been tinkering with small functions on my own time, trying to find ways to refactor them (I recently read Martin Fowler's book Refactoring: Improving the Design of Existing Code).  I found the following function MakeNiceString() while updating another part of the codebase near it, and it looked like a good candidate to mess with.  As it is, there's no real reason to replace it, but it's small enough and does something small so it's easy to follow and yet still get a 'good' experience from.

```<code>private static string MakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            string result = null;
            int i = 0;
            result += System.Convert.ToString(ca[0]);
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    result += " ";
                }
                result += System.Convert.ToString(ca[i]);
            }
            return result;
        }

static string SplitCamelCase(string str)
    {
        string[] temp = Regex.Split(str, @"(?<!^)(?=[A-Z])");
        string result = String.Join(" ", temp);
        return result;
    }
</code>```

The first function MakeNiceString() is the function I found in some code I was updating at work.  The purpose of the function is to translate ThisIsAString to This Is A String.  It's used in a half-dozen places in the code, and is pretty insignificant in the whole scheme of things.

I built the second function purely as an academic exercise to see if using a regular expression would take longer or not.

Well, here are the results:

With 10 Iterations:

```
MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks
```

However, it changes drastically over the longhaul:

With 10,000 Iterations:

```
MakeNiceString took 121625 ticks
SplitCamelCase took 443001 ticks
```

Refactoring MakeNiceString()

The process of refactoring MakeNiceString() started with simply removing the conversions that were taking place.  Doing that yielded the following results:

```
MakeNiceString took 124716 ticks
ImprovedMakeNiceString took 118486
```

Here's the code after Refactor #1:

```<code>private static string ImprovedMakeNiceString(string str)
        { //Removed Convert.ToString()
            char[] ca = str.ToCharArray();
            string result = null;
            int i = 0;
            result += ca[0];
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    result += " ";
                }
                result += ca[i];
            }
            return result;
        }
</code>```

Refactor#2 - Use StringBuilder

My second task was to use StringBuilder instead of String.  Since String is immutable, unnecessary copies were being created throughout the loop.  The benchmark for using that is below, as is the code:

```<code>static string RefactoredMakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            StringBuilder sb = new StringBuilder((str.Length * 5 / 4));
            int i = 0;
            sb.Append(ca[0]);
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    sb.Append(" ");
                }
                sb.Append(ca[i]);
            }
            return sb.ToString();
        }
</code>```

This results in the following Benchmark:

```
MakeNiceString Took:           124497 Ticks   //Original
SplitCamelCase Took:           464459 Ticks   //Regex
ImprovedMakeNiceString Took:   117369 Ticks   //Remove Conversion
RefactoredMakeNiceString Took:  38542 Ticks   //Using StringBuilder
```

Changing the for loop to a foreach loop resulted in the following benchmark result:

```<code>static string RefactoredForEachMakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            StringBuilder sb1 = new StringBuilder((str.Length * 5 / 4));
            sb1.Append(ca[0]);
            foreach (char c in ca)
            {
                if (!(char.IsLower(c)))
                {
                    sb1.Append(" ");
                }
                sb1.Append(c);
            }
            return sb1.ToString();
        }
</code>```

```
RefactoredForEachMakeNiceString    Took:  45163 Ticks
```

As you can see, maintenance-wise, the foreach loop will be the easiest to maintain and have the 'cleanest' look.  It is slightly slower than the for loop, but infinitely easier to follow.

Alternate Refactor: Use Compiled Regex

I moved the Regex to right before the loop is begun, in hopes that since it only compiles it once, it'll execute faster.  What I found out (and I'm sure I have a bug somewhere) is that that doesn't happen like it ought to:

```<code>static void runTest5()
        {
            Regex rg = new Regex(@"(?<!^)(?=[A-Z])", RegexOptions.Compiled);
            for (int i = 0; i < 10000; i++)
            {
                CompiledRegex(rg, myString);
            }
        }
 static string CompiledRegex(Regex regex, string str)
    {
        string result = null;
        Regex rg1 = regex;
        string[] temp = rg1.Split(str);
        result = String.Join(" ", temp);
        return result;
    }
</code>```

Final Benchmark Results:

```
MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks
```0

Or, if you prefer milliseconds:

```
MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks
```1

So the percentage gains are:

```
MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks
```2

(Please check my math)

In the end, I'm going to replace what's there with the RefactoredForEachMakeNiceString() and while I'm at it, I'm going to rename it to something useful, like SplitStringOnUpperCase.

Benchmark Test:

To benchmark, I simply invoke a new Stopwatch for each method call:

```<code>       string myString = "ThisIsAUpperCaseString";
       Stopwatch sw = new Stopwatch();
       sw.Start();
       runTest();
       sw.Stop();

     static void runTest()
        {

            for (int i = 0; i < 10000; i++)
            {
                MakeNiceString(myString);
            }

        }
</code>```

Questions

What causes these functions to be so different 'over the long haul', and

How can I improve this function
a) to be more maintainable or
b) to run faster?

How would I do memory benchmarks on these to see which used less memory?

Thank you for your responses thus far. I've inserted all of the suggestions made by @Jon Skeet, and would like feedback on the updated questions I've asked as a result.

NB: This question is meant to explore ways to refactor string handling functions in C#. I copied/pasted the first code as is.  I'm well aware you can remove the System.Convert.ToString() in the first method, and I did just that.  If anyone is aware of any implications of removing the System.Convert.ToString(), that would also be helpful to know.

答:
I know what they say about RegEx, use it to solve a problem and now you have two problems, but I remain a fan, Just for grins, here is a RegEx version. RegEx, with a little initiation is easy to read, less code, and lets you easily snap in additional delimiters (as I did with the comma).</p>

```<code>   s1 = MakeNiceString( "LookOut,Momma,There'sAWhiteBoatComingUpTheRiver" ) );

   private string MakeNiceString( string input )
   {
       StringBuilder sb = new StringBuilder( input );
       int Incrementer = 0;
       MatchCollection mc;
       const string SPACE = " ";

       mc = Regex.Matches( input, "[A-Z|,]" );

       foreach ( Match m in mc )
       {
           if ( m.Index > 0 )
           {
               sb.Insert( m.Index + Incrementer, SPACE );
               Incrementer++;
           }
       }

       return sb.ToString().TrimEnd();
   }
</code>```

OwnerDisplayName: Gortok

Body:
I've been tinkering with small functions on my own time, trying to find ways to refactor them (I recently read Martin Fowler's book Refactoring: Improving the Design of Existing Code).  I found the following function MakeNiceString() while updating another part of the codebase near it, and it looked like a good candidate to mess with.  As it is, there's no real reason to replace it, but it's small enough and does something small so it's easy to follow and yet still get a 'good' experience from.

private static string MakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            string result = null;
            int i = 0;
            result += System.Convert.ToString(ca[0]);
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    result += " ";
                }
                result += System.Convert.ToString(ca[i]);
            }
            return result;
        }

static string SplitCamelCase(string str)
    {
        string[] temp = Regex.Split(str, @"(?<!^)(?=[A-Z])");
        string result = String.Join(" ", temp);
        return result;
    }

The first function MakeNiceString() is the function I found in some code I was updating at work.  The purpose of the function is to translate ThisIsAString to This Is A String.  It's used in a half-dozen places in the code, and is pretty insignificant in the whole scheme of things.

I built the second function purely as an academic exercise to see if using a regular expression would take longer or not.

Well, here are the results:

With 10 Iterations:

MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks

However, it changes drastically over the longhaul:

With 10,000 Iterations:

MakeNiceString took 121625 ticks
SplitCamelCase took 443001 ticks

Refactoring MakeNiceString()

The process of refactoring MakeNiceString() started with simply removing the conversions that were taking place.  Doing that yielded the following results:

MakeNiceString took 124716 ticks
ImprovedMakeNiceString took 118486

Here's the code after Refactor #1:

private static string ImprovedMakeNiceString(string str)
        { //Removed Convert.ToString()
            char[] ca = str.ToCharArray();
            string result = null;
            int i = 0;
            result += ca[0];
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    result += " ";
                }
                result += ca[i];
            }
            return result;
        }

Refactor#2 - Use StringBuilder

My second task was to use StringBuilder instead of String.  Since String is immutable, unnecessary copies were being created throughout the loop.  The benchmark for using that is below, as is the code:

static string RefactoredMakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            StringBuilder sb = new StringBuilder((str.Length * 5 / 4));
            int i = 0;
            sb.Append(ca[0]);
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    sb.Append(" ");
                }
                sb.Append(ca[i]);
            }
            return sb.ToString();
        }

This results in the following Benchmark:

MakeNiceString Took:           124497 Ticks   //Original
SplitCamelCase Took:           464459 Ticks   //Regex
ImprovedMakeNiceString Took:   117369 Ticks   //Remove Conversion
RefactoredMakeNiceString Took:  38542 Ticks   //Using StringBuilder

Changing the for loop to a foreach loop resulted in the following benchmark result:

static string RefactoredForEachMakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            StringBuilder sb1 = new StringBuilder((str.Length * 5 / 4));
            sb1.Append(ca[0]);
            foreach (char c in ca)
            {
                if (!(char.IsLower(c)))
                {
                    sb1.Append(" ");
                }
                sb1.Append(c);
            }
            return sb1.ToString();
        }

RefactoredForEachMakeNiceString    Took:  45163 Ticks

As you can see, maintenance-wise, the foreach loop will be the easiest to maintain and have the 'cleanest' look.  It is slightly slower than the for loop, but infinitely easier to follow.

Alternate Refactor: Use Compiled Regex

I moved the Regex to right before the loop is begun, in hopes that since it only compiles it once, it'll execute faster.  What I found out (and I'm sure I have a bug somewhere) is that that doesn't happen like it ought to:

static void runTest5()
        {
            Regex rg = new Regex(@"(?<!^)(?=[A-Z])", RegexOptions.Compiled);
            for (int i = 0; i < 10000; i++)
            {
                CompiledRegex(rg, myString);
            }
        }
 static string CompiledRegex(Regex regex, string str)
    {
        string result = null;
        Regex rg1 = regex;
        string[] temp = rg1.Split(str);
        result = String.Join(" ", temp);
        return result;
    }

Final Benchmark Results:

MakeNiceString Took                   139363 Ticks
SplitCamelCase Took                   489174 Ticks
ImprovedMakeNiceString Took           115478 Ticks
RefactoredMakeNiceString Took          38819 Ticks
RefactoredForEachMakeNiceString Took   44700 Ticks
CompiledRegex Took                    227021 Ticks

Or, if you prefer milliseconds:

MakeNiceString Took                  38 ms
SplitCamelCase Took                 123 ms
ImprovedMakeNiceString Took          33 ms
RefactoredMakeNiceString Took        11 ms
RefactoredForEachMakeNiceString Took 12 ms
CompiledRegex Took                   63 ms

So the percentage gains are:

MakeNiceString                   38 ms   Baseline
SplitCamelCase                  123 ms   223% slower
ImprovedMakeNiceString           33 ms   13.15% faster
RefactoredMakeNiceString         11 ms   71.05% faster
RefactoredForEachMakeNiceString  12 ms   68.42% faster
CompiledRegex                    63 ms   65.79% slower

(Please check my math)

In the end, I'm going to replace what's there with the RefactoredForEachMakeNiceString() and while I'm at it, I'm going to rename it to something useful, like SplitStringOnUpperCase.

Benchmark Test:

To benchmark, I simply invoke a new Stopwatch for each method call:

       string myString = "ThisIsAUpperCaseString";
       Stopwatch sw = new Stopwatch();
       sw.Start();
       runTest();
       sw.Stop();

     static void runTest()
        {

            for (int i = 0; i < 10000; i++)
            {
                MakeNiceString(myString);
            }

        }

Questions

What causes these functions to be so different 'over the long haul', and

How can I improve this function
a) to be more maintainable or
b) to run faster?

How would I do memory benchmarks on these to see which used less memory?

Thank you for your responses thus far. I've inserted all of the suggestions made by @Jon Skeet, and would like feedback on the updated questions I've asked as a result.

NB: This question is meant to explore ways to refactor string handling functions in C#. I copied/pasted the first code as is.  I'm well aware you can remove the System.Convert.ToString() in the first method, and I did just that.  If anyone is aware of any implications of removing the System.Convert.ToString(), that would also be helpful to know.

LastEditorDisplayName: Gortok

Body:
I know what they say about RegEx, use it to solve a problem and now you have two problems, but I remain a fan, Just for grins, here is a RegEx version. RegEx, with a little initiation is easy to read, less code, and lets you easily snap in additional delimiters (as I did with the comma).

   s1 = MakeNiceString( "LookOut,Momma,There'sAWhiteBoatComingUpTheRiver" ) );

   private string MakeNiceString( string input )
   {
       StringBuilder sb = new StringBuilder( input );
       int Incrementer = 0;
       MatchCollection mc;
       const string SPACE = " ";

       mc = Regex.Matches( input, "[A-Z|,]" );

       foreach ( Match m in mc )
       {
           if ( m.Index > 0 )
           {
               sb.Insert( m.Index + Incrementer, SPACE );
               Incrementer++;
           }
       }

       return sb.ToString().TrimEnd();
   }

OwnerDisplayName: rp


问:
Java - Access file with user authentication
I have a server where I work with a database and files using a java app.
When I start my app I give a report regarding file access to the server using:

```<code>public static boolean folderExists(String folderPath) {
    File folderToCheck = new File(folderPath);
    return folderToCheck.exists();
}
</code>```

Every time I start my app (after a fresh restart of my computer)
I get a false response, even though the server is on.
The reason is because I must give an authentication as another user.
What I do is access the server through Windows
where I am being asked for username/password,
and after that I get a true response regarding file access to the server.

Is there a way to give the authentication username/password through Java,
and not through Windows?

Thank you

答:
I am pretty sure, that there is no way to grant fileaccess by java, without a Windows-Call.

You can call cacls file.log /e /t /p Everyone:f but this will be language-dependent.

I had a similar problem: How to change the file ACL in windows, if I only know the SID?

With Java7 there may be a way to do this.

Body:
I have a server where I work with a database and files using a java app.
When I start my app I give a report regarding file access to the server using:

public static boolean folderExists(String folderPath) {
    File folderToCheck = new File(folderPath);
    return folderToCheck.exists();
}

Every time I start my app (after a fresh restart of my computer)
I get a false response, even though the server is on.
The reason is because I must give an authentication as another user.
What I do is access the server through Windows
where I am being asked for username/password,
and after that I get a true response regarding file access to the server.

Is there a way to give the authentication username/password through Java,
and not through Windows?

Thank you


问:
How to recalculate page number when combining multiple jasper reports in export?
I have decided to pass this Q/A after receiving both questions in chat and comment on answer on how to handle page number in "combined" jasper reports

When combining reports in java using

```<code>JasperPrint jasperPrint1 = JasperFillManager.fillReport(report1, paramMap);
JasperPrint jasperPrint2 = JasperFillManager.fillReport(report2, paramMap);
List<JasperPrint> jasperPrintList = Arrays.asList(jasperPrint1, jasperPrint2);

JRPdfExporter exporter = new JRPdfExporter();
exporter.setExporterInput(SimpleExporterInput.getInstance(jasperPrintList));
</code>```

The page number and total page number

<textField>
    <reportElement x="435" y="30" width="80" height="20" uuid="14bad2ac-3a56-4cf4-b4dd-310b8fcd2120"/>
    <textElement textAlignment="Right"/>
    <textFieldExpression><![CDATA["Page "+$V{PAGE_NUMBER}+" of"]]></textFieldExpression>
</textField>
<textField evaluationTime="Report">
        <reportElement x="515" y="30" width="40" height="20" uuid="06567ba6-6243-43e9-9813-f6593528524c"/>
        <textFieldExpression><![CDATA[" " + $V{PAGE_NUMBER}]]></textFieldExpression>
</textField>
```

Is always restarted for each report that I'm including in list, is there a way that I can recalculate these?

I want to have on each page the current page (and correct total number of pages) considering my final combined report.

答:
I was inspired by @Adityaz7 answer, I think his method is the best one. But I've done this without the need to add a library to the project and to create a temporary PDF file.

First of all modify your template and add one parameter to hold the number of previous pages:

```<code><parameter name="PREVIOUS_PAGE_NUMBER" class="java.lang.Integer"/>
</code>```

In the report element that contains the page number insert this expression:

```<code><textFieldExpression><![CDATA[String.valueOf($V{PAGE_NUMBER} + $P{PREVIOUS_PAGE_NUMBER})]></textFieldExpression>
</code>```

You have to use String.valueOf() method because if you use the simple sum of the elements $V{PAGE_NUMBER} + $P{PREVIOUS_PAGE_NUMBER}, Jasper will process this as a sum of strings and will print the two numbers as concatenated. (e.g. will print 11 instead of 2)

In your java code create a variable to hold the number of previous pages and pass it to Jasper as parameter. Then fill the first report and simply add the size of the list that contains the report pages to prevPageNumber, and pass it as parameter to the second report and so on:

```<code>int prevPageNumber = 0;
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("PREVIOUS_PAGE_NUMBER", prevPageNumber);

// fill the first report with prevPageNumber = 0
JasperPrint jasperPrint1 = JasperFillManager.fillReport(report1, paramMap);

if(jasperPrint1 != null && jasperPrint1.getPages() != null)
{
    // add previous report page number
    prevPageNumber += jasperPrint1.getPages().size();
}

paramMap.put("PREVIOUS_PAGE_NUMBER", prevPageNumber);
JasperPrint jasperPrint2 = JasperFillManager.fillReport(report2, paramMap);
</code>```

I wrote this inline to respect the structure OP used in the question, but of course is better to do this in a loop if you have more than 2 report to print.

Body:
I have decided to pass this Q/A after receiving both questions in chat and comment on answer on how to handle page number in "combined" jasper reports

When combining reports in java using

JasperPrint jasperPrint1 = JasperFillManager.fillReport(report1, paramMap);
JasperPrint jasperPrint2 = JasperFillManager.fillReport(report2, paramMap);
List<JasperPrint> jasperPrintList = Arrays.asList(jasperPrint1, jasperPrint2);

JRPdfExporter exporter = new JRPdfExporter();
exporter.setExporterInput(SimpleExporterInput.getInstance(jasperPrintList));

The page number and total page number

<textField>
    <reportElement x="435" y="30" width="80" height="20" uuid="14bad2ac-3a56-4cf4-b4dd-310b8fcd2120"/>
    <textElement textAlignment="Right"/>
    <textFieldExpression><![CDATA["Page "+$V{PAGE_NUMBER}+" of"]]></textFieldExpression>
</textField>
<textField evaluationTime="Report">
        <reportElement x="515" y="30" width="40" height="20" uuid="06567ba6-6243-43e9-9813-f6593528524c"/>
        <textFieldExpression><![CDATA[" " + $V{PAGE_NUMBER}]]></textFieldExpression>
</textField>

Is always restarted for each report that I'm including in list, is there a way that I can recalculate these?

I want to have on each page the current page (and correct total number of pages) considering my final combined report.

Body:
I was inspired by @Adityaz7 answer, I think his method is the best one. But I've done this without the need to add a library to the project and to create a temporary PDF file.

First of all modify your template and add one parameter to hold the number of previous pages:

<parameter name="PREVIOUS_PAGE_NUMBER" class="java.lang.Integer"/>

In the report element that contains the page number insert this expression:

<textFieldExpression><![CDATA[String.valueOf($V{PAGE_NUMBER} + $P{PREVIOUS_PAGE_NUMBER})]></textFieldExpression>

You have to use String.valueOf() method because if you use the simple sum of the elements $V{PAGE_NUMBER} + $P{PREVIOUS_PAGE_NUMBER}, Jasper will process this as a sum of strings and will print the two numbers as concatenated. (e.g. will print 11 instead of 2)

In your java code create a variable to hold the number of previous pages and pass it to Jasper as parameter. Then fill the first report and simply add the size of the list that contains the report pages to prevPageNumber, and pass it as parameter to the second report and so on:

int prevPageNumber = 0;
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("PREVIOUS_PAGE_NUMBER", prevPageNumber);

// fill the first report with prevPageNumber = 0
JasperPrint jasperPrint1 = JasperFillManager.fillReport(report1, paramMap);

if(jasperPrint1 != null && jasperPrint1.getPages() != null)
{
    // add previous report page number
    prevPageNumber += jasperPrint1.getPages().size();
}

paramMap.put("PREVIOUS_PAGE_NUMBER", prevPageNumber);
JasperPrint jasperPrint2 = JasperFillManager.fillReport(report2, paramMap);

I wrote this inline to respect the structure OP used in the question, but of course is better to do this in a loop if you have more than 2 report to print.


问:
T-SQL hierarchy from two tables to a single view
Hi there i am trying to make a view that holds the (mafia) hierarchy (up to 5 levels) from a single table for each and every user with an additional table to fill in the name of each user, this is the actual structure, i am using windows azure.

```<code>              [ 1 ]
             /  |  \
        [ 2 ]  [3]  [4]
        / |  \      |  \
     [5] [11] [12] [10]  [9]
      /\                   \
    [6] [8]                [15]
   /    /\                 /  \
[7]  [13] [14]         [17]    [16]
      |   |
     [19] [18]
     / \
  [20] [21]
</code>```

These are the table's that i get the data from:

```<code>dbo.userFamily                  dbo.user
id | user_id | parent_id        id_user   |   name
------------------------        ------------------
1  | 2       | 1                1         |   Victor
2  | 3       | 1                2         |   Lucifer
3  | 4       | 1                3         |   Hellboy
4  | 11      | 2                4         |   Spiderman
5  | 12      | 2                5         |   Martin
6  | 10      | 4                6         |   Superwoman
7  | 9       | 4                7         |   Lex Luther
8  | 15      | 9                8         |   GodMaster
9  | 17      | 15               9         |   Demon
10 | 16      | 15               10        |   balou
11 | 6       | 5                11        |   Superman
12 | 8       | 5                12        |   xman
13 | 7       | 6                13        |   hulk
14 | 13      | 8                14        |   ironman
15 | 14      | 8                15        |   aquaman
16 | 19      | 13               16        |   wonderwoman
17 | 20      | 19               17        |   batman
18 | 21      | 19               18        |   robin
19 | 18      | 14               19        |   tiger
20 | 1       | NULL             20        |   oscar
</code>```

And this is the part i have so far:

```<code> SELECT dbo.UserFamily.id, dbo.UserFamily.user_id, dbo.[User].name AS capo,
 dbo.UserFamily.parent_id AS Capo_id, NULL AS underboss,
 NULL AS underboss_id, NULL AS consigliere, NULL AS consigliere_id,
 NULL AS godfather, NULL AS godfather_id
 FROM dbo.UserFamily
 INNER JOIN dbo.[User] ON dbo.UserFamily.parent_id = dbo.[User].id_user
 ORDER BY dbo.UserFamily.user_id
</code>```

this is the view i try to make (somehow user_id 1 is missing, what i think has to do with the fact there is no parent_id):

```<code>id | user_id | capo       | capo_id | underboss | underboss_id | etc.     | etc.
-----------------------------------------------------------------------------
1  | 2       | Victor     | 1       | NULL      | NULL         | NULL
2  | 3       | Victor     | 1       | NULL      | NULL         | NULL
3  | 4       | Victor     | 1       | NULL      | NULL         | NULL
11 | 6       | Martin     | 5       | Lucifer   | 2            | Ewald
13 | 7       | Superwoman | 6       | Martin    | 5            | Lucifer  | 2
12 | 8       | Martin     | 5       | Martin    | 5            | Lucifer  | 2
</code>```

But how do i get the other ones? Like the underboss etc. all the way up to the godfather? This is the family structure:

```<code>soldier (the user)
capo
underboss
consigliere
godfather
</code>```

答:
Recursive CTEs are the trick for building hierarchies like this. Here's a cool trick for rendering the hierarchy as a string:

```<code>;WITH cteBosses AS
(
    SELECT id_user, CAST(null AS VARCHAR(100)) AS parent_name, uf.parent_id,
        name, 1 AS level, cast(name AS VARCHAR(MAX)) AS hierarchy
    FROM [dbo.user] u
    INNER JOIN dbo.userFamily uf ON u.id_user = uf.user_id
    WHERE uf.parent_id IS NULL
    UNION ALL
    SELECT u.id_user, CAST(c.name AS VARCHAR(100)) AS parent_name, uf.parent_id,
        u.name, c.level + 1 AS level, cast(c.hierarchy + ' -> ' + u.name AS VARCHAR(MAX)) AS hierarchy
    FROM [dbo.user] u
    INNER JOIN dbo.userFamily uf ON u.id_user = uf.user_id
    INNER JOIN cteBosses c ON uf.parent_id = c.id_user
)
SELECT *
FROM cteBosses
ORDER BY hierarchy
</code>```

This outputs:

```<code>id_user parent      name         parent_id   level  hierarchy
1       NULL        Victor       1           1      Victor
3       Victor      Hellboy      1           2      Victor -> Hellboy
2       Victor      Lucifer      2           2      Victor -> Lucifer
5       Lucifer     Martin       5           3      Victor -> Lucifer -> Martin
8       Martin      GodMaster    8           4      Victor -> Lucifer -> Martin -> GodMaster
13      GodMaster   hulk         13          5      Victor -> Lucifer -> Martin -> GodMaster -> hulk
19      hulk        tiger        19          6      Victor -> Lucifer -> Martin -> GodMaster -> hulk -> tiger
etc.
</code>```

Read Steve Stedman's "Common Table Expressions Joes 2 Pros" for lots of great CTE examples like this. http://stevestedman.com/2013/06/cte-scope/

To generate the output you want, you can join the CTE to itself as many times as you need to, like this:

```<code>;WITH cteBosses AS
(
    SELECT id_user, CAST(null AS VARCHAR(100)) AS parent_name, uf.parent_id,
        name, 1 AS level, cast(name AS VARCHAR(MAX)) AS hierarchy
    FROM [dbo.user] u
    INNER JOIN dbo.userFamily uf ON u.id_user = uf.user_id
    WHERE uf.parent_id IS NULL
    UNION ALL
    SELECT u.id_user, CAST(c.name as VARCHAR(100)) AS parent_name, uf.parent_id,
        u.name, c.level + 1 AS level, cast(c.hierarchy + ' -> ' + u.name AS VARCHAR(MAX)) AS hierarchy
    FROM [dbo.user] u
    INNER JOIN dbo.userFamily uf ON u.id_user = uf.user_id
    INNER JOIN cteBosses c ON uf.parent_id = c.id_user
)
SELECT c1.id_user, c1.name, c2.id_user as capo_id, c2.name as capo,
    c3.id_user as underboss_id, c3.name as underboss,
    c4.id_user as next_boss_id, c4.name as next_boss
FROM cteBosses c1
LEFT JOIN cteBosses c2 ON c1.parent_id = c2.id_user
LEFT JOIN cteBosses c3 ON c2.parent_id = c3.id_user
LEFT JOIN cteBosses c4 ON c3.parent_id = c4.id_user

id_user name        capo_id capo        underboss_id    underboss   next_boss_id    next_boss
1       Victor      NULL    NULL        NULL            NULL        NULL            NULL
2       Lucifer     1       Victor      NULL            NULL        NULL            NULL
3       Hellboy     1       Victor      NULL            NULL        NULL            NULL
4       Spiderman   1       Victor      NULL            NULL        NULL            NULL
9       Demon       4       Spiderman   1               Victor      NULL            NULL
10      balou       4       Spiderman   1               Victor      NULL            NULL
15      aquaman     9       Demon       4               Spiderman   1               Victor
16      wonderwoman 15      aquaman     9               Demon       4               Spiderman
17      batman      15      aquaman     9               Demon       4               Spiderman
</code>```

To answer your follow up question about adding the CurrentPosition column, you can nest another CTE and use it for your EXISTS clause:

```<code>;WITH cteBosses AS
(
    SELECT id_user, CAST(null AS VARCHAR(100)) AS parent_name, uf.parent_id,
        name, 1 AS level, cast(name AS VARCHAR(MAX)) AS hierarchy, id_user as top_parent, name as top_parent_name
    FROM [dbo.user] u
    INNER JOIN dbo.userFamily uf ON u.id_user = uf.user_id
    WHERE uf.parent_id IS NULL
    UNION ALL
    SELECT u.id_user, CAST(c.name as VARCHAR(100)) AS parent_name, uf.parent_id,
        u.name, c.level + 1 AS level, cast(c.hierarchy + ' -> ' + u.name AS VARCHAR(MAX)) AS hierarchy,
        c.top_parent, c.top_parent_name
    FROM [dbo.user] u
    INNER JOIN dbo.userFamily uf ON u.id_user = uf.user_id
    INNER JOIN cteBosses c ON uf.parent_id = c.id_user
)
, cteHierarchy AS
(
    SELECT c1.id_user, c1.name, c2.id_user as capo_id, c2.name as capo,
        c3.id_user as underboss_id, c3.name as underboss,
        c4.id_user as next_boss_id, c4.name as next_boss
    FROM cteBosses c1
    LEFT JOIN cteBosses c2 ON c1.parent_id = c2.id_user
    LEFT JOIN cteBosses c3 ON c2.parent_id = c3.id_user
    LEFT JOIN cteBosses c4 ON c3.parent_id = c4.id_user
)
select id_user, name, --*,
case
    when exists (select * from cteHierarchy cInner where next_boss = cOuter.name) then 'next_boss'
    when exists (select * from cteHierarchy cInner where underboss = cOuter.name) then 'underboss'
    when exists (select * from cteHierarchy cInner where capo = cOuter.name) then 'capo'
    else 'regular_dude'
end as CurrentPosition
from cteHierarchy cOuter

id_user   name      CurrentPosition
1         Victor    next_boss
4         Spiderman next_boss
9         Demon     underboss
</code>```

You can keep adding levels of CTEs like this - a CTE can reference the CTEs that come before it (but not after). So you're basically giving a table alias to the query output and then using EXISTS to compute the CurrentPosition value.

Body:
Hi there i am trying to make a view that holds the (mafia) hierarchy (up to 5 levels) from a single table for each and every user with an additional table to fill in the name of each user, this is the actual structure, i am using windows azure.

              [ 1 ]
             /  |  \
        [ 2 ]  [3]  [4]
        / |  \      |  \
     [5] [11] [12] [10]  [9]
      /\                   \
    [6] [8]                [15]
   /    /\                 /  \
[7]  [13] [14]         [17]    [16]
      |   |
     [19] [18]
     / \
  [20] [21]

These are the table's that i get the data from:

dbo.userFamily                  dbo.user
id | user_id | parent_id        id_user   |   name
------------------------        ------------------
1  | 2       | 1                1         |   Victor
2  | 3       | 1                2         |   Lucifer
3  | 4       | 1                3         |   Hellboy
4  | 11      | 2                4         |   Spiderman
5  | 12      | 2                5         |   Martin
6  | 10      | 4                6         |   Superwoman
7  | 9       | 4                7         |   Lex Luther
8  | 15      | 9                8         |   GodMaster
9  | 17      | 15               9         |   Demon
10 | 16      | 15               10        |   balou
11 | 6       | 5                11        |   Superman
12 | 8       | 5                12        |   xman
13 | 7       | 6                13        |   hulk
14 | 13      | 8                14        |   ironman
15 | 14      | 8                15        |   aquaman
16 | 19      | 13               16        |   wonderwoman
17 | 20      | 19               17        |   batman
18 | 21      | 19               18        |   robin
19 | 18      | 14               19        |   tiger
20 | 1       | NULL             20        |   oscar

And this is the part i have so far:

 SELECT dbo.UserFamily.id, dbo.UserFamily.user_id, dbo.[User].name AS capo,
 dbo.UserFamily.parent_id AS Capo_id, NULL AS underboss,
 NULL AS underboss_id, NULL AS consigliere, NULL AS consigliere_id,
 NULL AS godfather, NULL AS godfather_id
 FROM dbo.UserFamily
 INNER JOIN dbo.[User] ON dbo.UserFamily.parent_id = dbo.[User].id_user
 ORDER BY dbo.UserFamily.user_id

this is the view i try to make (somehow user_id 1 is missing, what i think has to do with the fact there is no parent_id):

id | user_id | capo       | capo_id | underboss | underboss_id | etc.     | etc.
-----------------------------------------------------------------------------
1  | 2       | Victor     | 1       | NULL      | NULL         | NULL
2  | 3       | Victor     | 1       | NULL      | NULL         | NULL
3  | 4       | Victor     | 1       | NULL      | NULL         | NULL
11 | 6       | Martin     | 5       | Lucifer   | 2            | Ewald
13 | 7       | Superwoman | 6       | Martin    | 5            | Lucifer  | 2
12 | 8       | Martin     | 5       | Martin    | 5            | Lucifer  | 2

But how do i get the other ones? Like the underboss etc. all the way up to the godfather? This is the family structure:

soldier (the user)
capo
underboss
consigliere
godfather

Body:
Recursive CTEs are the trick for building hierarchies like this. Here's a cool trick for rendering the hierarchy as a string:

;WITH cteBosses AS
(
    SELECT id_user, CAST(null AS VARCHAR(100)) AS parent_name, uf.parent_id,
        name, 1 AS level, cast(name AS VARCHAR(MAX)) AS hierarchy
    FROM [dbo.user] u
    INNER JOIN dbo.userFamily uf ON u.id_user = uf.user_id
    WHERE uf.parent_id IS NULL
    UNION ALL
    SELECT u.id_user, CAST(c.name AS VARCHAR(100)) AS parent_name, uf.parent_id,
        u.name, c.level + 1 AS level, cast(c.hierarchy + ' -> ' + u.name AS VARCHAR(MAX)) AS hierarchy
    FROM [dbo.user] u
    INNER JOIN dbo.userFamily uf ON u.id_user = uf.user_id
    INNER JOIN cteBosses c ON uf.parent_id = c.id_user
)
SELECT *
FROM cteBosses
ORDER BY hierarchy

This outputs:

id_user parent      name         parent_id   level  hierarchy
1       NULL        Victor       1           1      Victor
3       Victor      Hellboy      1           2      Victor -> Hellboy
2       Victor      Lucifer      2           2      Victor -> Lucifer
5       Lucifer     Martin       5           3      Victor -> Lucifer -> Martin
8       Martin      GodMaster    8           4      Victor -> Lucifer -> Martin -> GodMaster
13      GodMaster   hulk         13          5      Victor -> Lucifer -> Martin -> GodMaster -> hulk
19      hulk        tiger        19          6      Victor -> Lucifer -> Martin -> GodMaster -> hulk -> tiger
etc.

Read Steve Stedman's "Common Table Expressions Joes 2 Pros" for lots of great CTE examples like this. http://stevestedman.com/2013/06/cte-scope/

To generate the output you want, you can join the CTE to itself as many times as you need to, like this:

;WITH cteBosses AS
(
    SELECT id_user, CAST(null AS VARCHAR(100)) AS parent_name, uf.parent_id,
        name, 1 AS level, cast(name AS VARCHAR(MAX)) AS hierarchy
    FROM [dbo.user] u
    INNER JOIN dbo.userFamily uf ON u.id_user = uf.user_id
    WHERE uf.parent_id IS NULL
    UNION ALL
    SELECT u.id_user, CAST(c.name as VARCHAR(100)) AS parent_name, uf.parent_id,
        u.name, c.level + 1 AS level, cast(c.hierarchy + ' -> ' + u.name AS VARCHAR(MAX)) AS hierarchy
    FROM [dbo.user] u
    INNER JOIN dbo.userFamily uf ON u.id_user = uf.user_id
    INNER JOIN cteBosses c ON uf.parent_id = c.id_user
)
SELECT c1.id_user, c1.name, c2.id_user as capo_id, c2.name as capo,
    c3.id_user as underboss_id, c3.name as underboss,
    c4.id_user as next_boss_id, c4.name as next_boss
FROM cteBosses c1
LEFT JOIN cteBosses c2 ON c1.parent_id = c2.id_user
LEFT JOIN cteBosses c3 ON c2.parent_id = c3.id_user
LEFT JOIN cteBosses c4 ON c3.parent_id = c4.id_user

id_user name        capo_id capo        underboss_id    underboss   next_boss_id    next_boss
1       Victor      NULL    NULL        NULL            NULL        NULL            NULL
2       Lucifer     1       Victor      NULL            NULL        NULL            NULL
3       Hellboy     1       Victor      NULL            NULL        NULL            NULL
4       Spiderman   1       Victor      NULL            NULL        NULL            NULL
9       Demon       4       Spiderman   1               Victor      NULL            NULL
10      balou       4       Spiderman   1               Victor      NULL            NULL
15      aquaman     9       Demon       4               Spiderman   1               Victor
16      wonderwoman 15      aquaman     9               Demon       4               Spiderman
17      batman      15      aquaman     9               Demon       4               Spiderman

To answer your follow up question about adding the CurrentPosition column, you can nest another CTE and use it for your EXISTS clause:

;WITH cteBosses AS
(
    SELECT id_user, CAST(null AS VARCHAR(100)) AS parent_name, uf.parent_id,
        name, 1 AS level, cast(name AS VARCHAR(MAX)) AS hierarchy, id_user as top_parent, name as top_parent_name
    FROM [dbo.user] u
    INNER JOIN dbo.userFamily uf ON u.id_user = uf.user_id
    WHERE uf.parent_id IS NULL
    UNION ALL
    SELECT u.id_user, CAST(c.name as VARCHAR(100)) AS parent_name, uf.parent_id,
        u.name, c.level + 1 AS level, cast(c.hierarchy + ' -> ' + u.name AS VARCHAR(MAX)) AS hierarchy,
        c.top_parent, c.top_parent_name
    FROM [dbo.user] u
    INNER JOIN dbo.userFamily uf ON u.id_user = uf.user_id
    INNER JOIN cteBosses c ON uf.parent_id = c.id_user
)
, cteHierarchy AS
(
    SELECT c1.id_user, c1.name, c2.id_user as capo_id, c2.name as capo,
        c3.id_user as underboss_id, c3.name as underboss,
        c4.id_user as next_boss_id, c4.name as next_boss
    FROM cteBosses c1
    LEFT JOIN cteBosses c2 ON c1.parent_id = c2.id_user
    LEFT JOIN cteBosses c3 ON c2.parent_id = c3.id_user
    LEFT JOIN cteBosses c4 ON c3.parent_id = c4.id_user
)
select id_user, name, --*,
case
    when exists (select * from cteHierarchy cInner where next_boss = cOuter.name) then 'next_boss'
    when exists (select * from cteHierarchy cInner where underboss = cOuter.name) then 'underboss'
    when exists (select * from cteHierarchy cInner where capo = cOuter.name) then 'capo'
    else 'regular_dude'
end as CurrentPosition
from cteHierarchy cOuter

id_user   name      CurrentPosition
1         Victor    next_boss
4         Spiderman next_boss
9         Demon     underboss

You can keep adding levels of CTEs like this - a CTE can reference the CTEs that come before it (but not after). So you're basically giving a table alias to the query output and then using EXISTS to compute the CurrentPosition value.


问:
Reading and capturing the ACL
I have been asked to write an application that will allow a user to select a database and have it read and store the ACL (including Roles) into a document. I haven't been able to find any way that let's you scan an ACL and capture the contents like that. </p>

答:
You can access the ACL of a database through the Database class in Java. There is a getAcl() method for that. Once you have the ACL you can loop through all the entries.

Every AclEntry object has methods to get the access level, roles, etc.

Title: Reading and capturing the ACL


问:
Jquery tagsinput not creating tags automatically on pasting input
I'm using jquery.tagsinput and would like to be able to paste a list of email addresses separated by comma or space. Using something like this https://github.com/xoxco/jQuery-Tags-Input/issues/22 but it doesn't add them until I press Enter - Tried triggering keypress Enter event but it doesn't work. No luck with blur event either (shown below). Any ideas?

The Flat-UI tags are based on this library and I'm trying to achieve a very similar behaviour.

```<code>var tidyTags = function(e) {
  var tags = (e.tags).split(/[ ,]+/);
  var target = $(e.target);

  for (var i = 0, z = tags.length; i<z; i++) {
      var tag = $.trim(tags[i]);
      if (!target.tagExist(tag)) {
          target.addTag(tag);
      }
  }
  $('#' + target[0].id + '_tag').trigger('focus');

  //This doesn't work.
  target.blur();

};

$("#tagsinput").tagsInput({
    onAddTag : function(tag){
      if(tag.indexOf(',') > 0) {
          tidyTags({target: '#tagsinput', tags : tag});
      }
    },
});
</code>```

答:
Thanks a lot for this inspiring solution !

I had some issues with the code above. I was using angularjs and didn't want to access the elements by ID.

Here is what worked for me in a directive declaration, in case someone might be insterested :

```<code>link: function(scope, el, attr){

    /* initializing element */
    var $el = angular.element(el);
    $el.tagsinput({...}); //<-- initialize as desired

    /* getting the "_tag" input  */
    var $elTag = $el.tagsinput('input');

    /* attaching event to "_tag" input */
    $elTag.on('paste', function (e) {
        var element = this;
        setTimeout(function () {
            var text = $(element).val();
            var target = $el;
            $elTag.val(''); // <--- removes the pasted value containing the ","
            var tags = (text).split(/[ ,]+/);
            for (var i = 0, z = tags.length; i < z; i++) {
                var tag = $.trim(tags[i]);
                if(target.tagsinput('items').indexOf(tag) < 0){ // <-- I got "'tagExist' not a function" error
                    target.tagsinput('add',tag);
                }
            }
        }, 0);
    });
}
</code>```

Body:
I'm using jquery.tagsinput and would like to be able to paste a list of email addresses separated by comma or space. Using something like this https://github.com/xoxco/jQuery-Tags-Input/issues/22 but it doesn't add them until I press Enter - Tried triggering keypress Enter event but it doesn't work. No luck with blur event either (shown below). Any ideas?

The Flat-UI tags are based on this library and I'm trying to achieve a very similar behaviour.

var tidyTags = function(e) {
  var tags = (e.tags).split(/[ ,]+/);
  var target = $(e.target);

  for (var i = 0, z = tags.length; i<z; i++) {
      var tag = $.trim(tags[i]);
      if (!target.tagExist(tag)) {
          target.addTag(tag);
      }
  }
  $('#' + target[0].id + '_tag').trigger('focus');

  //This doesn't work.
  target.blur();

};

$("#tagsinput").tagsInput({
    onAddTag : function(tag){
      if(tag.indexOf(',') > 0) {
          tidyTags({target: '#tagsinput', tags : tag});
      }
    },
});

Body:
Thanks a lot for this inspiring solution !

I had some issues with the code above. I was using angularjs and didn't want to access the elements by ID.

Here is what worked for me in a directive declaration, in case someone might be insterested :

link: function(scope, el, attr){

    /* initializing element */
    var $el = angular.element(el);
    $el.tagsinput({...}); //<-- initialize as desired

    /* getting the "_tag" input  */
    var $elTag = $el.tagsinput('input');

    /* attaching event to "_tag" input */
    $elTag.on('paste', function (e) {
        var element = this;
        setTimeout(function () {
            var text = $(element).val();
            var target = $el;
            $elTag.val(''); // <--- removes the pasted value containing the ","
            var tags = (text).split(/[ ,]+/);
            for (var i = 0, z = tags.length; i < z; i++) {
                var tag = $.trim(tags[i]);
                if(target.tagsinput('items').indexOf(tag) < 0){ // <-- I got "'tagExist' not a function" error
                    target.tagsinput('add',tag);
                }
            }
        }, 0);
    });
}