问:
In C language binary file io
if I input a binary file to array buf, why do I have to input it by (void*) ??
and why do I have to write it by (void*)?? please observe this code and please explain this code to me. (I just copy this code from my book)

```<code>int main(void) {
FILE * src = fopen("a.png", "rb");
FILE * des = fopen("b.png", "wb");

char buf[20];
int readCnt;

if (src == NULL || des == NULL) {
    puts("File open failed");
    return -1;
}

while (1) {
    readCnt = fread((void*)buf, 1, sizeof(buf), src);

    if (readCnt < sizeof(buf)) {
        if (feof(src) != 0) {
            fwrite((void*)buf, 1, readCnt, des);
            puts("File copy complete");
            break;
        }
        else
            puts("File copy Failed");

        break;
    }
    fwrite((void*)buf, 1, sizeof(buf), des);
}
fclose(src);
fclose(des);
return 0;
</code>```

}

答:
The cast to void* is because this is what the functions expect. See here and here.

Your code will compile without this cast, because cast to void* is not necessary (see quote below), but I guess the author wanted to be exact as possible.

6.3.2.3 Pointers

1 A pointer to void may be converted to or from a pointer to any incomplete or object type. A pointer to any incomplete or object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

Another thing - (void*) is a good way to suppress compiler warnings. It may not be a good thing to begin with (warning are there for a reason), but if need be, this is a simple way to ignore wrong pointer type in function arguments.

Title: In C language binary file io

Body:
if I input a binary file to array buf, why do I have to input it by (void*) ??
and why do I have to write it by (void*)?? please observe this code and please explain this code to me. (I just copy this code from my book)

int main(void) {
FILE * src = fopen("a.png", "rb");
FILE * des = fopen("b.png", "wb");

char buf[20];
int readCnt;

if (src == NULL || des == NULL) {
    puts("File open failed");
    return -1;
}

while (1) {
    readCnt = fread((void*)buf, 1, sizeof(buf), src);

    if (readCnt < sizeof(buf)) {
        if (feof(src) != 0) {
            fwrite((void*)buf, 1, readCnt, des);
            puts("File copy complete");
            break;
        }
        else
            puts("File copy Failed");

        break;
    }
    fwrite((void*)buf, 1, sizeof(buf), des);
}
fclose(src);
fclose(des);
return 0;

}


来源: stackexchange

问:
How to correctly include jquery-ui effects on wordpress
I've been trying to include the jquery ui effects (more specifically the shake effect) on my wordpress theme. So far, I've only been able to include the jQuery script, but I really have no clue where to place the ui scripts and how to enqueue them.

This is the code I have. It obviously doesnt work:

```<code>    <?php wp_enqueue_script("jquery"); ?>
<?php wp_enqueue_script("jquery-ui-core"); ?>
<?php wp_head(); ?>
<link rel="stylesheet" type="text/css" href="<?php bloginfo('stylesheet_url'); ?>" />
<script type="text/javascript">
    var $j = jQuery.noConflict();
    $j(document).ready(function() {
        $j("#manita-imagen").mouseover(function(){
            //$j(this).animate({ opacity: "hide" })
            // alert('asd');
            $j(this).effect("shake", { times:3 }, 300);
        });
    });

 </script>
</code>```

Thanks for your help!

答:
It might be possible that the jquery-ui-core included with wordpress does not include Effects. The documentation is unclear(http://codex.wordpress.org/Function_Reference/wp_enqueue_script#Default_scripts_included_with_WordPress) You might have to load a custom jquery-ui package from a url. Below will load full jquery UI from google cdn

<?php wp_enqueue_script("myUi","https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.8/jquery-ui.min.js"); ?>

You can also use the  wp_enqueue_script($name, $src) function to load your own scripts.

ContentLicense: CC BY-SA 2.5

Body:
I've been trying to include the jquery ui effects (more specifically the shake effect) on my wordpress theme. So far, I've only been able to include the jQuery script, but I really have no clue where to place the ui scripts and how to enqueue them.

This is the code I have. It obviously doesnt work:

    <?php wp_enqueue_script("jquery"); ?>
<?php wp_enqueue_script("jquery-ui-core"); ?>
<?php wp_head(); ?>
<link rel="stylesheet" type="text/css" href="<?php bloginfo('stylesheet_url'); ?>" />

Thanks for your help!


问:
How to remove all the spaces and \n\r in a String?
What is the most efficient way to remove all the spaces, \n and \r in a String in Swift?

I have tried:

```<code>for character in string.characters {

}
</code>```

But it's a little inconvenient.

答:
Swift 4:</p>

```<code>let text = "This \n is a st\tri\rng"
let cleanedText = text.filter { !" \n\t\r".characters.contains($0) }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
What is the most efficient way to remove all the spaces, \n and \r in a String in Swift?

I have tried:

for character in string.characters {

}

But it's a little inconvenient.

Body:
Swift 4:

let text = "This \n is a st\tri\rng"
let cleanedText = text.filter { !" \n\t\r".characters.contains($0) }


问:
How to recursively merge two objects?
I have the following two objects:

```<code>var objectA = {
    "a": [
        {
            "col": 1,
            "row": 1,
            "pnl": 1.0
        },
        {
            "col": 1,
            "row": 2,
            "pnl": 2.0
        },
    ]
};

var objectB = {
    "a": [
        {
            "col": 1,
            "row": 1,
            "sharpe": 1.5
        },
        {
            "col": 1,
            "row": 2,
            "sharpe": 2.5
        },
    ]
};
</code>```

and I'd like to get:

```<code>var objectC = {
    "a": [
        {
            "col": 1,
            "row": 1,
            "pnl": 1.0,
            "sharpe": 1.5
        },
        {
            "col": 1,
            "row": 2,
            "pnl": 2.0,
            "sharpe": 2.5
        },
    ]
};
</code>```

答:
You could use a hash table for reference to the same key and col/row items. Then update the object or assign the new object if no hash is available.

var objectA = { a: [{ col: 1, row: 1, pnl: 1.0 }, { col: 1, row: 2, pnl: 2.0 }] },
    objectB = { a: [{ col: 1, row: 1, sharpe: 1.5 }, { col: 1, row: 2, sharpe: 2.5 }] },
    hash = Object.create(null);

Object.keys(objectA).forEach(function (k) {
    hash[k] = hash[k] || {};
    objectA[k].forEach(function (o) {
        var key = ['col', 'row'].map(function (l) { return o[l]; }).join('|');
        hash[k][key] = o;
    });
});

Object.keys(objectB).forEach(function (k) {
    if (!hash[k]) {
        objectA[k] = objectB[k];
        return;
    }
    objectB[k].forEach(function (o) {
        var key = ['col', 'row'].map(function (l) { return o[l]; }).join('|');
        if (hash[k][key]) {
            Object.keys(o).forEach(function (l) {
                hash[k][key][l] = o[l];
            });
        } else {
            objectA[k].push(o);
        }
    });
});

console.log(objectA);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: How to recursively merge two objects?

Body:
I have the following two objects:

var objectA = {
    "a": [
        {
            "col": 1,
            "row": 1,
            "pnl": 1.0
        },
        {
            "col": 1,
            "row": 2,
            "pnl": 2.0
        },
    ]
};

var objectB = {
    "a": [
        {
            "col": 1,
            "row": 1,
            "sharpe": 1.5
        },
        {
            "col": 1,
            "row": 2,
            "sharpe": 2.5
        },
    ]
};

and I'd like to get:

var objectC = {
    "a": [
        {
            "col": 1,
            "row": 1,
            "pnl": 1.0,
            "sharpe": 1.5
        },
        {
            "col": 1,
            "row": 2,
            "pnl": 2.0,
            "sharpe": 2.5
        },
    ]
};

Body:
You could use a hash table for reference to the same key and col/row items. Then update the object or assign the new object if no hash is available.

var objectA = { a: [{ col: 1, row: 1, pnl: 1.0 }, { col: 1, row: 2, pnl: 2.0 }] },
    objectB = { a: [{ col: 1, row: 1, sharpe: 1.5 }, { col: 1, row: 2, sharpe: 2.5 }] },
    hash = Object.create(null);

Object.keys(objectA).forEach(function (k) {
    hash[k] = hash[k] || {};
    objectA[k].forEach(function (o) {
        var key = ['col', 'row'].map(function (l) { return o[l]; }).join('|');
        hash[k][key] = o;
    });
});

Object.keys(objectB).forEach(function (k) {
    if (!hash[k]) {
        objectA[k] = objectB[k];
        return;
    }
    objectB[k].forEach(function (o) {
        var key = ['col', 'row'].map(function (l) { return o[l]; }).join('|');
        if (hash[k][key]) {
            Object.keys(o).forEach(function (l) {
                hash[k][key][l] = o[l];
            });
        } else {
            objectA[k].push(o);
        }
    });
});

console.log(objectA);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Efficient method for building a promise object
At the moment what I have is this :

```<code>    getData(user) {
     return this.$q.all({
        userInfo: this.$http.get(this.buildUrl('user.getinfo', user)),
        userTopArtists: this.$http.get(this.buildUrl('user.gettopartists', user)),
        userChart: this.$http.get(this.buildUrl('user.getWeeklyChartList', user))
            .then(resp => {
                let promises = [];
                let data = resp.data.weeklychartlist.chart;
                for (let i = data.length - 4; i < data.length; i++) {
                    promises.push(
                        this.$http.get(this.buildUrl('user.getWeeklyTrackChart', user) + `&from=${data[i].from}&to=${data[i].to}`)
                        .then(resp => {
                            return resp.data.weeklytrackchart.track.length;
                        })
                    );
                }

                return this.$q.all(promises);
            })
    }).then(resp => {
        return resp;
    }).catch(err => {
        this.$q.reject('Error' + err.status);
    })
}
</code>```

But I'm thinking there may be a more functional approach to building this promise object, because a lot of code is getting repeated. So I tried to come up with a better solution:

```<code>    buildPromiseObj(target) {
     const methods = ['getinfo', 'gettopartists', 'getweeklychartlist'];
     let obj = {};
     for ( let method in methods ) {
        obj[`${methods[method]}`] = this.$http.get(this.buildUrl(`${target}.${methods[method]}`, target))
    }
}
</code>```

Does this approach make sense and should I use it ?

You can see that the 3rd request I make in the first function has other nested requests. Is there any way I can integrate that in the approach I've written above ?

答:
As a first pass, here's what I would do with it.

const { $http: { get }, $q: { all } } = this,
      // convert { x: 'a', y: 'b' } to '&x=a&y=b'
      paramStr = obj => Object.entries(obj).map(([k,v]) => `&${k}=${v}`).join(), // You might not have Object#entries; it's new

      getUrl = (target, method, params={}) => this.buildUrl(`user.get${method}`, target) + paramStr(params),

      getData = user => all(Object.assign({},
        ...['info', 'topartists', 'WeeklyChartList'].map(m => get(getUrl(user, m)))
      ))
        .then(([ userInfo, userTopArtists, { data: { weeklychartlist: { chart } } } ]) =>
          all({
            userInfo,
            userTopArtists,
            userChart: all([
                ...chart.slice(-4)
                  .map(({ from, to }) =>
                    get(getUrl(target, 'WeeklyTrackChart', { from, to }))
                      .then(({ data: { weeklytrackchart: { track: { length } } } }) => length)
                  )
              ])
          })
        )
        .catch(({ status }) => this.$q.reject(`Error${status}`));```

I'm keeping your code functionally the same, though Bergi's recommendations are good ones.

Body:
At the moment what I have is this :

    getData(user) {
     return this.$q.all({
        userInfo: this.$http.get(this.buildUrl('user.getinfo', user)),
        userTopArtists: this.$http.get(this.buildUrl('user.gettopartists', user)),
        userChart: this.$http.get(this.buildUrl('user.getWeeklyChartList', user))
            .then(resp => {
                let promises = [];
                let data = resp.data.weeklychartlist.chart;
                for (let i = data.length - 4; i < data.length; i++) {
                    promises.push(
                        this.$http.get(this.buildUrl('user.getWeeklyTrackChart', user) + `&from=${data[i].from}&to=${data[i].to}`)
                        .then(resp => {
                            return resp.data.weeklytrackchart.track.length;
                        })
                    );
                }

                return this.$q.all(promises);
            })
    }).then(resp => {
        return resp;
    }).catch(err => {
        this.$q.reject('Error' + err.status);
    })
}

But I'm thinking there may be a more functional approach to building this promise object, because a lot of code is getting repeated. So I tried to come up with a better solution:

    buildPromiseObj(target) {
     const methods = ['getinfo', 'gettopartists', 'getweeklychartlist'];
     let obj = {};
     for ( let method in methods ) {
        obj[`${methods[method]}`] = this.$http.get(this.buildUrl(`${target}.${methods[method]}`, target))
    }
}

Does this approach make sense and should I use it ?

You can see that the 3rd request I make in the first function has other nested requests. Is there any way I can integrate that in the approach I've written above ?

Body:
As a first pass, here's what I would do with it.

const { $http: { get }, $q: { all } } = this,
      // convert { x: 'a', y: 'b' } to '&x=a&y=b'
      paramStr = obj => Object.entries(obj).map(([k,v]) => `&${k}=${v}`).join(), // You might not have Object#entries; it's new

      getUrl = (target, method, params={}) => this.buildUrl(`user.get${method}`, target) + paramStr(params),

      getData = user => all(Object.assign({},
        ...['info', 'topartists', 'WeeklyChartList'].map(m => get(getUrl(user, m)))
      ))
        .then(([ userInfo, userTopArtists, { data: { weeklychartlist: { chart } } } ]) =>
          all({
            userInfo,
            userTopArtists,
            userChart: all([
                ...chart.slice(-4)
                  .map(({ from, to }) =>
                    get(getUrl(target, 'WeeklyTrackChart', { from, to }))
                      .then(({ data: { weeklytrackchart: { track: { length } } } }) => length)
                  )
              ])
          })
        )
        .catch(({ status }) => this.$q.reject(`Error${status}`));

I'm keeping your code functionally the same, though Bergi's recommendations are good ones.


问:
Syntax issues in OS detection
I'm working on a script using bash to determine the os being used and print to the screen the version.

The only line giving me issues is this one, could you please help me?:

答:
An alternative is to use

```<code>lsb_release -d
</code>```

for getting the distribution name, or

```<code>lsb_release -a
</code>```

to get all info about the distro.

More info about this linux standard base utility.

Title: Syntax issues in OS detection

Body:
An alternative is to use

lsb_release -d

for getting the distribution name, or

lsb_release -a

to get all info about the distro.

More info about this linux standard base utility.


问:
Need sample javascript object literal
I need a sample js object literal which can be accessed in the following way:

```<code>hist.undo[0].operation[0].x // would print '2' or whatever
hist.undo[0].operation[0].y // would print '21' or whatever
// [...]
hist.undo[2].operation[0].x // would print '32' or whatever
hist.undo[2].operation[0].y // would print '12' or whatever
</code>```

Thanks!

答:
(working jsfiddle example here)

```<code>var sample_operation_member = {"x": 100, "y": 250};
var sample_undo_member = { "operation" : [sample_operation_member, sample_operation_member,sample_operation_member] };

var hist = {
   "undo": [
      sample_undo_member,
      sample_undo_member,
      sample_undo_member,
      sample_undo_member
   ]
}

alert(hist.undo[0].operation[0].x);
</code>```

Or, more verbosely:

```<code>var hist = {
    undo: [
        {"operation": [{"x": 100, "y":100},{"x": 100, "y":100},{"x": 100, "y":100}]},
        {"operation": [{"x": 100, "y":100},{"x": 100, "y":100},{"x": 100, "y":100}]},
        {"operation": [{"x": 100, "y":100},{"x": 100, "y":100},{"x": 100, "y":100}]},
        {"operation": [{"x": 100, "y":100},{"x": 100, "y":100},{"x": 100, "y":100}]}
    ]
}

alert(hist.undo[0].operation[0].x);
</code>```

Title: Need sample javascript object literal

Body:
I need a sample js object literal which can be accessed in the following way:

hist.undo[0].operation[0].x // would print '2' or whatever
hist.undo[0].operation[0].y // would print '21' or whatever
// [...]
hist.undo[2].operation[0].x // would print '32' or whatever
hist.undo[2].operation[0].y // would print '12' or whatever

Thanks!

Body:
(working jsfiddle example here)

var sample_operation_member = {"x": 100, "y": 250};
var sample_undo_member = { "operation" : [sample_operation_member, sample_operation_member,sample_operation_member] };

var hist = {
   "undo": [
      sample_undo_member,
      sample_undo_member,
      sample_undo_member,
      sample_undo_member
   ]
}

alert(hist.undo[0].operation[0].x);

Or, more verbosely:

var hist = {
    undo: [
        {"operation": [{"x": 100, "y":100},{"x": 100, "y":100},{"x": 100, "y":100}]},
        {"operation": [{"x": 100, "y":100},{"x": 100, "y":100},{"x": 100, "y":100}]},
        {"operation": [{"x": 100, "y":100},{"x": 100, "y":100},{"x": 100, "y":100}]},
        {"operation": [{"x": 100, "y":100},{"x": 100, "y":100},{"x": 100, "y":100}]}
    ]
}

alert(hist.undo[0].operation[0].x);


问:
Cannot assign through subscript: 'dict' is a 'let' constant
I have a very simple problem with Swift.
I created this function:

```<code>var dictAges : [String: Int] = ["John":40, "Michael":20, "Bob": -16]

func correctAges(dict:[String:Int]) {
     for (name, age) in dict {
          guard age >= 0 else {
          dict[name] = 0
          continue
          }
     }
}
correctAges(dict:dictAges)
</code>```

But I don't understand the error:

"cannot assign through subscript: 'dict' is a 'let' constant, dict[name] = 0"

How can I solve it?

答:
Input arguments to functions are immutable inside the function body and a Dictionary is a value type, so the dict you see inside the function is actually a copy of the original dictAges. When you call a function with a value type as its input argument, that input argument is passed by value, not passed by reference, hence inside the function you cannot access the original variable.

Either declare the dict input argument as inout or if you'd prefer the more functional approach, return a mutated version of the dictionary from the function.

Functional approach:

```<code>var dictAges : [String: Int] = ["John":40, "Michael":20, "Bob": -16]

func correctAges(dict:[String:Int])->[String:Int] {
     var mutatedDict = dict
     for (name, age) in mutatedDict {
          guard age >= 0 else {
              mutatedDict[name] = 0
              continue
          }
     }
     return mutatedDict
}
let newDict = correctAges(dict:dictAges) //["Michael": 20, "Bob": 0, "John": 40]
</code>```

Inout version:

```<code>func correctAges(dict: inout [String:Int]){
    for (name,age) in dict {
        guard age >= 0 else {
            dict[name] = 0
            continue
        }
    }
}

correctAges(dict: &dictAges) //["Michael": 20, "Bob": 0, "John": 40]
</code>```

Body:
I have a very simple problem with Swift.
I created this function:

var dictAges : [String: Int] = ["John":40, "Michael":20, "Bob": -16]

func correctAges(dict:[String:Int]) {
     for (name, age) in dict {
          guard age >= 0 else {
          dict[name] = 0
          continue
          }
     }
}
correctAges(dict:dictAges)

But I don't understand the error:

"cannot assign through subscript: 'dict' is a 'let' constant, dict[name] = 0"

How can I solve it?

Body:
Input arguments to functions are immutable inside the function body and a Dictionary is a value type, so the dict you see inside the function is actually a copy of the original dictAges. When you call a function with a value type as its input argument, that input argument is passed by value, not passed by reference, hence inside the function you cannot access the original variable.

Either declare the dict input argument as inout or if you'd prefer the more functional approach, return a mutated version of the dictionary from the function.

Functional approach:

var dictAges : [String: Int] = ["John":40, "Michael":20, "Bob": -16]

func correctAges(dict:[String:Int])->[String:Int] {
     var mutatedDict = dict
     for (name, age) in mutatedDict {
          guard age >= 0 else {
              mutatedDict[name] = 0
              continue
          }
     }
     return mutatedDict
}
let newDict = correctAges(dict:dictAges) //["Michael": 20, "Bob": 0, "John": 40]

Inout version:

func correctAges(dict: inout [String:Int]){
    for (name,age) in dict {
        guard age >= 0 else {
            dict[name] = 0
            continue
        }
    }
}

correctAges(dict: &dictAges) //["Michael": 20, "Bob": 0, "John": 40]


答:
This is so that you can pass any pointer type. So for example, if you want to write a structure like for example

```<code>struct point {
    int x;
    int y;
};

struct point my_point = {1, 2};
FILE *file = fopen("sample-file.bin", "w");
if (file != NULL) {
    // Normally check that this returns the number of
    // written items
    fwrite(&my_point, 1, sizeof(my_point), file);
    fclose(file);
}
</code>```

would work, and when you open the file for reading you can fread(&my_point ...) too.

Note that casting to void * is not necessary in c, nor is it needed to cast from void * to another pointer type, for instance

```<code>char *example = malloc(size + 1);
</code>```

is perfectly valid and malloc() returns void *.

Title: In C language binary file io

Body:
This is so that you can pass any pointer type. So for example, if you want to write a structure like for example

struct point {
    int x;
    int y;
};

struct point my_point = {1, 2};
FILE *file = fopen("sample-file.bin", "w");
if (file != NULL) {
    // Normally check that this returns the number of
    // written items
    fwrite(&my_point, 1, sizeof(my_point), file);
    fclose(file);
}

would work, and when you open the file for reading you can fread(&my_point ...) too.

Note that casting to void * is not necessary in c, nor is it needed to cast from void * to another pointer type, for instance

char *example = malloc(size + 1);

is perfectly valid and malloc() returns void *.


问:
Redirect to a specific URL with Javascript
what i want to do is simple, let's say I have a URL like this https://www.example.com/pro?type=oil coming from the URL it could anything like /pro?type=beans or /pro?type=rice and what I want is to get the URL redirect it to something like this https://www.example.com/zpro?type=oil. PLEASE THE FIRST URL is /pro? the redirect location is /zpro? Thank you.

答:
If I understand what you want correctly, the below should do it.</p>

```<code>window.location.href = window.location.href.replace('/pro?', '/zpro?')
</code>```

Body:
If I understand what you want correctly, the below should do it.

window.location.href = window.location.href.replace('/pro?', '/zpro?')


问:
python key in dict.keys() performance for large dictionaries
I was wondering if you guys might be able to give me some advice in regards to making the performance of my code much better.

I have a set of for loops which look to see if a key is in a dictionary of which its values are a list, if the key exists, it appends to the list and if it doesnt it adds a new list in for that key

```<code>dict={}
for value in value_list:
   if value.key in dict.keys():
      temp_list = dict[value.key]
      temp_list.append(value.val)
      dict[value.key] = temp_list
   else:
      dict[value.key] = [value.val]
</code>```

Now this code works fine, but evenrually as the dictionary starts to fill up the line value.key in dict.keys() becomes more and more cumbersome.

Is there a better way of doing this?

Thanks,

Mike

答:
```<code>if value.key in dict.keys():
</code>```

Is very expensive because you're converting to a list of keys and then searching the list.  Just replacing that with:

```<code>if value.key in dict:
</code>```

Should shorten the search to ~log N (EDIT: I stand corrected by Glenn, probably even faster because the Python dictionaries use a hash table).  Then simply:

```<code>dict[key].append(value.val)
</code>```

Should speed things up a bit.  Using a temporary is not required and just eats some CPU cycles.

If you can give more details about what you're trying to do someone may be able to suggest a better algorithm.

Body:
I was wondering if you guys might be able to give me some advice in regards to making the performance of my code much better.

I have a set of for loops which look to see if a key is in a dictionary of which its values are a list, if the key exists, it appends to the list and if it doesnt it adds a new list in for that key

dict={}
for value in value_list:
   if value.key in dict.keys():
      temp_list = dict[value.key]
      temp_list.append(value.val)
      dict[value.key] = temp_list
   else:
      dict[value.key] = [value.val]

Now this code works fine, but evenrually as the dictionary starts to fill up the line value.key in dict.keys() becomes more and more cumbersome.

Is there a better way of doing this?

Thanks,

Mike

Body:
if value.key in dict.keys():

Is very expensive because you're converting to a list of keys and then searching the list.  Just replacing that with:

if value.key in dict:

Should shorten the search to ~log N (EDIT: I stand corrected by Glenn, probably even faster because the Python dictionaries use a hash table).  Then simply:

dict[key].append(value.val)

Should speed things up a bit.  Using a temporary is not required and just eats some CPU cycles.

If you can give more details about what you're trying to do someone may be able to suggest a better algorithm.


问:
Netbeans build-impl.xml messed up
My build-impl.xml file was messed up due to merge conflicts. I fixed the conflicts, but when I try an ant run, it throws Target "-do-jar-delete-manifest" does not exist in the project "PROJ". It is used from target "-do-jar-without-libraries". This is a Java FX project and we are using Java 8.

I would like to fix this by just creating a new build-impl.xml file. How can I do this in Netbeans? Thanks!

答: With the same problem, I had to delete both build-impl.xml and build.xml. After restarting NetBeans I could run my project.</p>

Title: Netbeans build-impl.xml messed up


问:
Initialise Java List in Scala with Java ArrayList
When being in scala and I write

```<code>val data: java.util.List[java.util.List[Double]] = new java.util.ArrayList[java.util.ArrayList[Double]]()
</code>```

I get the error

Expression of type util.ArrayList[util.ArrayList[Double]] does not conform to expected type util.List[util.List[Double]]

What am I doing wrong?

答:
My answer applies to Java but I guess that the reason is the same.

You are mixing polymorphism by subtype with generics. It's true that an ArrayList<T> can be assigned to a List<T> variable but here you have a List<List<T>> and you are trying to assign an object of type ArrayList<ArrayList<T>>.

But a List<E> is not a subtype of List<F> even if F is a subtype of E so this is not allowed directly (invariance), but Scala has tools to manage this issue (as Java has bounds and wildcards).

Body:
When being in scala and I write

val data: java.util.List[java.util.List[Double]] = new java.util.ArrayList[java.util.ArrayList[Double]]()

I get the error

Expression of type util.ArrayList[util.ArrayList[Double]] does not conform to expected type util.List[util.List[Double]]

What am I doing wrong?


答:
Because fread() & fwrite() are generic function for reading and writing binary data into file irrespective of their data type.

man page of fwrite() says,

```<code>size_t fwrite(const void *ptr, size_t size, size_t nmemb,
                     FILE *stream);
</code>```

what is first arguement, its const void *ptr means its expecting address. it can be any variable address int or char or any other data type .

Title: In C language binary file io

Body:
if I input a binary file to array buf, why do I have to input it by (void*) ??
and why do I have to write it by (void*)?? please observe this code and please explain this code to me. (I just copy this code from my book)

int main(void) {
FILE * src = fopen("a.png", "rb");
FILE * des = fopen("b.png", "wb");

char buf[20];
int readCnt;

if (src == NULL || des == NULL) {
    puts("File open failed");
    return -1;
}

while (1) {
    readCnt = fread((void*)buf, 1, sizeof(buf), src);

    if (readCnt < sizeof(buf)) {
        if (feof(src) != 0) {
            fwrite((void*)buf, 1, readCnt, des);
            puts("File copy complete");
            break;
        }
        else
            puts("File copy Failed");

        break;
    }
    fwrite((void*)buf, 1, sizeof(buf), des);
}
fclose(src);
fclose(des);
return 0;

}

Body:
Because fread() & fwrite() are generic function for reading and writing binary data into file irrespective of their data type.

man page of fwrite() says,

size_t fwrite(const void *ptr, size_t size, size_t nmemb,
                     FILE *stream);

what is first arguement, its const void *ptr means its expecting address. it can be any variable address int or char or any other data type .


问:
PKCS11 - Delete prefix "SunPKCS11-"?
It is possible to delete the prefix "SunPKCS11-"?
because always I get a provider whose name is "SunPKCS11-SmartCard" and not "SmartCard" .

this my code :

```<code>String configName = "pkcs11.cfg";

Provider p = getInstalledProvider(providerName);
if (p == null)
{
    p = new sun.security.pkcs11.SunPKCS11(configName);
}

Security.addProvider(p);
return KeyStore.Builder.newInstance("PKCS11", p, loadProtection);
</code>```

and this my configuration file :

```<code>name = SmartCard
description = configuration file
library =C:\Program Files\Gemalto\Classic Client\BIN\gclib.dll
</code>```

答:
As @EJP pointed, you cannot change the provider name. When you are creating the provider instance, Java prepends the string SunPKCS11-prefix to the name you provide. You can look at the Java documentation about it here.

Once you have created your provider instance, it is recommended to get the name using the Provider.getName().

Title: PKCS11 - Delete prefix "SunPKCS11-"?

Body:
It is possible to delete the prefix "SunPKCS11-"?
because always I get a provider whose name is "SunPKCS11-SmartCard" and not "SmartCard" .

this my code :

String configName = "pkcs11.cfg";

Provider p = getInstalledProvider(providerName);
if (p == null)
{
    p = new sun.security.pkcs11.SunPKCS11(configName);
}

Security.addProvider(p);
return KeyStore.Builder.newInstance("PKCS11", p, loadProtection);

and this my configuration file :

name = SmartCard
description = configuration file
library =C:\Program Files\Gemalto\Classic Client\BIN\gclib.dll


答:
```<code><html>
<head>
</head>
<body>
test
<script>
hist = {
 "undo" : [
  {
   "operation": [ {"x":"2","y":"21"}, {"x":"x2","y":"y21"} ]
  },
  {
   "operation": [ {"x":"99","y":"88"} ]
  },
  {
   "operation": [ {"x":"32","y":"12"} ]
  }
 ]
 };
alert(hist.undo[0].operation[0].x);
alert(hist.undo[0].operation[0].y);
alert(hist.undo[2].operation[0].x);
alert(hist.undo[2].operation[0].y);
</script>
</body>
</html>
</code>```

Title: Need sample javascript object literal


问:
Tensorflow Regression is predicting insanely wrong values
I am currently doing an exercise for university.
The task is to change a given classification to regression.
I did all the changes to the data's preprocessing and the network, so the regression is executed.

But when I try to test the network's prediction, there are insanely wrong values predicted.

The data is a pixel matrix and a corresponding angle between 0° and 90°.
I have splitted up the data to a training set and a testing set and checked all the values in both sets are in range 0° to 90°.

To test the accuracy of the regression I run the following code:

```<code>def reg_perceptron(t, weights, biases):
    t = tf.nn.relu(tf.add(tf.matmul(t, weights['h1']), biases['b1']), name = "layer_1")
    t = tf.add(tf.matmul(t, weights['hOut'], name="LOut_MatMul"), biases['bOut'], name = output_tensor)
    return t

pred = reg_perceptron(_x, rg_weights, rg_biases)

pred_y = np.array([])
total_batch_test = int(len(test_x)/batch_size)
for i in range(total_batch_test):
    lower_bound = i * batch_size
    upper_bound = i * batch_size + batch_size
    batch_test_x = test_x[lower_bound : upper_bound]#test_x are the pixel matrices of the test dataset
    feed_dict = {_x: batch_test_x}
    batch_test_y_predict = sess.run(pred, feed_dict = feed_dict)
    print ("min: %.2f max: %.2f" % (batch_test_y_predict.min(), batch_test_y_predict.max()))
    #WHY ARE THERE VALUES LIKE min: -13563819760524520849408.00 max: 1280719166070321053696.00 PREDICTED?

    if len(pred_y) == 0:
        pred_y = batch_test_y_predict
    else:
        pred_y = np.concatenate((pred_y, batch_test_y_predict), axis=0)

# Print test results.
pred_y = pd.Series(pred_y.reshape(-1).tolist())
#cut of the last elements if division by batch_size has rest
true_y = test_y[:pred_y.size]

RMSE = np.sqrt(np.mean(np.square(np.subtract(pred_y, true_y))))
print ("Epoch: %3.i - RMSE: %.2f" % (epoch, RMSE))
</code>```

Why are there values in range min: -13563819760524520849408.00 max: 1280719166070321053696.00 predicted, if the training data was only in range 0° to 90°?

Thus I get the result: Epoch: 0 - RMSE: 23738450191911909064704.00, which obviously should be way under 90°.

答: I could fix the problem, by normalizing the given data.</p>

Body:
I am currently doing an exercise for university.
The task is to change a given classification to regression.
I did all the changes to the data's preprocessing and the network, so the regression is executed.

But when I try to test the network's prediction, there are insanely wrong values predicted.

The data is a pixel matrix and a corresponding angle between 0° and 90°.
I have splitted up the data to a training set and a testing set and checked all the values in both sets are in range 0° to 90°.

To test the accuracy of the regression I run the following code:

def reg_perceptron(t, weights, biases):
    t = tf.nn.relu(tf.add(tf.matmul(t, weights['h1']), biases['b1']), name = "layer_1")
    t = tf.add(tf.matmul(t, weights['hOut'], name="LOut_MatMul"), biases['bOut'], name = output_tensor)
    return t

pred = reg_perceptron(_x, rg_weights, rg_biases)

pred_y = np.array([])
total_batch_test = int(len(test_x)/batch_size)
for i in range(total_batch_test):
    lower_bound = i * batch_size
    upper_bound = i * batch_size + batch_size
    batch_test_x = test_x[lower_bound : upper_bound]#test_x are the pixel matrices of the test dataset
    feed_dict = {_x: batch_test_x}
    batch_test_y_predict = sess.run(pred, feed_dict = feed_dict)
    print ("min: %.2f max: %.2f" % (batch_test_y_predict.min(), batch_test_y_predict.max()))
    #WHY ARE THERE VALUES LIKE min: -13563819760524520849408.00 max: 1280719166070321053696.00 PREDICTED?

    if len(pred_y) == 0:
        pred_y = batch_test_y_predict
    else:
        pred_y = np.concatenate((pred_y, batch_test_y_predict), axis=0)

# Print test results.
pred_y = pd.Series(pred_y.reshape(-1).tolist())
#cut of the last elements if division by batch_size has rest
true_y = test_y[:pred_y.size]

RMSE = np.sqrt(np.mean(np.square(np.subtract(pred_y, true_y))))
print ("Epoch: %3.i - RMSE: %.2f" % (epoch, RMSE))

Why are there values in range min: -13563819760524520849408.00 max: 1280719166070321053696.00 predicted, if the training data was only in range 0° to 90°?

Thus I get the result: Epoch: 0 - RMSE: 23738450191911909064704.00, which obviously should be way under 90°.


问:
Does python support character type?
When I am checking with data types I wonder why a char value is returning as string type.

Please see my input and output.

Input:

```<code>a = 'c'

type(a)
</code>```

Output:

```<code>class 'str'
</code>```

答:
No.

Python does not have a character or char type. All single characters are strings with length one.

Title: Does python support character type?

Body:
When I am checking with data types I wonder why a char value is returning as string type.

Please see my input and output.

Input:

a = 'c'

type(a)

Output:

class 'str'


问:
Pycharm: "No Python interpreter configured for the project" everytime
Every time I open PyCharm I get this message:

No Python interpreter configured for the project.

So I set the interpreter, everything works fine, then I close PyCharm and reopen it, and the message pops up again.

Reinstalling Python and Pycharm didn't fix the problem.

答:
If you are opening individual files then try setting the default settings.

File > Default Settings > Project Interpreter.

I think when you are opening individual files you are not loading the project. This sets a default interpreter so opening a file without loading the project should give it this interpreter.

If this doesn't work then open pycharm normally and select the project that you are working on.

ContentLicense: CC BY-SA 4.0


问:
Change layout and styling for most recent post in CPT archive template
I have a custom post type called 'Blog' with an archive template of archive-su_blog.php. Within the template i am just calling the standard loop to pull in all the posts and then using some html to construct the page.

I'm wondering if it's possible to change the html and style for the most recent post? Rather than having the same html for all. I know how to do this with a custom query but i'm curious if there's a way to do it with the standard loop?

Example of what i would like to do with the standard if ( have_posts() ) : while ( have_posts() ) : the_post(); loop.

```<code><div class="featured-post">
<div class="col-sm-6 featured-img"><img src=""></div>
<div class="col-sm-6 featured-info"> </div>
</div>

<div class="default-post">
<div class="post-info"></div>
</div>
</code>```

Thank you

答:
```<code>// Query Arguments
$args = array(
    'post_type' => array('blog'),
    'order' => 'DESC',
    'orderby' => 'date',
);

// The Query
$query = new WP_Query( $args );

// The Loop
if ( $query->have_posts() ) {
    $i = 0;
    while ( $query->have_posts() ) {
        if($i ==0){
            // My Custom style
            $query->the_post();
            ?>
            <div class="featured-post">
            <div class="col-sm-6 featured-img"><img src=""></div>
            <div class="col-sm-6 featured-info"> </div>
            </div>
            <?php
            // End of my Custom style
            $i++;
        }else{
            $query->the_post();
            ?>
            <div class="default-post">
            <div class="post-info"></div>
            </div>
            <?php
        }
    }
} else {
    // no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
</code>```

Body:
I have a custom post type called 'Blog' with an archive template of archive-su_blog.php. Within the template i am just calling the standard loop to pull in all the posts and then using some html to construct the page.

I'm wondering if it's possible to change the html and style for the most recent post? Rather than having the same html for all. I know how to do this with a custom query but i'm curious if there's a way to do it with the standard loop?

Example of what i would like to do with the standard if ( have_posts() ) : while ( have_posts() ) : the_post(); loop.

Thank you


问:
How can I pass a variable into an ng-include?
I have the following code:

```<code><div ng-repeat="item in items">
  <div ng-include src="itemG.html"></div>
</div>
</code>```

then in itemG.html I have:

```<code><img src="{{item.image}}">
</code>```

How can I get my ng-repeat to print out all of the images?

答:
In principal code

```<code><div ng-repeat="item in items">
  <ng-include src="itemG.html" ng-controller="MyCtrl" ng-init="i=item"><ng-include>
</div>
</code>```

then in itemG.html I have:

```<code><img src="{{i.image}}">
</code>```

Body:
I have the following code:

then in itemG.html I have:

How can I get my ng-repeat to print out all of the images?

Body:
In principal code

<div ng-repeat="item in items">
  <ng-include src="itemG.html" ng-controller="MyCtrl" ng-init="i=item"><ng-include>
</div>

then in itemG.html I have:

<img src="{{i.image}}">


问:
ionic application run error : Multiple dex files define Lcom/google/zxing/BarcodeFormat
i am developing Hybrid app using ionic. i want to use barcode scanner within it.
i am installing barcode scanner plugin using https://www.thepolyglotdeveloper.com/2014/09/implement-barcode-scanner-using-ionic-framework/

plugin install successfully but after that when i try to deploye my app on android devices using command

ionic run android

I'm getting this following error

Here is version list :

```<code>ionic -v  :  2.1.0

cordova -v :  6.4.0

npm -v :  2.15.9

node -v : 4.6.0
</code>```

I dont know , why my project does not run in device, please help me.

Sorry for my english.

thanks in advance

答:
Remove all plugins then have dependencies on cordova-plugin-compat, listed here: https://cordova.apache.org/news/2017/11/10/plugins-release.html

Remove plugin itself and re-install platform.

cordova plugin rm cordova-plugin-compat --force
cordova platform rm android
cordova platform add android@6.4.0

This should help.

Body:
i am developing Hybrid app using ionic. i want to use barcode scanner within it.
i am installing barcode scanner plugin using https://www.thepolyglotdeveloper.com/2014/09/implement-barcode-scanner-using-ionic-framework/

plugin install successfully but after that when i try to deploye my app on android devices using command

ionic run android

I'm getting this following error

Here is version list :

ionic -v  :  2.1.0

cordova -v :  6.4.0

npm -v :  2.15.9

node -v : 4.6.0

I dont know , why my project does not run in device, please help me.

Sorry for my english.

thanks in advance


问:
C++ static_cast downcast validity
Is this static_cast downcast valid?

```<code>// non-virtual, may be non-trivially copyable
struct Base{
    int m_object;
};

// Derived class have only non-virtual functions
struct A : Base{
    void arggh(){
        std::cout << "Arrghh " << m_object;
    }
};

int main() {
    Base base{190};
    A& a = static_cast<A&>(base);
    a.arggh();
    return 0;
}
</code>```

I mean, CREATE base class, and then cast to derived.

Live

答:
Not at all.

Let's say Base is represented in memory by this block [--] and A is [--+], here you can see that A contains a part Base (with the little '-').

When you are creating a Base you have your [--] and then you are casting it to A which means that you are saying it's in fact [--+] BUT the memory after [--] does not correspond to [--+]

As you may understand with this example, you can cast A to Base because [--+] contains [--]

Title: C++ static_cast downcast validity

Body:
Is this static_cast downcast valid?

// non-virtual, may be non-trivially copyable
struct Base{
    int m_object;
};

// Derived class have only non-virtual functions
struct A : Base{
    void arggh(){
        std::cout << "Arrghh " << m_object;
    }
};

int main() {
    Base base{190};
    A& a = static_cast(base);
    a.arggh();
    return 0;
}

I mean, CREATE base class, and then cast to derived.

Live


答:
You should rather use val data: java.util.List[java.util.List[Double]] = new java.util.ArrayList[java.util.List[Double]]()

Because generic types are not polymorphic in Java. See this

You could also have write the following in order to explicit the type :

val data: java.util.List[? extends java.util.List[Double]] = new java.util.ArrayList[java.util.ArrayList[Double]]()

To be easily understood List is not a super of List even if B extends A.

Title: Initialise Java List in Scala with Java ArrayList

Body:
You should rather use val data: java.util.List[java.util.List[Double]] = new java.util.ArrayList[java.util.List[Double]]()

Because generic types are not polymorphic in Java. See this

You could also have write the following in order to explicit the type :

val data: java.util.List[? extends java.util.List[Double]] = new java.util.ArrayList[java.util.ArrayList[Double]]()

To be easily understood List<A> is not a super of List<B> even if B extends A.


问:
Ruby: Convert an array or hash to an activerecord relation
I am trying to convert a hash to an activerecord relation but am not able to do so. I intend to use the activerecord relation to sort and then filter the Category table. The end goal is to  create an instance method to filter the top 5 visited categories, which i can then use/call in the controller. This is what i have in mind:

Category model:

```<code>def top_5_visited
        Article.joins(:categories).group('categories.name').sum(:impressions_count)
// Add sort
// Limit to top 5
end
</code>```

Category controller:

```<code>@categories = Category.top_5 visited
</code>```

A hash {"Simula"=>7, "Haskell"=>5, "JavaScript"=>10, "C#"=>112} will be created through the following query:

```<code>total_count = Article.joins(:categories).group('categories.name').sum(:impressions_count)
</code>```

I have also tried to convert it to an array using sort_by method:

```<code>total_count_sorted = total_count.sort_by {|_key, value| value}
</code>```

I have googled "convert array to activerecord relation" and referenced this post, but testing this:

```<code>Category.where(id: total_count_sort.map(&:id))
</code>```

in the rails console, brings up this error:

NoMethodError: undefined method id for ["Simula", 7]:Array

答:
What you want to do start from the inverse end (Category) and use an aggregate in the ORDER clause.

```<code>Category.joins(:articles)
        .order('SUM(articles.impressions_count) DESC')
        .group(:id)
        .limit(5)
</code>```

```<code>irb(main):005:0> Category.joins(:articles).order("SUM(articles.impressions_count) DESC").group('categories.id').limit(5)
  Category Load (1.5ms)  SELECT  "categories".* FROM "categories" INNER JOIN "articles" ON "articles"."category_id" = "categories"."id" GROUP BY categories.id ORDER BY SUM(articles.impressions_count) DESC LIMIT $1  [["LIMIT", 5]]
=> #<ActiveRecord::Relation [#<Category id: 4, name: "C#", created_at: "2017-11-15 15:06:32", updated_at: "2017-11-15 15:06:32">, #<Category id: 3, name: "JavaScript", created_at: "2017-11-15 15:06:32", updated_at: "2017-11-15 15:06:32">, #<Category id: 1, name: "Simula", created_at: "2017-11-15 15:03:37", updated_at: "2017-11-15 15:03:37">, #<Category id: 2, name: "Haskell", created_at: "2017-11-15 15:06:32", updated_at: "2017-11-15 15:06:32">]>
</code>```

And you should create a class method - not an instance method as this is basically just a scope and does not make sense to call on an instance.

```<code>class Category < ApplicationRecord
  has_many :articles

  def self.order_by_article_impressions
    self.joins(:articles)
        .order('SUM(articles.impressions_count)')
        .group(:id)
  end

  def self.top_5_visited
    order_by_article_impressions.limit(5)
  end

  # Or use `scope` which is just syntactic sugar
  scope(:top_5_visited) -> { order_by_article_impressions.limit(5) }
end
</code>```

Body:
I am trying to convert a hash to an activerecord relation but am not able to do so. I intend to use the activerecord relation to sort and then filter the Category table. The end goal is to  create an instance method to filter the top 5 visited categories, which i can then use/call in the controller. This is what i have in mind:

Category model:

def top_5_visited
        Article.joins(:categories).group('categories.name').sum(:impressions_count)
// Add sort
// Limit to top 5
end

Category controller:

@categories = Category.top_5 visited

A hash {"Simula"=>7, "Haskell"=>5, "JavaScript"=>10, "C#"=>112} will be created through the following query:

total_count = Article.joins(:categories).group('categories.name').sum(:impressions_count)

I have also tried to convert it to an array using sort_by method:

total_count_sorted = total_count.sort_by {|_key, value| value}

I have googled "convert array to activerecord relation" and referenced this post, but testing this:

Category.where(id: total_count_sort.map(&:id))

in the rails console, brings up this error:

NoMethodError: undefined method id for ["Simula", 7]:Array

Body:
What you want to do start from the inverse end (Category) and use an aggregate in the ORDER clause.

Category.joins(:articles)
        .order('SUM(articles.impressions_count) DESC')
        .group(:id)
        .limit(5)

irb(main):005:0> Category.joins(:articles).order("SUM(articles.impressions_count) DESC").group('categories.id').limit(5)
  Category Load (1.5ms)  SELECT  "categories".* FROM "categories" INNER JOIN "articles" ON "articles"."category_id" = "categories"."id" GROUP BY categories.id ORDER BY SUM(articles.impressions_count) DESC LIMIT $1  [["LIMIT", 5]]
=> #<ActiveRecord::Relation [#<Category id: 4, name: "C#", created_at: "2017-11-15 15:06:32", updated_at: "2017-11-15 15:06:32">, #<Category id: 3, name: "JavaScript", created_at: "2017-11-15 15:06:32", updated_at: "2017-11-15 15:06:32">, #<Category id: 1, name: "Simula", created_at: "2017-11-15 15:03:37", updated_at: "2017-11-15 15:03:37">, #<Category id: 2, name: "Haskell", created_at: "2017-11-15 15:06:32", updated_at: "2017-11-15 15:06:32">]>

And you should create a class method - not an instance method as this is basically just a scope and does not make sense to call on an instance.

class Category < ApplicationRecord
  has_many :articles

  def self.order_by_article_impressions
    self.joins(:articles)
        .order('SUM(articles.impressions_count)')
        .group(:id)
  end

  def self.top_5_visited
    order_by_article_impressions.limit(5)
  end

  # Or use `scope` which is just syntactic sugar
  scope(:top_5_visited) -> { order_by_article_impressions.limit(5) }
end


问:
UISlider problem - how to detect a user releasing the slider button in iOS?
I can detect the value change event from the UISlider, but now I need to detect a user releasing the slider button.

How to detect this event (or touch on slider ends) ?

Should I use the "touch up inside" event for detection ?

Thanks.

答: UIControlEventTouchDown event to detect when the user starts using the control. UIControlEventTouchUpInside when the user finishes using the slider. To add the event just do as @JohnK suggested


问:
Extracting certain parts on image with PHP
I would like to be able to extract radar data from gif which occurs every hour.

This is an example of one gif:

Data colors can vary according data legend on the right. I would also like that country borders are not visible, as gif is drown in order: base layer, radar data layer, borders layer - I only need pure radar data.

Any suggestion or solution will be very much appriciated!

答:
All the radar data seems to be highly saturated, so you could extract the saturation onto its own layer and threshold it at, say, 85% and use that as the opacity like this:

```<code>convert radar.gif \
   \( +clone -colorspace hsl -channel S -separate -threshold 85% \) \
     -compose copyopacity -composite result.gif
</code>```

which gives you this, where all the unsaturated colours are now transparent:

As you can see, it is correctly picking up and retaining all the colours in the "key" on the right, but it also picks up the mauve on the left of the image. Let's make that specific tone transparent:

```<code>convert radar.gif \
   \( +clone -colorspace hsl -channel S -separate -threshold 85% \) \
      -compose copyopacity -composite                               \
      -fuzz 10% -fill none -opaque "rgb(160,153,255)" result.gif
</code>```

which gives this:

Now, I presume we need to get rid of the sickly yellow too:

```<code>convert radar.gif \
  \( +clone -colorspace hsl -channel S -separate -threshold 85% \) \
     -compose copyopacity -composite                               \
     -fuzz 10% -fill none                                          \
     -opaque "rgb(160,153,255)"                                    \
     -opaque "rgb(254,251,175)" result.gif
</code>```

Finally, let's crop to the top left 480x480 px:

```<code>convert radar.gif -crop 480x480+0+0 +repage \
  \( +clone -colorspace hsl -channel S -separate -threshold 85% \) \
     -compose copyopacity -composite                               \
     -fuzz 10% -fill none                                          \
     -opaque "rgb(160,153,255)"                                    \
     -opaque "rgb(254,251,175)" result.gif
</code>```

Body:
All the radar data seems to be highly saturated, so you could extract the saturation onto its own layer and threshold it at, say, 85% and use that as the opacity like this:

convert radar.gif \
   \( +clone -colorspace hsl -channel S -separate -threshold 85% \) \
     -compose copyopacity -composite result.gif

which gives you this, where all the unsaturated colours are now transparent:

As you can see, it is correctly picking up and retaining all the colours in the "key" on the right, but it also picks up the mauve on the left of the image. Let's make that specific tone transparent:

convert radar.gif \
   \( +clone -colorspace hsl -channel S -separate -threshold 85% \) \
      -compose copyopacity -composite                               \
      -fuzz 10% -fill none -opaque "rgb(160,153,255)" result.gif

which gives this:

Now, I presume we need to get rid of the sickly yellow too:

convert radar.gif \
  \( +clone -colorspace hsl -channel S -separate -threshold 85% \) \
     -compose copyopacity -composite                               \
     -fuzz 10% -fill none                                          \
     -opaque "rgb(160,153,255)"                                    \
     -opaque "rgb(254,251,175)" result.gif

Finally, let's crop to the top left 480x480 px:

convert radar.gif -crop 480x480+0+0 +repage \
  \( +clone -colorspace hsl -channel S -separate -threshold 85% \) \
     -compose copyopacity -composite                               \
     -fuzz 10% -fill none                                          \
     -opaque "rgb(160,153,255)"                                    \
     -opaque "rgb(254,251,175)" result.gif


问:
Find a way in the java logging frameworks scene
Java has a lot of frameworks / APIs that help you do logging in your application:

The Java API has java.util.logging package.

Apache's Log4j.

Apache's Commons Logging.

SLF4J (logging Facade).

jLo.
and many many more...

I've always used the log4j library, i found it sufficient most of the time, and extensible when i needed more control.

Anyone who had experience with more than one framework can share his experience? when is it better to use one framework over the other and from application architecture point of view? Why would i prefer one over other?

Thanks

答: Commons Logging is source of strange classloading problems. Avoid it if you can. I prefer log4j when developing application. If you develop library/framework and you don't want to enforce logging library, choose slf4j.</p>

OwnerDisplayName: Alon

OwnerDisplayName: Peter Štibraný


问:
Simple question on how to format a number
my question is the following and I guess is really simple.
I have a number echoed with PHP. For example 37452.
I would like to have a dot and be displayed like 37.452

My var is $numposts

How is this possible ?
Thank you

答:
use number_format with custom decimal and thousands characters.</p>

```<code>number_format(37452, 0, ',', '.');
</code>```

Body:
use number_format with custom decimal and thousands characters.

number_format(37452, 0, ',', '.');


问:
What does the "js" method do on gulp (for Typescript project using gulp-typescript)
I'm in the process of defining a seed node.js based server project for Typescript using Gulp and Mocha and am looking at the example at: https://www.typescriptlang.org/docs/handbook/gulp.html.

A gulpfile has been defined with the following code:

```<code>var gulp = require("gulp");
var ts = require("gulp-typescript");
var tsProject = ts.createProject("tsconfig.json");

gulp.task("default", function () {
  return tsProject.src()
    .pipe(tsProject())
    .js.pipe(gulp.dest("dist"));
});
</code>```

I know that this code compiles Typescript into javascript and places the resulting files in the "dist" folder. However, I would like to break this code down and understand what is happening at every point (I'm not sure which exact bit of code invokes the Typescript compiler).

1) So, which part of the code invokes the compiler?

2) What does the .js call do? (I'm guessing this is the call to invoke typescript compilation, but I don't know).

The problem I find with the gulp documentation is that its not very comprehensive. I would like to find the documentation for all of the api methods (eg, "src", "js", "createProject", "pipe" etc). And the documentation on gulp-typescript on https://www.npmjs.com/package/gulp-typescript provides you with code snippets without explaining the details.

I have already watched the video at https://gulpjs.org by markgdyr, but the other videos are for browser projects, which I'm not interested in, thanks.

答:
Piping your source files through the TypeScript project tsProject you created executes the compile step.

This produces an object containing a set of JavaScript files js, and a set of TypeScript definition files dts. In this case, you are accessing the JavaScript files via .js and saving them in the output folder via gulp.dest.

js is not a function, but a simple property access.

More info in the gulp-typescript docs.

Body:
I'm in the process of defining a seed node.js based server project for Typescript using Gulp and Mocha and am looking at the example at: https://www.typescriptlang.org/docs/handbook/gulp.html.

A gulpfile has been defined with the following code:

var gulp = require("gulp");
var ts = require("gulp-typescript");
var tsProject = ts.createProject("tsconfig.json");

gulp.task("default", function () {
  return tsProject.src()
    .pipe(tsProject())
    .js.pipe(gulp.dest("dist"));
});

I know that this code compiles Typescript into javascript and places the resulting files in the "dist" folder. However, I would like to break this code down and understand what is happening at every point (I'm not sure which exact bit of code invokes the Typescript compiler).

1) So, which part of the code invokes the compiler?

2) What does the .js call do? (I'm guessing this is the call to invoke typescript compilation, but I don't know).

The problem I find with the gulp documentation is that its not very comprehensive. I would like to find the documentation for all of the api methods (eg, "src", "js", "createProject", "pipe" etc). And the documentation on gulp-typescript on https://www.npmjs.com/package/gulp-typescript provides you with code snippets without explaining the details.

I have already watched the video at https://gulpjs.org by markgdyr, but the other videos are for browser projects, which I'm not interested in, thanks.


问:
OHCL (Open-high-low-close) T-SQL Query
I'm trying to do a OHCL sql query (SQL Server 2012) on a StockData table. There are thousands of rows per day added to the table and I want to get the Open, High, Low and Close data for each day.

The create table sql is below:

```<code>  CREATE TABLE [dbo].[StockData](
    [ID] [bigint] IDENTITY(1,1) NOT NULL,
    [StockExchangeID] [bigint] NOT NULL,
    [DataDateTime] [datetime] NOT NULL,
    [ExportCost] [bigint] NOT NULL,
 CONSTRAINT [PK_StockData] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
</code>```

Using the query below I can get the High, Low and Average but I'm having difficulty getting the Open (earliest ExportCost based on DataDateTime) and Close (latest ExportCost based on DataDateTime) of the ExportCost for the day.

My query so far is below. If there is a more efficient way to do it then any suggestions welcome.

```<code>DECLARE @IntervalDays INT, @StartDate DATETIME, @EndDate DATETIME;
SET @IntervalDays = 1;
SET @StartDate = '01/01/2017'
SET @EndDate = '01/01/2018'

-- Create the database table
SELECT
    StockExchangeID,
    DATEADD(DAY, DATEDIFF(DAY,0,[DataDateTime]) / @IntervalDays * @IntervalDays, 0) AS [DateDay],
    MAX(ExportCost) AS DayHigh,
    MIN(ExportCost) AS DayLow,
    AVG(ExportCost) AS DayAverage,
    '??????????' As DayOpen, --Not sure how to get the start price for the day i.e. ExportCost for the first record for that day based on [DataDateTime]
    '??????????' As DatClose
FROM StockData
WHERE [DataDateTime] >= @StartDate AND [DataDateTime] <= @EndDate
GROUP BY DATEADD(DAY, DATEDIFF(DAY,0,[DataDateTime]) / @IntervalDays * @IntervalDays, 0), StockExchangeID
ORDER BY [DateDay]
</code>```

答:
Trust me - you might want to keep this level of detail data but you don't want to use it for general reporting purposes. You need to aggregate the pricing to the high/low/close/open values for each day and store them because they don't change once a trading day has finished (well, sometimes they do but it is extremely rare and doesn't change the general approach). </p>

<p>A step further - your choice of primary key and clustered index might not be particularly useful. You almost always search this table for either a given security or a given date (or date range). Clustering on an identity column is likely wasteful. I would also consider separating the date and the time into separate columns. The date part is extremely important - the time part probably isn't used much. If you were to separate the date and time, your queries become much simpler since you simply group by date to find min/max. Finding open and close could be simplified with additional schema changes (or better - with the post trading aggregated table). </p>

Title: OHCL (Open-high-low-close) T-SQL Query

Body:
I'm trying to do a OHCL sql query (SQL Server 2012) on a StockData table. There are thousands of rows per day added to the table and I want to get the Open, High, Low and Close data for each day.

The create table sql is below:

  CREATE TABLE [dbo].[StockData](
    [ID] [bigint] IDENTITY(1,1) NOT NULL,
    [StockExchangeID] [bigint] NOT NULL,
    [DataDateTime] [datetime] NOT NULL,
    [ExportCost] [bigint] NOT NULL,
 CONSTRAINT [PK_StockData] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Using the query below I can get the High, Low and Average but I'm having difficulty getting the Open (earliest ExportCost based on DataDateTime) and Close (latest ExportCost based on DataDateTime) of the ExportCost for the day.

My query so far is below. If there is a more efficient way to do it then any suggestions welcome.

DECLARE @IntervalDays INT, @StartDate DATETIME, @EndDate DATETIME;
SET @IntervalDays = 1;
SET @StartDate = '01/01/2017'
SET @EndDate = '01/01/2018'

-- Create the database table
SELECT
    StockExchangeID,
    DATEADD(DAY, DATEDIFF(DAY,0,[DataDateTime]) / @IntervalDays * @IntervalDays, 0) AS [DateDay],
    MAX(ExportCost) AS DayHigh,
    MIN(ExportCost) AS DayLow,
    AVG(ExportCost) AS DayAverage,
    '??????????' As DayOpen, --Not sure how to get the start price for the day i.e. ExportCost for the first record for that day based on [DataDateTime]
    '??????????' As DatClose
FROM StockData
WHERE [DataDateTime] >= @StartDate AND [DataDateTime] <= @EndDate
GROUP BY DATEADD(DAY, DATEDIFF(DAY,0,[DataDateTime]) / @IntervalDays * @IntervalDays, 0), StockExchangeID
ORDER BY [DateDay]

Body:
Trust me - you might want to keep this level of detail data but you don't want to use it for general reporting purposes. You need to aggregate the pricing to the high/low/close/open values for each day and store them because they don't change once a trading day has finished (well, sometimes they do but it is extremely rare and doesn't change the general approach).

A step further - your choice of primary key and clustered index might not be particularly useful. You almost always search this table for either a given security or a given date (or date range). Clustering on an identity column is likely wasteful. I would also consider separating the date and the time into separate columns. The date part is extremely important - the time part probably isn't used much. If you were to separate the date and time, your queries become much simpler since you simply group by date to find min/max. Finding open and close could be simplified with additional schema changes (or better - with the post trading aggregated table).


问:
Align two buttons center horizontally programmatically using constraint layout
I'm trying to programmatically use constraint layout to center two buttons of equal size horizontally at the center of the screen.  Here's what I have so far:

```<code>    val view = super.onCreateView(inflater, container, savedInstanceState)

    buttonTrue = Button(activity, null, 0, R.style.NeutrifProText_BooleanButton)
    buttonTrue?.id = View.generateViewId()
    buttonTrue?.text = task?.booleanTrueLabel() ?: getString(R.string.button_yes)
    buttonTrue?.gravity = Gravity.CENTER_HORIZONTAL
    buttonTrue?.setOnClickListener { listener?.onTaskContinue(getAnswer(true)) }

    buttonFalse = Button(activity, null, 0, R.style.NeutrifProText_BooleanButton)
    buttonFalse?.id = View.generateViewId()
    buttonFalse?.text = task?.booleanFalseLabel() ?: getString(R.string.button_no)
    buttonFalse?.gravity = Gravity.CENTER_HORIZONTAL
    buttonFalse?.setOnClickListener { listener?.onTaskContinue(getAnswer(false)) }

    buttonTrue?.layoutParams = ConstraintLayout.LayoutParams(0, ConstraintLayout.LayoutParams.WRAP_CONTENT)
    buttonFalse?.layoutParams = ConstraintLayout.LayoutParams(0, ConstraintLayout.LayoutParams.WRAP_CONTENT)
    view?.task_constraint_layout?.addView(buttonTrue)
    view?.task_constraint_layout?.addView(buttonFalse)

    val idYes = buttonTrue?.id ?: 0
    val idNo = buttonFalse?.id ?: 0
    val descid = view?.task_description?.id ?: 0

    val clid = view?.task_constraint_layout?.id ?: 0
    val constraintSet = ConstraintSet()
    constraintSet.clone(view?.task_constraint_layout)
    constraintSet.connect(idYes, ConstraintSet.TOP, descid, ConstraintSet.BOTTOM, topMargin)
    constraintSet.connect(idNo, ConstraintSet.TOP, descid, ConstraintSet.BOTTOM, topMargin)

    constraintSet.connect(idYes, ConstraintSet.START, clid, ConstraintSet.START, buttonSideMargin)

    constraintSet.connect(idNo, ConstraintSet.START, idYes, ConstraintSet.END, buttonSideMargin)
    constraintSet.connect(idNo, ConstraintSet.END, clid, ConstraintSet.END, buttonSideMargin)
    constraintSet.applyTo(view?.task_constraint_layout)
</code>```

This results in:

How do I get the buttons to be spaced evenly?

答:
I created this layout XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/myConstraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button 1" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button 2" />
</android.support.constraint.ConstraintLayout>
</code>```

As you can see, there are no constraints, this is for simplicity since you are creating the Buttons programmatically.

Now, in the onCreate() method (you can do it wherever you want), I do this:

```<code>override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val constraintLayout = findViewById<ConstraintLayout>(R.id.myConstraintLayout)

    val constraintSet = ConstraintSet()
    constraintSet.clone(constraintLayout)
    constraintSet.connect(R.id.button1, ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START)
    constraintSet.connect(R.id.button1, ConstraintSet.END, R.id.button2, ConstraintSet.START)
    constraintSet.setHorizontalChainStyle(R.id.button1, ConstraintSet.CHAIN_SPREAD)

    constraintSet.connect(R.id.button2, ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END)
    constraintSet.connect(R.id.button2, ConstraintSet.START, R.id.button1, ConstraintSet.END)
    constraintSet.applyTo(constraintLayout)
}
</code>```

Note, this is the magic line:

constraintSet.setHorizontalChainStyle(R.id.button1, ConstraintSet.CHAIN_SPREAD)

So, your ConstraintSet code should look like this:

```<code>val clid = view?.task_constraint_layout?.id ?: 0
val constraintSet = ConstraintSet()
constraintSet.clone(view?.task_constraint_layout)
constraintSet.connect(idYes, ConstraintSet.TOP, descid, ConstraintSet.BOTTOM, topMargin)
constraintSet.connect(idNo, ConstraintSet.TOP, descid, ConstraintSet.BOTTOM, topMargin)

constraintSet.connect(idYes, ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START, buttonSideMargin)
constraintSet.connect(idYes, ConstraintSet.END, idNo, ConstraintSet.START)
// This line does the magic
constraintSet.setHorizontalChainStyle(idYes, ConstraintSet.CHAIN_SPREAD)

constraintSet.connect(idNo, ConstraintSet.START, idYes, ConstraintSet.END)
constraintSet.connect(idNo, ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END, buttonSideMargin)
constraintSet.applyTo(view?.task_constraint_layout)
</code>```

EDIT:

Verify your style R.style.NeutrifProText_BooleanButton is not applyng big margins to your buttons. Otherwise, if there is no space between your buttons, try to add some margins between them:

```<code>constraintSet.connect(idYes, ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START, buttonSideMargin)
constraintSet.connect(idYes, ConstraintSet.END, idNo, ConstraintSet.START, yourMarginValue /* Get it the same way you are getting buttonSideMargin */)
// This line does the magic
constraintSet.setHorizontalChainStyle(idYes, ConstraintSet.CHAIN_SPREAD)

constraintSet.connect(idNo, ConstraintSet.START, idYes, ConstraintSet.END, yourMarginValue /* Get it the same way you are getting buttonSideMargin */)
constraintSet.connect(idNo, ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END, buttonSideMargin)
constraintSet.applyTo(view?.task_constraint_layout)
</code>```

This is the final result of my example:

Body:
I'm trying to programmatically use constraint layout to center two buttons of equal size horizontally at the center of the screen.  Here's what I have so far:

    val view = super.onCreateView(inflater, container, savedInstanceState)

    buttonTrue = Button(activity, null, 0, R.style.NeutrifProText_BooleanButton)
    buttonTrue?.id = View.generateViewId()
    buttonTrue?.text = task?.booleanTrueLabel() ?: getString(R.string.button_yes)
    buttonTrue?.gravity = Gravity.CENTER_HORIZONTAL
    buttonTrue?.setOnClickListener { listener?.onTaskContinue(getAnswer(true)) }

    buttonFalse = Button(activity, null, 0, R.style.NeutrifProText_BooleanButton)
    buttonFalse?.id = View.generateViewId()
    buttonFalse?.text = task?.booleanFalseLabel() ?: getString(R.string.button_no)
    buttonFalse?.gravity = Gravity.CENTER_HORIZONTAL
    buttonFalse?.setOnClickListener { listener?.onTaskContinue(getAnswer(false)) }

    buttonTrue?.layoutParams = ConstraintLayout.LayoutParams(0, ConstraintLayout.LayoutParams.WRAP_CONTENT)
    buttonFalse?.layoutParams = ConstraintLayout.LayoutParams(0, ConstraintLayout.LayoutParams.WRAP_CONTENT)
    view?.task_constraint_layout?.addView(buttonTrue)
    view?.task_constraint_layout?.addView(buttonFalse)

    val idYes = buttonTrue?.id ?: 0
    val idNo = buttonFalse?.id ?: 0
    val descid = view?.task_description?.id ?: 0

    val clid = view?.task_constraint_layout?.id ?: 0
    val constraintSet = ConstraintSet()
    constraintSet.clone(view?.task_constraint_layout)
    constraintSet.connect(idYes, ConstraintSet.TOP, descid, ConstraintSet.BOTTOM, topMargin)
    constraintSet.connect(idNo, ConstraintSet.TOP, descid, ConstraintSet.BOTTOM, topMargin)

    constraintSet.connect(idYes, ConstraintSet.START, clid, ConstraintSet.START, buttonSideMargin)

    constraintSet.connect(idNo, ConstraintSet.START, idYes, ConstraintSet.END, buttonSideMargin)
    constraintSet.connect(idNo, ConstraintSet.END, clid, ConstraintSet.END, buttonSideMargin)
    constraintSet.applyTo(view?.task_constraint_layout)

This results in:

How do I get the buttons to be spaced evenly?

Body:
I created this layout XML:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/myConstraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button 1" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button 2" />
</android.support.constraint.ConstraintLayout>

As you can see, there are no constraints, this is for simplicity since you are creating the Buttons programmatically.

Now, in the onCreate() method (you can do it wherever you want), I do this:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val constraintLayout = findViewById<ConstraintLayout>(R.id.myConstraintLayout)

    val constraintSet = ConstraintSet()
    constraintSet.clone(constraintLayout)
    constraintSet.connect(R.id.button1, ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START)
    constraintSet.connect(R.id.button1, ConstraintSet.END, R.id.button2, ConstraintSet.START)
    constraintSet.setHorizontalChainStyle(R.id.button1, ConstraintSet.CHAIN_SPREAD)

    constraintSet.connect(R.id.button2, ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END)
    constraintSet.connect(R.id.button2, ConstraintSet.START, R.id.button1, ConstraintSet.END)
    constraintSet.applyTo(constraintLayout)
}

Note, this is the magic line:

constraintSet.setHorizontalChainStyle(R.id.button1, ConstraintSet.CHAIN_SPREAD)

So, your ConstraintSet code should look like this:

val clid = view?.task_constraint_layout?.id ?: 0
val constraintSet = ConstraintSet()
constraintSet.clone(view?.task_constraint_layout)
constraintSet.connect(idYes, ConstraintSet.TOP, descid, ConstraintSet.BOTTOM, topMargin)
constraintSet.connect(idNo, ConstraintSet.TOP, descid, ConstraintSet.BOTTOM, topMargin)

constraintSet.connect(idYes, ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START, buttonSideMargin)
constraintSet.connect(idYes, ConstraintSet.END, idNo, ConstraintSet.START)
// This line does the magic
constraintSet.setHorizontalChainStyle(idYes, ConstraintSet.CHAIN_SPREAD)

constraintSet.connect(idNo, ConstraintSet.START, idYes, ConstraintSet.END)
constraintSet.connect(idNo, ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END, buttonSideMargin)
constraintSet.applyTo(view?.task_constraint_layout)

EDIT:

Verify your style R.style.NeutrifProText_BooleanButton is not applyng big margins to your buttons. Otherwise, if there is no space between your buttons, try to add some margins between them:

constraintSet.connect(idYes, ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START, buttonSideMargin)
constraintSet.connect(idYes, ConstraintSet.END, idNo, ConstraintSet.START, yourMarginValue /* Get it the same way you are getting buttonSideMargin */)
// This line does the magic
constraintSet.setHorizontalChainStyle(idYes, ConstraintSet.CHAIN_SPREAD)

constraintSet.connect(idNo, ConstraintSet.START, idYes, ConstraintSet.END, yourMarginValue /* Get it the same way you are getting buttonSideMargin */)
constraintSet.connect(idNo, ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END, buttonSideMargin)
constraintSet.applyTo(view?.task_constraint_layout)

This is the final result of my example:


问:
Spotfire Trellis Maps of Cumulative Activity
I want to create Maps by Year-Quarter each accumulating on the previous quarter.

I'm splitting the Maps on Trellis by a Date column so the custom expression looks like this currently:

< BinByDateTime([Approved Date],"Year.Month",1)>

and the problem is I don't know how to incorporate the AllPrevious function. If there is another way to make each map trellis add up the previous maps' data.

I'd really appreciate it!

Open attachment to see what my current maps trellis looks like without them accumulating.

Thanks, George

答:
I'm not sure you're going to be able to do this the way you'd like. I believe by now you have read the documentation of OVER functions and understand that they navigate a hierarchy, in this case one constructed from the date (if you haven't read it yet, press F1 and get to studying because none of this will make sense :).

thing is, what you're doing with the trellis is then limiting each visualization by a given category. in other words, each panel of the trellis is containing and can access only the data defined by your Year.Quarter hierarchy.

to put it in OOP terms, it is out of scope to access 2016.Q2 from 2016.Q3.

you can recreate this by building a chart with a Data Limiting Expression of, say, Year([Approved Date]) = 2016. no matter what you do, you won't be able to access 2015 or 2017 from this chart, because you've explicitly limited  the chart to only 2016. the trellis is an implicit limit, I guess you could say.

that said, I don't know the ideal solution to recommend. one idea is to have a separate map to the side that shows the cumulative sum. this will show the comparison quarter to quarter as well as the result for "today," but you lose the perception of growth over time.

another could be to create a slider property control for the date, and then limit a single map chart to that document property, so that the user could choose his own date range and even drag the slider back and forth to visualize change over time. but then you lose the side-by-side comparison.

a third idea: use a single map chart with markers showing the total all time, then create a details visualization line or bar chart that shows the growth over time. you get total comparison and growth, but sort of muddy the big picture.

sorry that this isn't a perfect answer, but hopefully one of these suggestions works for your use case. even better is if one of the other power users here have an idea of how to break out of trellises.


问:
static ip address allocation for public virtual server
```<code>Image image = new Image();
image.setCapacity(50L);

Guest guest = new Guest();
guest.setHostname("hostname1");
guest.setDomain("softlayer.com");
guest.setStartCpus(1l);
guest.setMaxMemory(1024l);
guest.setDatacenter(new Location());
guest.getDatacenter().setName("che01");

guest.setLocalDiskFlag(false);
guest.setHourlyBillingFlag(true);

guest.setOperatingSystemReferenceCode("UBUNTU_LATEST");

Component privateComponent = new Component();
Component publicComponent = new Component();

Vlan privateVlan = new Vlan();
privateVlan.setVlanNumber(1365L);
privateVlan.setId(2117919L);

Subnet privateSubnet = new Subnet();
privateSubnet.setId(1059121L);

privateComponent.setNetworkVlan(privateVlan);
privateComponent.setPrimarySubnet(privateSubnet);
guest.setPrimaryBackendNetworkComponent(privateComponent);

Vlan publicVlan = new Vlan();
publicVlan.setId(2117917L);
publicVlan.setVlanNumber(1290L);

Subnet primarySubnetVersion4 = new Subnet();
primarySubnetVersion4.setVersion(4L);
primarySubnetVersion4.setId(1547547L);
publicVlan.setPrimarySubnet(primarySubnetVersion4);

publicComponent.setNetworkVlan(publicVlan);
publicComponent.setPrimaryIpAddress("169.38.101.156");
guest.setPrimaryNetworkComponent(publicComponent);

Guest.service(client).createObject(guest);
</code>```

How to configure a static ip address while creating a virtual server instead of assigning the dynamic IP address. I used the above code but its not working for me. please suggest a best way to configure the static ip address.

答:
Unfortunately you won't be able to configure the ip address while creating the VSI. The provisioning process looks for an available ip address in the subnet an it is assigned to the VSI, this ip address is static so it will not change each time you turn on/off the VSI.

More info can be find in the documentation, for example in  can-i-move-my-ip-address-one-server-another? says:

Each customer will receive an initial routed block of one primary IP address.  Primary IP addresses are bound to each individual server and cannot be moved unless the server is cancelled and replaced by a new server on the existing VLAN.

Below are some links that you can review about subnets and ip addresses.

http://knowledgelayer.softlayer.com/faq/can-i-move-my-ip-address-one-server-another

http://knowledgelayer.softlayer.com/faq/how-are-server-ip-addresses-assigned-softlayer-network

http://knowledgelayer.softlayer.com/faq/can-i-pick-my-servers-private-ip

http://knowledgelayer.softlayer.com/learning/virtual-machine-network-setup

http://knowledgelayer.softlayer.com/learning/utilizing-subnets-and-ips

http://knowledgelayer.softlayer.com/faq/how-do-i-use-public-network

Body:
Image image = new Image();
image.setCapacity(50L);

Guest guest = new Guest();
guest.setHostname("hostname1");
guest.setDomain("softlayer.com");
guest.setStartCpus(1l);
guest.setMaxMemory(1024l);
guest.setDatacenter(new Location());
guest.getDatacenter().setName("che01");

guest.setLocalDiskFlag(false);
guest.setHourlyBillingFlag(true);

guest.setOperatingSystemReferenceCode("UBUNTU_LATEST");

Component privateComponent = new Component();
Component publicComponent = new Component();

Vlan privateVlan = new Vlan();
privateVlan.setVlanNumber(1365L);
privateVlan.setId(2117919L);

Subnet privateSubnet = new Subnet();
privateSubnet.setId(1059121L);

privateComponent.setNetworkVlan(privateVlan);
privateComponent.setPrimarySubnet(privateSubnet);
guest.setPrimaryBackendNetworkComponent(privateComponent);

Vlan publicVlan = new Vlan();
publicVlan.setId(2117917L);
publicVlan.setVlanNumber(1290L);

Subnet primarySubnetVersion4 = new Subnet();
primarySubnetVersion4.setVersion(4L);
primarySubnetVersion4.setId(1547547L);
publicVlan.setPrimarySubnet(primarySubnetVersion4);

publicComponent.setNetworkVlan(publicVlan);
publicComponent.setPrimaryIpAddress("169.38.101.156");
guest.setPrimaryNetworkComponent(publicComponent);

Guest.service(client).createObject(guest);

How to configure a static ip address while creating a virtual server instead of assigning the dynamic IP address. I used the above code but its not working for me. please suggest a best way to configure the static ip address.


问:
How does one clear user input in Bash when using 'read'?
I have this code in an infinite loop:

```<code>read -a output
echo ${output[@]}
</code>```

When the code runs the screen might look like this:

```<code>Hello, World # line where value was given to output (I want this gone)
Hello, World # echoed output
[] # <-- cursor waiting for next input
</code>```

Is there a way to clear the line where the user inputs the value? Like, as in get rid of it totally (not just changing the line to whitespace that will still leave a gap in the desired output)?

答:
Use tput with the cuu1 and dl1 capabilities.

```<code>echo "foobar42"
echo "$(tput cuu1)$(tput dl1)baz123"
</code>```

Body:
I have this code in an infinite loop:

read -a output
echo ${output[@]}

When the code runs the screen might look like this:

Hello, World # line where value was given to output (I want this gone)
Hello, World # echoed output
[] # <-- cursor waiting for next input

Is there a way to clear the line where the user inputs the value? Like, as in get rid of it totally (not just changing the line to whitespace that will still leave a gap in the desired output)?

Body:
Use tput with the cuu1 and dl1 capabilities.

echo "foobar42"
echo "$(tput cuu1)$(tput dl1)baz123"


问:
Css Selector for inputs which name contains two words?
It is possibile to use this selector

```<code>$( "input[name~='man']" )
</code>```

to identify any input in page which name contains the word 'man' but if i need to select, instead of a single word pattern i.e. 'man', a pattern containing two words like '(anything)checkbox(anything)man(anything)' so that

```<code><input name="checkbox-foo-man">
<input name="checkbox-bar-man">
<input name="foo-checkbox-foo-man-foo">
</code>```

gets selected? Possibily, impliying the right order that is 'checkbox' before 'man'

答:
You can do it without regexes by combining selectors. I don't think there's a way to ensure the order this way though.

[name*="foo"][name*="bar"] {
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div name="foo-bar"> foo-bar </div> <!-- selected -->
<div name="bar-foo"> bar-foo </div> <!-- selected -->
<div name="foo-bar-baz"> foo-bar-baz </div> <!-- selected -->
<div name="foo-baz"> foo-baz </div>
<div name="bar-baz"> bar-baz </div></code>```

Body:
It is possibile to use this selector

$( "input[name~='man']" )

to identify any input in page which name contains the word 'man' but if i need to select, instead of a single word pattern i.e. 'man', a pattern containing two words like '(anything)checkbox(anything)man(anything)' so that

<input name="checkbox-foo-man">
<input name="checkbox-bar-man">
<input name="foo-checkbox-foo-man-foo">

gets selected? Possibily, impliying the right order that is 'checkbox' before 'man'

Body:
You can do it without regexes by combining selectors. I don't think there's a way to ensure the order this way though.

[name*="foo"][name*="bar"] {
  color: red;
}

<div name="foo-bar"> foo-bar </div> <!-- selected -->
<div name="bar-foo"> bar-foo </div> <!-- selected -->
<div name="foo-bar-baz"> foo-bar-baz </div> <!-- selected -->
<div name="foo-baz"> foo-baz </div>
<div name="bar-baz"> bar-baz </div>


问:
Creating dynamic elements with jQuery separately in different divs
I'm using jQuery in order to create dinamically input forms. I made an example of my code (this example doesn't creates input forms but it works exacly as my script, and it reproduce the same error) that you can play in order to understand better what I mean.

The problem is that if I press "Add" of the first div "event", my jQuery produces the skulls with numbers starting from 1.

After that I press "Add" of the second div "event", but the numbers starts not from 1, but from the last number of the first div "event".

Change the class "event" is not possible. In this example there are 2 div but they could be 3-4-5 or more, all with the class "event".

What can I do in order to start both the "event" from 1?

var i = 1;

$('.plus').click(function(e) {

  var $numberDiv = $('' + i + '').addClass('numberDiv');
  var $clear = $('
').addClass('clear');
  var $event = $(e.currentTarget).closest('.event');

  $event.find('.participantContainer').append($numberDiv);

  i++;
})

$('.minus').click(function(e) {
  var $numberDiv = $(''> + i + '').addClass('numberDiv');
  var $clear = $('
').addClass('clear');
  var $event = $(e.currentTarget).closest('.event');

  $event.find('.numberDiv:last').remove();

  i--;
})

$('.reset').click(function() {
 i = 1;
  $('.numberDiv').each(function() {
   $(this).remove();
  })
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    font-family: sans-serif;
}

button {
    background: none;
}

.clear {
  clear: both;
}

.plus,
.minus,
.reset {
  height: 33px;
    font-size: 20px;
    cursor: pointer;
    margin-right: 2px;
    float: left;
    margin-bottom: 10px;
    border-radius: 10px;
    padding: 0 0 0 0;
}

.plus {
  border: 2px solid green;
  width: 56px;
}

.plus:hover {
  background-color: green;
}

.minus:hover {
  background-color:red;
}

.minus {
  border: 2px solid red;
  width: 95px;
}

.reset {
  border: 2px solid blue;
  width: 95px;
}

.reset:hover {
  background-color: lightblue;
}

.numberDiv {
  font-size: 20px;
  position: relative;
  top: -5px;
  margin-right: 10px;
}

.numberDiv:before {
  content:'☠';
  font-size: 30px;
}

.participantContainer {
  float: left;
}</code>```

  <button class="plus">Add</button>
  <button class="minus">Remove</button>

  <button class="plus">Add</button>
  <button class="minus">Remove</button>

<button class="reset">Reset</button>```

The main reason is of course that I'm learning and I don't have a lot of experience with jQuery.

Thanks in Advance!

答:
You can use the count of existing skulls, and have your reset, just delete them. You could skip the counter altogether.

var currentCount = $(e.currentTarget).closest('.event').find('.participantContainer').children('span').length;

Uses the length property to get the current count. Then increment it by one.

$('.plus').click(function(e) {
  var currentCount = $(e.currentTarget).closest('.event').find('.participantContainer').children('span').length;

  var $numberDiv = $('' + (currentCount+1) + '').addClass('numberDiv');
  var $clear = $('
').addClass('clear');
  var $event = $(e.currentTarget).closest('.event');

  $event.find('.participantContainer').append($numberDiv);
})

$('.minus').click(function(e) {

  var $event = $(e.currentTarget).closest('.event');
  $event.find('.numberDiv:last').remove();
})

$('.reset').click(function() {
  $('.numberDiv').each(function() {
   $(this).remove();
  })
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    font-family: sans-serif;
}

button {
    background: none;
}

.clear {
  clear: both;
}

.plus,
.minus,
.reset {
  height: 33px;
    font-size: 20px;
    cursor: pointer;
    margin-right: 2px;
    float: left;
    margin-bottom: 10px;
    border-radius: 10px;
    padding: 0 0 0 0;
}

.plus {
  border: 2px solid green;
  width: 56px;
}

.plus:hover {
  background-color: green;
}

.minus:hover {
  background-color:red;
}

.minus {
  border: 2px solid red;
  width: 95px;
}

.reset {
  border: 2px solid blue;
  width: 95px;
}

.reset:hover {
  background-color: lightblue;
}

.numberDiv {
  font-size: 20px;
  position: relative;
  top: -5px;
  margin-right: 10px;
}

.numberDiv:before {
  content:'☠';
  font-size: 30px;
}

.participantContainer {
  float: left;
}</code>```

  <button class="plus">Add</button>
  <button class="minus">Remove</button>

  <button class="plus">Add</button>
  <button class="minus">Remove</button>

<button class="reset">Reset</button>```

Body:
I'm using jQuery in order to create dinamically input forms. I made an example of my code (this example doesn't creates input forms but it works exacly as my script, and it reproduce the same error) that you can play in order to understand better what I mean.

The problem is that if I press "Add" of the first div "event", my jQuery produces the skulls with numbers starting from 1.

After that I press "Add" of the second div "event", but the numbers starts not from 1, but from the last number of the first div "event".

Change the class "event" is not possible. In this example there are 2 div but they could be 3-4-5 or more, all with the class "event".

What can I do in order to start both the "event" from 1?

var i = 1;

$('.plus').click(function(e) {

  var $numberDiv = $('' + i + '').addClass('numberDiv');
  var $clear = $('
').addClass('clear');
  var $event = $(e.currentTarget).closest('.event');

  $event.find('.participantContainer').append($numberDiv);

  i++;
})

$('.minus').click(function(e) {
  var $numberDiv = $(''> + i + '').addClass('numberDiv');
  var $clear = $('
').addClass('clear');
  var $event = $(e.currentTarget).closest('.event');

  $event.find('.numberDiv:last').remove();

  i--;
})

$('.reset').click(function() {
 i = 1;
  $('.numberDiv').each(function() {
   $(this).remove();
  })
})

body {
    font-family: sans-serif;
}

button {
    background: none;
}

.clear {
  clear: both;
}

.plus,
.minus,
.reset {
  height: 33px;
    font-size: 20px;
    cursor: pointer;
    margin-right: 2px;
    float: left;
    margin-bottom: 10px;
    border-radius: 10px;
    padding: 0 0 0 0;
}

.plus {
  border: 2px solid green;
  width: 56px;
}

.plus:hover {
  background-color: green;
}

.minus:hover {
  background-color:red;
}

.minus {
  border: 2px solid red;
  width: 95px;
}

.reset {
  border: 2px solid blue;
  width: 95px;
}

.reset:hover {
  background-color: lightblue;
}

.numberDiv {
  font-size: 20px;
  position: relative;
  top: -5px;
  margin-right: 10px;
}

.numberDiv:before {
  content:'☠';
  font-size: 30px;
}

.participantContainer {
  float: left;
}

  <button class="plus">Add</button>
  <button class="minus">Remove</button>

  <button class="plus">Add</button>
  <button class="minus">Remove</button>

<button class="reset">Reset</button>

The main reason is of course that I'm learning and I don't have a lot of experience with jQuery.

Thanks in Advance!

Body:
You can use the count of existing skulls, and have your reset, just delete them. You could skip the counter altogether.

var currentCount = $(e.currentTarget).closest('.event').find('.participantContainer').children('span').length;

Uses the length property to get the current count. Then increment it by one.

$('.plus').click(function(e) {
  var currentCount = $(e.currentTarget).closest('.event').find('.participantContainer').children('span').length;

  var $numberDiv = $('<span>' + (currentCount+1) + '</span>').addClass('numberDiv');
  var $clear = $('<div />').addClass('clear');
  var $event = $(e.currentTarget).closest('.event');

  $event.find('.participantContainer').append($numberDiv);
})

$('.minus').click(function(e) {

  var $event = $(e.currentTarget).closest('.event');
  $event.find('.numberDiv:last').remove();
})

$('.reset').click(function() {
  $('.numberDiv').each(function() {
   $(this).remove();
  })
})

body {
    font-family: sans-serif;
}

button {
    background: none;
}

.clear {
  clear: both;
}

.plus,
.minus,
.reset {
  height: 33px;
    font-size: 20px;
    cursor: pointer;
    margin-right: 2px;
    float: left;
    margin-bottom: 10px;
    border-radius: 10px;
    padding: 0 0 0 0;
}

.plus {
  border: 2px solid green;
  width: 56px;
}

.plus:hover {
  background-color: green;
}

.minus:hover {
  background-color:red;
}

.minus {
  border: 2px solid red;
  width: 95px;
}

.reset {
  border: 2px solid blue;
  width: 95px;
}

.reset:hover {
  background-color: lightblue;
}

.numberDiv {
  font-size: 20px;
  position: relative;
  top: -5px;
  margin-right: 10px;
}

.numberDiv:before {
  content:'☠';
  font-size: 30px;
}

.participantContainer {
  float: left;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="event">
  <button class="plus">Add</button>
  <button class="minus">Remove</button>
  <div class="participantContainer"></div>
</div>
<div class="clear"></div>
<div class="event">
  <button class="plus">Add</button>
  <button class="minus">Remove</button>
  <div class="participantContainer"></div>
</div>
<div class="clear"></div>
<button class="reset">Reset</button>


问:
Show another element if current input was changed
I want to show one element if current input was changed.

```<code>$('.type_number').change(function() {
  $(this)
  $('.check-update').css('display', 'block')
})
</code>```

<input class="type_number" type="number" name="amount" value="{{ product.amount }}">
<input type="hidden" name="product" value="{{ product.product.id }}">
<button type="submit" class="btn btn-link check-update">

</button>
```

How to say jquery if current was changed show another element

This creates a difficulty for me and besides I can not figure out how to do it. Please explain me if someone knows about it

答:
Using jQuery, if input element value is not empty and changed other than "myname", it shows the label with value "bob".

html

```<code><input id = "type_number" type = "text" value="myname"/>
<label id = "check-update" style="display:none;">bob</label>
</code>```

jQuery

```<code>$("#type_number").on("change keyup paste", function() {
    if($("#type_number").val() !== "" && $("#type_number").val() !== "myname")
        $("#check-update").css("display", "block");
   else
        $("#check-update").css("display", "none");
});
</code>```

jsFiddle demo

Body:
I want to show one element if current input was changed.

$('.type_number').change(function() {
  $(this)
  $('.check-update').css('display', 'block')
})

<input class="type_number" type="number" name="amount" value="{{ product.amount }}">
<input type="hidden" name="product" value="{{ product.product.id }}">
<button type="submit" class="btn btn-link check-update">

</button>

How to say jquery if current was changed show another element

This creates a difficulty for me and besides I can not figure out how to do it. Please explain me if someone knows about it

Body:
Using jQuery, if input element value is not empty and changed other than "myname", it shows the label with value "bob".

html

<input id = "type_number" type = "text" value="myname"/>
<label id = "check-update" style="display:none;">bob</label>

jQuery

$("#type_number").on("change keyup paste", function() {
    if($("#type_number").val() !== "" && $("#type_number").val() !== "myname")
        $("#check-update").css("display", "block");
   else
        $("#check-update").css("display", "none");
});

jsFiddle demo