问:
Is it well defined to create a BackgroundWorker object only referenced by a local variable?
I'm new to C# and WPF. I took hours reading online docs and examples to review some code. The code subclasses System.Windows.Controls.Page and use BackgroundWorker to do background computing.

From what I learned, the desired way to create a BackgroundWorker object in this case, is to make it referenced by a class member variable.

E.g.,

```<code>public class MyPage: System.Windows.Controls.Page
{
    // Or: backgroundWorker = new System.ComponentModel.BackgroundWorker()
    private System.ComponentModel.BackgroundWorker backgroundWorker;
    ..
}
</code>```

But the code under review creates the object referenced by a local variable.

```<code>// Inside a class member function
if (someCondition)
{
    BackgroundWorker worker = new BackgroundWorker();
    worker.WorkerSupportsCancellation = true;
    worker.WorkerReportsProgress = true;
    worker.DoWork += new DoWorkEventHandler(DoWork1);
    worker.DoWork += new DoWorkEventHandler(DoWork2);
    worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(RunWorkerCompleted);
    worker.RunWorkerAsync(this.DataContext);
}
</code>```

Is this well defined? Will the object be eligible for GC after worker is out of scope since it's the obvious sole reference to the object? Or the framework adds extra reference count(s) due to those asnyc function callbacks?

By "well-defined", I mean the worker object is guaranteed to stay in memory at least until all the callbacks (e.g., RunWorkerCompleted) are finished.

Thanks!

答:
The BackgroundWorker won't be immediately eligible for garbage collection provided that you call the RunWorkerAsync() method. You can confirm this yourself using a WeakReference:

```<code>BackgroundWorker worker = new BackgroundWorker();
worker.WorkerSupportsCancellation = true;
worker.WorkerReportsProgress = true;
worker.DoWork += new DoWorkEventHandler(DoWork1);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(RunWorkerCompleted);
worker.RunWorkerAsync();

WeakReference viewModelWeakReference = new WeakReference(worker);
worker = null;
GC.Collect();
GC.WaitForPendingFinalizers();
MessageBox.Show(viewModelWeakReference.IsAlive.ToString());
</code>```

Even if you dispose it right after you have called RunWorkerAsync(), it will still hang around until it has finished.

Body:
I'm new to C# and WPF. I took hours reading online docs and examples to review some code. The code subclasses System.Windows.Controls.Page and use BackgroundWorker to do background computing.

From what I learned, the desired way to create a BackgroundWorker object in this case, is to make it referenced by a class member variable.

E.g.,

public class MyPage: System.Windows.Controls.Page
{
    // Or: backgroundWorker = new System.ComponentModel.BackgroundWorker()
    private System.ComponentModel.BackgroundWorker backgroundWorker;
    ..
}

But the code under review creates the object referenced by a local variable.

// Inside a class member function
if (someCondition)
{
    BackgroundWorker worker = new BackgroundWorker();
    worker.WorkerSupportsCancellation = true;
    worker.WorkerReportsProgress = true;
    worker.DoWork += new DoWorkEventHandler(DoWork1);
    worker.DoWork += new DoWorkEventHandler(DoWork2);
    worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(RunWorkerCompleted);
    worker.RunWorkerAsync(this.DataContext);
}

Is this well defined? Will the object be eligible for GC after worker is out of scope since it's the obvious sole reference to the object? Or the framework adds extra reference count(s) due to those asnyc function callbacks?

By "well-defined", I mean the worker object is guaranteed to stay in memory at least until all the callbacks (e.g., RunWorkerCompleted) are finished.

Thanks!

Body:
The BackgroundWorker won't be immediately eligible for garbage collection provided that you call the RunWorkerAsync() method. You can confirm this yourself using a WeakReference:

BackgroundWorker worker = new BackgroundWorker();
worker.WorkerSupportsCancellation = true;
worker.WorkerReportsProgress = true;
worker.DoWork += new DoWorkEventHandler(DoWork1);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(RunWorkerCompleted);
worker.RunWorkerAsync();

WeakReference viewModelWeakReference = new WeakReference(worker);
worker = null;
GC.Collect();
GC.WaitForPendingFinalizers();
MessageBox.Show(viewModelWeakReference.IsAlive.ToString());

Even if you dispose it right after you have called RunWorkerAsync(), it will still hang around until it has finished.


来源: stackexchange

问:
Three.js/WebGL: Large spheres appear broken at intersection
Let me preface this with saying I'm very inexperienced with 3D graphics.

Problem

I'm using Three.js. I have two spheres which (deliberately) collide in my WebGL model. When my spheres are incredibly large, the overlapping spheres appear "broken" where they intersect, but smaller spheres render perfectly fine.

I have a very specific reason for using such large units for some objects, and scaling down objects isn't really an option.

Example

Here is a fiddle for the larger spheres: http://jsfiddle.net/YSX7h/

and for the smaller ones: http://jsfiddle.net/7Lca2/

Code

```<code>var radiusUnits = 1790; // 179000000
var container;
var camera, scene, renderer;
var clock = new THREE.Clock();
var cross;
var plane;
var controls;
var cube;
var cubeMaterial = new THREE.MeshBasicMaterial( { color: 0xffffff, vertexColors: THREE.VertexColors } );
init();
animate();

function init() {
    camera = new THREE.PerspectiveCamera(100, window.innerWidth / window.innerHeight, 0.1, 3500000);
    controls = new THREE.OrbitControls(camera);
    camera.position.set(2000, 2000, 2000);
    camera.position.z = 500;
    scene = new THREE.Scene();

    var texture = THREE.ImageUtils.loadTexture('http://i.imgur.com/qDAEVoo.jpg');
    var material = new THREE.MeshBasicMaterial({
        color: 0xFFFFFF,
        map: texture,
        opacity:1
    });

    var material1 = new THREE.MeshBasicMaterial({ color: 0xFF0000, wireframe: true, opacity:1 });
    var geometry = new THREE.SphereGeometry(radiusUnits, 32, 32);
    var geometry1 = new THREE.SphereGeometry(radiusUnits, 32, 32);
    var mesh = new THREE.Mesh(geometry, material);
    var mesh1 = new THREE.Mesh(geometry1, material1);
    mesh1.position.set(0, 1000, 0);
    mesh.position.set(0, -1000, 0);

    scene.add(mesh);
    scene.add(mesh1);

    renderer = new THREE.WebGLRenderer( { antialias: true, alpha: true } );

    document.body.appendChild(renderer.domElement);
    renderer.setSize( window.innerWidth, window.innerHeight );
}

function onWindowResize() {
    renderer.setSize( window.innerWidth, window.innerHeight );
    render();
}

function animate() {
    controls.update();
    requestAnimationFrame( animate );
}

window.requestAnimFrame = (function(){
    return  window.requestAnimationFrame       ||
                window.webkitRequestAnimationFrame ||
                window.mozRequestAnimationFrame    ||
                window.oRequestAnimationFrame      ||
                window.msRequestAnimationFrame     ||
                function( callback ){
                  window.setTimeout(callback, 1000 / 60);
                };
})();

(function animloop(){
    requestAnimFrame(animloop);
    render();
})();

function render() {
    var delta = clock.getDelta();
    renderer.render( scene, camera );
}
</code>```

Why, exactly, does this happen? And is there anything I can do to fix this, short of scaling down these objects?

Thanks in advance.

答:
You could also try using a logarithmic depth buffer:</p>

```<code>renderer = new THREE.WebGLRenderer( { logarithmicDepthBuffer: true } );
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Let me preface this with saying I'm very inexperienced with 3D graphics.

Problem

I'm using Three.js. I have two spheres which (deliberately) collide in my WebGL model. When my spheres are incredibly large, the overlapping spheres appear "broken" where they intersect, but smaller spheres render perfectly fine.

I have a very specific reason for using such large units for some objects, and scaling down objects isn't really an option.

Example

Here is a fiddle for the larger spheres: http://jsfiddle.net/YSX7h/

and for the smaller ones: http://jsfiddle.net/7Lca2/

Code

var radiusUnits = 1790; // 179000000
var container;
var camera, scene, renderer;
var clock = new THREE.Clock();
var cross;
var plane;
var controls;
var cube;
var cubeMaterial = new THREE.MeshBasicMaterial( { color: 0xffffff, vertexColors: THREE.VertexColors } );
init();
animate();

function init() {
    camera = new THREE.PerspectiveCamera(100, window.innerWidth / window.innerHeight, 0.1, 3500000);
    controls = new THREE.OrbitControls(camera);
    camera.position.set(2000, 2000, 2000);
    camera.position.z = 500;
    scene = new THREE.Scene();

    var texture = THREE.ImageUtils.loadTexture('http://i.imgur.com/qDAEVoo.jpg');
    var material = new THREE.MeshBasicMaterial({
        color: 0xFFFFFF,
        map: texture,
        opacity:1
    });

    var material1 = new THREE.MeshBasicMaterial({ color: 0xFF0000, wireframe: true, opacity:1 });
    var geometry = new THREE.SphereGeometry(radiusUnits, 32, 32);
    var geometry1 = new THREE.SphereGeometry(radiusUnits, 32, 32);
    var mesh = new THREE.Mesh(geometry, material);
    var mesh1 = new THREE.Mesh(geometry1, material1);
    mesh1.position.set(0, 1000, 0);
    mesh.position.set(0, -1000, 0);

    scene.add(mesh);
    scene.add(mesh1);

    renderer = new THREE.WebGLRenderer( { antialias: true, alpha: true } );

    document.body.appendChild(renderer.domElement);
    renderer.setSize( window.innerWidth, window.innerHeight );
}

function onWindowResize() {
    renderer.setSize( window.innerWidth, window.innerHeight );
    render();
}

function animate() {
    controls.update();
    requestAnimationFrame( animate );
}

window.requestAnimFrame = (function(){
    return  window.requestAnimationFrame       ||
                window.webkitRequestAnimationFrame ||
                window.mozRequestAnimationFrame    ||
                window.oRequestAnimationFrame      ||
                window.msRequestAnimationFrame     ||
                function( callback ){
                  window.setTimeout(callback, 1000 / 60);
                };
})();

(function animloop(){
    requestAnimFrame(animloop);
    render();
})();

function render() {
    var delta = clock.getDelta();
    renderer.render( scene, camera );
}

Why, exactly, does this happen? And is there anything I can do to fix this, short of scaling down these objects?

Thanks in advance.

Body:
You could also try using a logarithmic depth buffer:

renderer = new THREE.WebGLRenderer( { logarithmicDepthBuffer: true } );


问:
Create APFS RAM disk on macOS High Sierra
usually creating RAM disks works with the following commands

```<code>hdid -nomount ram://<blocksize>
</code>```

Returns e.g. /dev/disk2
Then I would format the disk, with say

```<code>newfs_hfs /dev/disk2
</code>```

followed by mounting it:

```<code>mount -t hfs /dev/disk2 /some/mount/target
</code>```

This procedure doesn't seem to work with APFS. I'm on High Sierra beta 9. The mount command doesn't output any error, but the path is not mounted.

In my case, after the hdid command finished, newfs_apfs -i /dev/disk2 yields

```<code>nx_kernel_mount:1364: checkpoint search: largest xid 1, best xid 1 @ 1
nx_kernel_mount:1422: sanity checking all nx state... please be patient.
spaceman_metazone_init:278: no metazone for device 0, of size 209715200 bytes, block_size 4096
apfs_newfs:18075: FS will NOT be encrypted.
</code>```

When I then enter mount -t apfs /dev/disk2 /some/target/path then the mount commands seems to work for 2 seconds, doesn't give any output and the mount was NOT succesful.

Can anyone tell me how to actually make a APFS RAM disk s.t. it works? :p

PS: I've also tried something like diskutil partitionDisk /dev/disk2 GPT APFS myvolumename 0b which does mount the volume to /Volumes/myvolumename but creates yet another disk (disk3 in this case) which seems odd to me!

答:
@Glyph provided the best answer in a comment to the accepted answer, but it deserves its own answer:

```<code>diskutil partitionDisk $(hdiutil attach -nomount ram://$((2048*sizeInMB))) 1 GPTFormat APFS 'Ramdisk' '100%'
</code>```

Change sizeInMB to your desired size.

I've updated Glyph's answer to simplify the volume name a little.

Body:
usually creating RAM disks works with the following commands

hdid -nomount ram://<blocksize>

Returns e.g. /dev/disk2
Then I would format the disk, with say

newfs_hfs /dev/disk2

followed by mounting it:

mount -t hfs /dev/disk2 /some/mount/target

This procedure doesn't seem to work with APFS. I'm on High Sierra beta 9. The mount command doesn't output any error, but the path is not mounted.

In my case, after the hdid command finished, newfs_apfs -i /dev/disk2 yields

nx_kernel_mount:1364: checkpoint search: largest xid 1, best xid 1 @ 1
nx_kernel_mount:1422: sanity checking all nx state... please be patient.
spaceman_metazone_init:278: no metazone for device 0, of size 209715200 bytes, block_size 4096
apfs_newfs:18075: FS will NOT be encrypted.

When I then enter mount -t apfs /dev/disk2 /some/target/path then the mount commands seems to work for 2 seconds, doesn't give any output and the mount was NOT succesful.

Can anyone tell me how to actually make a APFS RAM disk s.t. it works? :p

PS: I've also tried something like diskutil partitionDisk /dev/disk2 GPT APFS myvolumename 0b which does mount the volume to /Volumes/myvolumename but creates yet another disk (disk3 in this case) which seems odd to me!

Body:
@Glyph provided the best answer in a comment to the accepted answer, but it deserves its own answer:

diskutil partitionDisk $(hdiutil attach -nomount ram://$((2048*sizeInMB))) 1 GPTFormat APFS 'Ramdisk' '100%'

Change sizeInMB to your desired size.

I've updated Glyph's answer to simplify the volume name a little.

ContentLicense: CC BY-SA 4.0


问:
ng-bootstrap and Angular 5 compatibility
Was ng-bootstrap already tested with Angular 5 and is it compatible ?

If not, any compatible ng-bootsrap angular 5 release planned ?

Thanks !

答:
There is a pull request to add angular 5 support for ng-bootstrap.

I hope it will be released soon.

UPDATE:

It's now released: https://github.com/ng-bootstrap/ng-bootstrap/blob/master/CHANGELOG.md#100-beta7-2017-12-08


问:
Does Observable.race for two observables work more than one time?
Tasks is: I have two effects (ngrx/store), let's say ef1$ and ef2$, which are Observables. In angular component I would like to detect which one is triggered. I added the following code:

```<code> Observable.race(ef1$, ef2$)
     .subscribe((payload) => {
          if (payload.type == ThreadActions.THREAD_READY_TO_BE_RENDERED) {
            // do one thing
          }
          else if (payload.type == ThreadActions.THREAD_ITEM_READY_TO_BE_RENDERED) {
            // do another thing
          }
        });
</code>```

But it looks like that after first emit of any effects Observable.race is going to be dead and no reaction more on additional emits, despite of I sure that effect executes again and again.

答:
Observable.race() will only emit whichever the emission comes first.

If you want two Observable streams and observe them concurrently aka you do not care whoever will be emitting, use Observable.combineLatest:

```<code>Observable.combineLatest(ef1$, ef2$)
    .subscribe(([ef1,ef2]) => {

        //ef1.type will be ThreadActions.THREAD_READY_TO_BE_RENDERED
        //ef2.type will be ThreadActions.THREAD_ITEM_READY_TO_BE_RENDERED

        //check if ef1 is truthy
        if(ef1){
            //do one thing
        }
        if(ef2){
            //do another thing
        }
    });
</code>```

Body:
Tasks is: I have two effects (ngrx/store), let's say ef1$ and ef2$, which are Observables. In angular component I would like to detect which one is triggered. I added the following code:

 Observable.race(ef1$, ef2$)
     .subscribe((payload) => {
          if (payload.type == ThreadActions.THREAD_READY_TO_BE_RENDERED) {
            // do one thing
          }
          else if (payload.type == ThreadActions.THREAD_ITEM_READY_TO_BE_RENDERED) {
            // do another thing
          }
        });

But it looks like that after first emit of any effects Observable.race is going to be dead and no reaction more on additional emits, despite of I sure that effect executes again and again.

Body:
Observable.race() will only emit whichever the emission comes first.

If you want two Observable streams and observe them concurrently aka you do not care whoever will be emitting, use Observable.combineLatest:

Observable.combineLatest(ef1$, ef2$)
    .subscribe(([ef1,ef2]) => {

        //ef1.type will be ThreadActions.THREAD_READY_TO_BE_RENDERED
        //ef2.type will be ThreadActions.THREAD_ITEM_READY_TO_BE_RENDERED

        //check if ef1 is truthy
        if(ef1){
            //do one thing
        }
        if(ef2){
            //do another thing
        }
    });


问:
Connecting with MySQL Provider
We can write SQL Command from Variable in OLE DB Source Task. How do we get SQL Command from variable in ADO Net Source Task ? Here My Source is MySQL. Because I want to pass a parameter in this SQL Command at WHERE clause. I dont find SQL Command from Variable in ADO.Net Source task. And I cant connect to MySQL in OLE DB Task.</p>

答:
You can use an expression to specify a variable by doing the following:

On the Control Flow, right click on the Data Flow task and select Properties

On the Properties window, click the ellipsis for Expressions

Choose the [ADO NET Source].[SqlCommand] from the Property drop down and click the ellipsis to go to Expression Builder

In Expression Builder you can reference your variables and add in any SQL clauses you need.

Here is a very rough example...

ContentLicense: CC BY-SA 2.5

Title: Connecting with MySQL Provider


问:
Linux group by, sum and count
From a directory listing, I have created an output that presents file size in column 1 and a section of the filename (it's a date) in column 2.

```<code>178694671 2017-10-14
175332227 2017-10-14
175021608 2017-10-14
174851281 2017-10-14
175316643 2017-10-14
</code>```

What I now need to do is group by, sum and count on this list. Group by and count files by column 2, and sum the file size associated with each grouping.

The result of the above output would look like this:

```<code>879216430 2017-10-14 5
</code>```

I tried this

```<code>awk '{sum[$1]+= $2;}END{for (date in sum){print sum[date], date;}}'
</code>```

But it provides strange results and I don't really understand what it's doing.

Can anyone help?

答:
Use another associated array to store frequency of date as in:

```<code>awk '{++freq[$2]; sum[$2]+=$1}
END{for (date in sum) print sum[date], date, freq[date]}' file

879216430 2017-10-14 5
</code>```

Also note key of your array would be $2 i.e. date not $1

Title: Linux group by, sum and count

Body:
From a directory listing, I have created an output that presents file size in column 1 and a section of the filename (it's a date) in column 2.

178694671 2017-10-14
175332227 2017-10-14
175021608 2017-10-14
174851281 2017-10-14
175316643 2017-10-14

What I now need to do is group by, sum and count on this list. Group by and count files by column 2, and sum the file size associated with each grouping.

The result of the above output would look like this:

879216430 2017-10-14 5

I tried this

awk '{sum[$1]+= $2;}END{for (date in sum){print sum[date], date;}}'

But it provides strange results and I don't really understand what it's doing.

Can anyone help?

Body:
Use another associated array to store frequency of date as in:

awk '{++freq[$2]; sum[$2]+=$1}
END{for (date in sum) print sum[date], date, freq[date]}' file

879216430 2017-10-14 5

Also note key of your array would be $2 i.e. date not $1


问:
How to change a value when a list object is selected
I have a master list of products and stock counts (see image below), but I want for when a product is selected (on another sheet) for the stock count to be subtracted by 1.

Example data set

What is the best way of doing this? (I tired a bit of VBA but didn't get too far)

Edit:

Here is how my mind would picture it working:
How I picture how it would work

答:
Basic VBA Example.

The Worksheet_Change event needs to be on the sheet that contains the dropdown.

Just check to see if the address of the changed cell is the address of your dropdown. You can use a named range or you can just use a static address as I did below.

I gave the list a named range called Items which we can reference.

Please note that on a separate sheet, you would need to use Sheets("SheetName").Range("Items")

I also used a simple For Each loop to check the values in the list - it may be better if it gets large enough to use a dictionary, variant array, or Find.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$H$4" Then
    Dim c
    For Each c In Range("Items")
        If c = Target.Value Then
            c.Offset(0, 1).Value = c.Offset(0, 1).Value - 1
            Exit For
        End If
    Next c
End If
End Sub
</code>```

Body:
Basic VBA Example.

The Worksheet_Change event needs to be on the sheet that contains the dropdown.

Just check to see if the address of the changed cell is the address of your dropdown. You can use a named range or you can just use a static address as I did below.

I gave the list a named range called Items which we can reference.

Please note that on a separate sheet, you would need to use Sheets("SheetName").Range("Items")

I also used a simple For Each loop to check the values in the list - it may be better if it gets large enough to use a dictionary, variant array, or Find.

Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$H$4" Then
    Dim c
    For Each c In Range("Items")
        If c = Target.Value Then
            c.Offset(0, 1).Value = c.Offset(0, 1).Value - 1
            Exit For
        End If
    Next c
End If
End Sub


问:
Template type deduction for member variables and function arguments
Consider the following implementation of a template class:

```<code>template<class T>
class MyClass
{
public:
    void setVar1(const T& v1)
    {
        var1 = v1;
    }
    void setVar2(const T1& v2)
    {
        var2 = v2;
    }

    T var1;
    T1 var2;
};
</code>```

If the template parameter T is a fundamental type (like float, double, or long double) I would like to have T1 = T.

If the template parameter T is std::complex<float>, I would like to have T=std::complex<float> and T1 = float. Similarly for std::complex<double> and std::complex<long double>.

Deducing the type of the variable is discussed at Template type derivation

However, the additional member functions prevents usage of their solution in this context.

答:
A custom traits class would suffice. You can leverage partial specializations to select the type you want/need. Example code

```<code>template<typename T, bool F> class Base;

template<typename T>
class Base <T, true> {
public:
  T var2;
};

template<typename T>
class Base <std::complex<T>, false> {
public:
  typename std::complex<T>::value_type var2;
};

template <typename T>
class BaseHelper : public Base<T, std::is_fundamental<T>::value> {};

template<class T>
class MyClass : public BaseHelper<T> {
public:

  using T1 = decltype(BaseHelper<T>::var2);

  void setVar1(const T& v1) {
    var1 = v1;
  }
  void setVar2(const T1& v2) {
    this->var2 = v2;
  }

  T var1;
};
</code>```

Live Example

There are many other ways though.

Body:
Consider the following implementation of a template class:

template<class T>
class MyClass
{
public:
    void setVar1(const T& v1)
    {
        var1 = v1;
    }
    void setVar2(const T1& v2)
    {
        var2 = v2;
    }

    T var1;
    T1 var2;
};

If the template parameter T is a fundamental type (like float, double, or long double) I would like to have T1 = T.

If the template parameter T is std::complex<float>, I would like to have T=std::complex<float> and T1 = float. Similarly for std::complex<double> and std::complex<long double>.

Deducing the type of the variable is discussed at Template type derivation

However, the additional member functions prevents usage of their solution in this context.

Body:
A custom traits class would suffice. You can leverage partial specializations to select the type you want/need. Example code

template<typename T, bool F> class Base;

template<typename T>
class Base <T, true> {
public:
  T var2;
};

template<typename T>
class Base <std::complex<T>, false> {
public:
  typename std::complex<T>::value_type var2;
};

template <typename T>
class BaseHelper : public Base<T, std::is_fundamental<T>::value> {};

template<class T>
class MyClass : public BaseHelper<T> {
public:

  using T1 = decltype(BaseHelper<T>::var2);

  void setVar1(const T& v1) {
    var1 = v1;
  }
  void setVar2(const T1& v2) {
    this->var2 = v2;
  }

  T var1;
};

Live Example

There are many other ways though.


问:
Get minX, maxX, minY, maxY from multidimensional array
I have an array like this

```<code>var my_array = [
  [3,9],
  [1,5],
  [7,2],
  [5,4]
 ]
</code>```

As you can see my_array is a multidimensional array that includes in this case 4 different arrays.

All of the arrays are x/y-coordinates ([3,9] ---> X: 3, Y: 9) and I'd like to move the arrays of the array with ...

the biggest X value,

the biggest Y value,

the smallest X value,

the smallest Y value

... to an object like this:

```<code>var my_object = {
  "minX": [1,5],
  "maxX": [7,2],
  "minY": [7,2],
  "maxY": [3,9]
}
</code>```

The function I've created you can find below, but my function is just returning the listed values from above instead of returning the full array. So my current (wrong) result looks like this:

```<code>var wrong_object = {
  "minX": 1, // missing 5
  "maxX": 7, // missing 2
  "minY": 2, // missing 7
  "maxY": 9  // missing 3
}
</code>```

var my_array = [
  [3, 9],
  [1, 5],
  [7, 2],
  [5, 4]
]

var extreme_result = {}
extreme_result.minX = Math.min.apply(Math, my_array.map(function(i) {
  return i[0]
}));
extreme_result.maxX = Math.max.apply(Math, my_array.map(function(i) {
  return i[0]
}));
extreme_result.minY = Math.min.apply(Math, my_array.map(function(i) {
  return i[1]
}));
extreme_result.maxY = Math.max.apply(Math, my_array.map(function(i) {
  return i[1]
}));

console.log(extreme_result)```

I hope somebody can help me with this problem.

Thanks in advance, Greetings Pete

答:
```<code>function findExtremes( array ){
  let maxX = array[0],
       maxY = array[0],
       minX = array[0],
       minY = array[0];

  for(const [x,y] of array){
    if(x < minX[0]) minX = [x,y];
    if(x > maxX[0]) maxX = [x,y];

    if(y > minY[1]) minY = [x,y];
    if(y < maxY[1]) maxY = [x,y];
  }

  return {maxX, maxY, minX, minY};
}
</code>```

This is O(n) ...

Body:
I have an array like this

var my_array = [
  [3,9],
  [1,5],
  [7,2],
  [5,4]
 ]

As you can see my_array is a multidimensional array that includes in this case 4 different arrays.

All of the arrays are x/y-coordinates ([3,9] ---> X: 3, Y: 9) and I'd like to move the arrays of the array with ...

the biggest X value,

the biggest Y value,

the smallest X value,

the smallest Y value

... to an object like this:

var my_object = {
  "minX": [1,5],
  "maxX": [7,2],
  "minY": [7,2],
  "maxY": [3,9]
}

The function I've created you can find below, but my function is just returning the listed values from above instead of returning the full array. So my current (wrong) result looks like this:

var wrong_object = {
  "minX": 1, // missing 5
  "maxX": 7, // missing 2
  "minY": 2, // missing 7
  "maxY": 9  // missing 3
}

var my_array = [
  [3, 9],
  [1, 5],
  [7, 2],
  [5, 4]
]

var extreme_result = {}
extreme_result.minX = Math.min.apply(Math, my_array.map(function(i) {
  return i[0]
}));
extreme_result.maxX = Math.max.apply(Math, my_array.map(function(i) {
  return i[0]
}));
extreme_result.minY = Math.min.apply(Math, my_array.map(function(i) {
  return i[1]
}));
extreme_result.maxY = Math.max.apply(Math, my_array.map(function(i) {
  return i[1]
}));

console.log(extreme_result)

I hope somebody can help me with this problem.

Thanks in advance, Greetings Pete

Body:
function findExtremes( array ){
  let maxX = array[0],
       maxY = array[0],
       minX = array[0],
       minY = array[0];

  for(const [x,y] of array){
    if(x < minX[0]) minX = [x,y];
    if(x > maxX[0]) maxX = [x,y];

    if(y > minY[1]) minY = [x,y];
    if(y < maxY[1]) maxY = [x,y];
  }

  return {maxX, maxY, minX, minY};
}

This is O(n) ...


问:
elixir map with mixed keys
in the Phoenix application, I have a function that takes two maps, and creates two entries in the database via Ecto.Changeset.

```<code>def create_user_with_data(user_attrs, data_attrs) do
    name = cond do
        data_attrs["name"] ->
            data_attrs["name"]
        data_attrs[:name] ->
            data_attrs[:name]
        true -> nil
    end
    Ecto.Multi.new()
    |> Ecto.Multi.insert(:user, User.registration_changeset(%User{}, Map.put(user_attrs, :name, name)))
    |> Ecto.Multi.run(:user_data, fn(%{user: user}) ->
        %MyApp.Account.UserData{}
        |> MyApp.Account.UserData.changeset(Map.put(data_attrs, :user_id, user.id))
        |> Repo.insert()
    end)
    |> Repo.transaction()
end
</code>```

because the keys in these map can be both atoms and lines, I have to check these keys.

but the expression

```<code>Map.put(user_attrs, :name, name)
</code>```

will cause an error

```<code>** (Ecto.CastError) expected params to be a map with atoms or string keys, got a map with mixed keys: %{:name => "John", "email" => "m@gmail.com"}
</code>```

if the keys are strings.

Is there any best practice in dealing with this issue?

答:
Explicitly cast all the keys to strings with Kernel.to_string/1:

```<code>data_attrs = for {k, v} <- data_attrs,
               do: {to_string(k), v}, into: %{}
</code>```

Title: elixir map with mixed keys

Body:
in the Phoenix application, I have a function that takes two maps, and creates two entries in the database via Ecto.Changeset.

def create_user_with_data(user_attrs, data_attrs) do
    name = cond do
        data_attrs["name"] ->
            data_attrs["name"]
        data_attrs[:name] ->
            data_attrs[:name]
        true -> nil
    end
    Ecto.Multi.new()
    |> Ecto.Multi.insert(:user, User.registration_changeset(%User{}, Map.put(user_attrs, :name, name)))
    |> Ecto.Multi.run(:user_data, fn(%{user: user}) ->
        %MyApp.Account.UserData{}
        |> MyApp.Account.UserData.changeset(Map.put(data_attrs, :user_id, user.id))
        |> Repo.insert()
    end)
    |> Repo.transaction()
end

because the keys in these map can be both atoms and lines, I have to check these keys.

but the expression

Map.put(user_attrs, :name, name)

will cause an error

** (Ecto.CastError) expected params to be a map with atoms or string keys, got a map with mixed keys: %{:name => "John", "email" => "m@gmail.com"}

if the keys are strings.

Is there any best practice in dealing with this issue?

Body:
Explicitly cast all the keys to strings with Kernel.to_string/1:

data_attrs = for {k, v} <- data_attrs,
               do: {to_string(k), v}, into: %{}


问:
Xamarin.Forms - Difference between Button.TextProperty.PropertyName and nameof(myButton.Text)
Besides the syntax, is there any difference between:

```<code>Button.TextProperty.PropertyName //(Xamarin.Forms.BindableProperty.PropertyName)
</code>```

and

```<code>nameof(myButton.Text)
</code>```

Is one preferred over the other for any reasons besides personal preference?

答:
In practice they will be the same value.

nameof() is a compile time value, while Button.TextProperty.PropertyName isn't necessarily.

Button.TextProperty is a statically allocated object with a PropertyName property.

nameof() will be compiled into the source and likely be a faster access depending on your compiler optimizations.

Body:
Besides the syntax, is there any difference between:

Button.TextProperty.PropertyName //(Xamarin.Forms.BindableProperty.PropertyName)

and

nameof(myButton.Text)

Is one preferred over the other for any reasons besides personal preference?


答:
I'd convert all the keys to atoms first and then use atoms everywhere.

```<code>def key_to_atom(map) do
  Enum.reduce(map, %{}, fn
    {key, value}, acc when is_atom(key) -> Map.put(acc, key, value)
    # String.to_existing_atom saves us from overloading the VM by
    # creating too many atoms. It'll always succeed because all the fields
    # in the database already exist as atoms at runtime.
    {key, value}, acc when is_binary(key) -> Map.put(acc, String.to_existing_atom(key), value)
  end)
end
</code>```

Then, convert pass all such maps through this function:

```<code>user_attrs = user_attrs |> key_to_atom
data_attrs = data_attrs |> key_to_atom
</code>```

Now you can Map.put atom keys whenever you want to.

Title: elixir map with mixed keys

Body:
I'd convert all the keys to atoms first and then use atoms everywhere.

def key_to_atom(map) do
  Enum.reduce(map, %{}, fn
    {key, value}, acc when is_atom(key) -> Map.put(acc, key, value)
    # String.to_existing_atom saves us from overloading the VM by
    # creating too many atoms. It'll always succeed because all the fields
    # in the database already exist as atoms at runtime.
    {key, value}, acc when is_binary(key) -> Map.put(acc, String.to_existing_atom(key), value)
  end)
end

Then, convert pass all such maps through this function:

user_attrs = user_attrs |> key_to_atom
data_attrs = data_attrs |> key_to_atom

Now you can Map.put atom keys whenever you want to.


问:
Retrieve List of String from webservice in android
I am trying to retrieve List of String from my SoapObject.I am using KSoap2 to call my webservice which returns List of Strings.Here is my code

```<code>SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
</code>```

Can anybody help me to get all the list elements from my SoapPrimitive object.

like List abc =response.getList() or something??

答:
You can get the strings of your soapObject like this:</p>

```<code>SoapObject resSoap =(SoapObject)envelope.bodyIn;
int count = resSoap.getPropertyCount();
for (int i=0; i<count;i++){
    SoapObject so = (SoapObject) resSoap.getProperty(i);
    int idxic = so.getPropertyCount();
    lst= new String[idxic];
    String item;
    for (int e=0; e<idxic;e++){
        item=so.getProperty(e).toString();
        lst[e]=item;
    }
}
</code>```

Body:
I am trying to retrieve List of String from my SoapObject.I am using KSoap2 to call my webservice which returns List of Strings.Here is my code

SoapPrimitive response = (SoapPrimitive)envelope.getResponse();

Can anybody help me to get all the list elements from my SoapPrimitive object.

like List abc =response.getList() or something??

Body:
You can get the strings of your soapObject like this:

SoapObject resSoap =(SoapObject)envelope.bodyIn;
int count = resSoap.getPropertyCount();
for (int i=0; i<count;i++){
    SoapObject so = (SoapObject) resSoap.getProperty(i);
    int idxic = so.getPropertyCount();
    lst= new String[idxic];
    String item;
    for (int e=0; e<idxic;e++){
        item=so.getProperty(e).toString();
        lst[e]=item;
    }
}


问:
Can't seem to get submit/buttons/anchors to line up
Some times I may may want an anchor beside a submit button, but I always seem to have problems lining them up ...

```<code>a, input[type=submit], input[type=button], button {
  font-family: arial;
  background: #fff;
  color: #777;
  border: 1px solid #ccc;
  font-size: 12px;
  line-height: 20px !important;
  padding: 5px 10px;
  margin: 0;
}
</code>```

http://jsfiddle.net/cXgzM/

with that, anchors are still 2 pixels short

答:
Simply add this to your CSS:

```<code>a
{
    display: inline-block;
}
</code>```

I updated your example. Note that this property doesn't work in IE7 and lower. :)

Body:
Some times I may may want an anchor beside a submit button, but I always seem to have problems lining them up ...

a, input[type=submit], input[type=button], button {
  font-family: arial;
  background: #fff;
  color: #777;
  border: 1px solid #ccc;
  font-size: 12px;
  line-height: 20px !important;
  padding: 5px 10px;
  margin: 0;
}

http://jsfiddle.net/cXgzM/

with that, anchors are still 2 pixels short

Body:
Simply add this to your CSS:

a
{
    display: inline-block;
}

I updated your example. Note that this property doesn't work in IE7 and lower. :)


问:
Show data-attribute class from other class hovering
I´m using the following tooltip hint from this SO post.

JSFiddle here

.content {
  display: flex;
  flex-direction: column;
}

.area1 {
  background-color: red;
  height: 20px;
  width: 20px;
}

.area2 {
  background-color: orange;
  height: 20px;
  width: 20px;
}

.area3 {
  background-color: violet;
  height: 20px;
  width: 20px;
}

[tooltip]:before {
  position: absolute;
  content: attr(tooltip);
  opacity: 0;
}

[tooltip]:hover:before {
  opacity: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='content'>
  <div class='area1' tooltip='this is area 1'>
  </div>
  <div class='area2' tooltip='this is area 2'>
  </div>
  <div class='area3' tooltip='this is area 3'>
  </div>
</div></code>```

I need to show the tooltip only when hovering the area, not when hovering the tooltip (as shown).

I´ve tried:

```<code>.area1:hover [tooltip] {
    opacity: 1;
}
</code>```

and

```<code>.area1:hover [tooltip]:before {
    opacity: 1;
}
</code>```

Both cases I had no success.

答:
Use pointer-events: none on [tooltip]::before. It does exactly what it seems:

.content {
  display: flex;
  flex-direction: column;
}

.area {
  width: 20px;
  height: 20px;
}

#area1 { background-color: red; }
#area2 { background-color: orange; }
#area3 { background-color: violet; }

[tooltip]::before {
  position: absolute;
  content: attr(tooltip);
  opacity: 0;
  pointer-events: none;
}

[tooltip]:hover::before {
  opacity: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content">
  <div id="area1" class="area" tooltip="this is area 1"></div>
  <div id="area2" class="area" tooltip="this is area 2"></div>
  <div id="area3" class="area" tooltip="this is area 3"></div>
</div></code>```

Body:
I´m using the following tooltip hint from this SO post.

JSFiddle here

.content {
  display: flex;
  flex-direction: column;
}

.area1 {
  background-color: red;
  height: 20px;
  width: 20px;
}

.area2 {
  background-color: orange;
  height: 20px;
  width: 20px;
}

.area3 {
  background-color: violet;
  height: 20px;
  width: 20px;
}

[tooltip]:before {
  position: absolute;
  content: attr(tooltip);
  opacity: 0;
}

[tooltip]:hover:before {
  opacity: 1;
}

I need to show the tooltip only when hovering the area, not when hovering the tooltip (as shown).

I´ve tried:

.area1:hover [tooltip] {
    opacity: 1;
}

and

.area1:hover [tooltip]:before {
    opacity: 1;
}

Both cases I had no success.

Body:
Use pointer-events: none on [tooltip]::before. It does exactly what it seems:

.content {
  display: flex;
  flex-direction: column;
}

.area {
  width: 20px;
  height: 20px;
}

#area1 { background-color: red; }
#area2 { background-color: orange; }
#area3 { background-color: violet; }

[tooltip]::before {
  position: absolute;
  content: attr(tooltip);
  opacity: 0;
  pointer-events: none;
}

[tooltip]:hover::before {
  opacity: 1;
}

<div class="content">
  <div id="area1" class="area" tooltip="this is area 1"></div>
  <div id="area2" class="area" tooltip="this is area 2"></div>
  <div id="area3" class="area" tooltip="this is area 3"></div>
</div>


问:
Autodesk Forge: programmatically zoom out after focus on object by fitToView()
After select and focusing on an object with fitToView(objectIds, model),
I want to zoom out the camera programatically instead of via mouse events.

I tried the following code and it was able to zoom out, but the 3D space was distorted.
If you know how to correctly zoom out, please let me know.

```<code>// select and isolate target object
let dbid = [1137]
viewer.impl.visibilityManager.isolate(dbid, viewer.model)
viewer.select(dbid)

//focus on target object
viewer.getAggregateSelection((data) => {
    let rootId = data.selector.getInstanceTree().nodeAccess.rootId
    viewer.fitToView(rootId, viewer.model)
})

//zoom out camera
let cam = viewer.getCamera().perspectiveCamera
cam.zoom *= 0.05
viewer.impl.syncCamera();
</code>```

答:
It's not the zoom property that you need to change but the camera position:</p>

```<code>var nav = viewer.navigation

var pos = nav.getPosition()

var target = nav.getTarget()

var viewdir = new THREE.Vector3()

viewdir.subVectors (pos, target).normalize()

// zooms out by 100 along the view direction
viewdir.multiplyScalar (100)

pos.add(viewdir)

nav.setPosition(pos)
</code>```

Body:
After select and focusing on an object with fitToView(objectIds, model),
I want to zoom out the camera programatically instead of via mouse events.

I tried the following code and it was able to zoom out, but the 3D space was distorted.
If you know how to correctly zoom out, please let me know.

// select and isolate target object
let dbid = [1137]
viewer.impl.visibilityManager.isolate(dbid, viewer.model)
viewer.select(dbid)

//focus on target object
viewer.getAggregateSelection((data) => {
    let rootId = data.selector.getInstanceTree().nodeAccess.rootId
    viewer.fitToView(rootId, viewer.model)
})

//zoom out camera
let cam = viewer.getCamera().perspectiveCamera
cam.zoom *= 0.05
viewer.impl.syncCamera();

Body:
It's not the zoom property that you need to change but the camera position:

var nav = viewer.navigation

var pos = nav.getPosition()

var target = nav.getTarget()

var viewdir = new THREE.Vector3()

viewdir.subVectors (pos, target).normalize()

// zooms out by 100 along the view direction
viewdir.multiplyScalar (100)

pos.add(viewdir)

nav.setPosition(pos)


问:
How to get details of log form dashboards of kibana
Hi I am new to Kibana (ELK stack).I have created an error dashboard in Kibana but If I need more information about errors how can I get that.Like If I want to know because of what error has been created.How can I get it.

Any initiatives will be appreciated.

答:
For any information that you want to display in Kibana you need to have a source from where that particular information is available. In this case if we assume that the logs being parsed by Logstash has the information on the errors, then you can parse/filter the logs via the pipeline of Logstash to extract the information and store it in a field.

Now the document which are saved in the ES contain the information, this can be used to perform various aggregations or apply different mathematical functions and then eventually visualize it.


问:
PostgreSQL deadlock detected
Assume I've table A with 20 million entries, and another smaller table B with <1 million entries.

I'm trying to add a FK from B pointing to A.

```<code>Process 1240: ALTER TABLE "product" ADD CONSTRAINT
"product_top_id_56635_fk_tableb_id" FOREIGN KEY ("top_id")
REFERENCES "tableb" ("id") DEFERRABLE INITIALLY DEFERRED
</code>```

Does this alteration change anything on tableb? If not why is it causing a deadlock?

答:
Creating the foreign key won't modify A, but it will lock rows in A. This is to guarantee that those values cannot be modified or deleted while the constraint is created.

So there can be deadlocks with other transactions that lock rows in both tables.

Avoid modifications to A, either with an explicit lock or by waiting for a maintenance window.

Title: PostgreSQL deadlock detected

Body:
Assume I've table A with 20 million entries, and another smaller table B with <1 million entries.

I'm trying to add a FK from B pointing to A.

Process 1240: ALTER TABLE "product" ADD CONSTRAINT
"product_top_id_56635_fk_tableb_id" FOREIGN KEY ("top_id")
REFERENCES "tableb" ("id") DEFERRABLE INITIALLY DEFERRED

Does this alteration change anything on tableb? If not why is it causing a deadlock?


问:
Javascript : RemoveEventListener with Anonym Function
How to remove and event listener with an Anonym function , with removeEventListener();

```<code>document.getElementById("object").onclick = function(e){
    if(e && e.stopPropagation) {
        e.stopPropagation();
    } else {
          e = window.event;
          e.cancelBubble = true;
    }
}
</code>```

So I have this piece of code and the function what's called must be anonym I'dont know why but If it's not then doesn't works correctly, maybe beacuse of the event :|

But If it's anonym how can I remove it?

答:
Just give it a null value, which is the starting value when onclick is not initialized:
 document.getElementById("object").onclick = null

Body:
How to remove and event listener with an Anonym function , with removeEventListener();

document.getElementById("object").onclick = function(e){
    if(e && e.stopPropagation) {
        e.stopPropagation();
    } else {
          e = window.event;
          e.cancelBubble = true;
    }
}

So I have this piece of code and the function what's called must be anonym I'dont know why but If it's not then doesn't works correctly, maybe beacuse of the event :|

But If it's anonym how can I remove it?


问:
jQuery Scrolling to Next Section Not Working Properly
I am trying to develop a site where if user press n or N key on the keyboard, the page will auto scroll to the next section. Same applies to the previous section. But I am facing a problem, to scroll next section, sometimes I have to press n twice. On the contrary, it's skipping two sections instead of one while I am pressing p key to go back the previous section. How can I solve this?
I am including my code here:

```<code>    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
         pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

    <script type="text/javascript">
        function ScrollTo(address) {
            $('html, body').animate({
                scrollTop : ($('#' + address).offset().top)
            }, 700);
        }

    </script>

</head>

<body>

<section id="section1">
    <h1>section1</h1>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</section>

<section id="section2">
    <h1>section2</h1>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</section>

<section id="section3">
    <h1>section3</h1>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</section>

<section id="section4">
    <h1>section4</h1>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</section>

<section id="section5">
    <h1>section5</h1>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</section>

<section id="section6">
    <h1>section6</h1>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</section>

<section id="section7">
    <h1>section7</h1>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</section>

<section id="section8">
    <h1>section8</h1>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</section>

<section id="section9">
    <h1>section9</h1>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</section>

<section id="section10">
    <h1>section10</h1>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</section>

<script type="text/javascript">

    var sections = [];
    $(document).find("section").each(function() {
        sections.push(this.id);
    });

    var sectionIndex = 0;

    $(document).keyup(
        function(evt) {
            var elid = $(document.activeElement).is("input, textarea");
            if (elid) {
                return;
            }

            if ((evt.keyCode == 80 | evt.keyCode == 112)
                & sectionIndex > 0) {
                sectionIndex=sectionIndex-1;
                ScrollTo(sections[sectionIndex]);
            } else if ((evt.keyCode == 78 | evt.keyCode == 110)
                & sectionIndex < sections.length - 1) {
                sectionIndex=sectionIndex+1;
                ScrollTo(sections[sectionIndex]);
            }
        });

    $(document).scroll(
        function() {
            $('section').each(
                function() {
                    if ($(this).position().top <= $(document).scrollTop() && ($(this).position().top + $(this).outerHeight()) > $(document).scrollTop()) {
                        sectionIndex = sections.indexOf(($(this).attr('id')));
                    }
                });
        });
</script>

</body>
</html>
</code>```

答:
Hint: Change your code a little bit...

```<code>$('section').each(
  function () {
    this.style.background = '';
    if ($(this).position().top <= $(document).scrollTop() && ($(this).position().top + $(this).outerHeight()) > $(document).scrollTop()) {
      this.style.background = 'lightseagreen';
      sectionIndex = sections.indexOf(($(this).attr('id')));
    }
  });
</code>```

now during scrolling you'll see which section is "current". This demonstrates the problem: after pressing "N" the previous section is still "current".

You can easily fix it:

currently the highlighted section is the one that intersects the upper bound of the screen,

instead, you can imagine a line a bit below top of the screen, like 50px  lower, and consider that as the "focus point" that determines which section is current.

The code could look like this:

```<code>    $('section').each(
      function () {
        const focus = $(document).scrollTop() + 50;
        this.style.background = '';
        if ($(this).position().top <= focus && ($(this).position().top + $(this).outerHeight()) > focus) {
          this.style.background = 'lightseagreen';
          sectionIndex = sections.indexOf(($(this).attr('id')));
        }
      });
</code>```

Only change here is comparing against $(document).scrollTop() + 50 instead of $(document).scrollTop(). Notice that now the section becomes highlighted quicker, before it touches the top edge of the screen.

Body:
I am trying to develop a site where if user press n or N key on the keyboard, the page will auto scroll to the next section. Same applies to the previous section. But I am facing a problem, to scroll next section, sometimes I have to press n twice. On the contrary, it's skipping two sections instead of one while I am pressing p key to go back the previous section. How can I solve this?
I am including my code here:

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
         pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

section1

section2

section3

section4

section5

section6

section7

section8

section9

section10

Body:
Hint: Change your code a little bit...

$('section').each(
  function () {
    this.style.background = '';
    if ($(this).position().top <= $(document).scrollTop() && ($(this).position().top + $(this).outerHeight()) > $(document).scrollTop()) {
      this.style.background = 'lightseagreen';
      sectionIndex = sections.indexOf(($(this).attr('id')));
    }
  });

now during scrolling you'll see which section is "current". This demonstrates the problem: after pressing "N" the previous section is still "current".

You can easily fix it:

currently the highlighted section is the one that intersects the upper bound of the screen,

instead, you can imagine a line a bit below top of the screen, like 50px  lower, and consider that as the "focus point" that determines which section is current.

The code could look like this:

    $('section').each(
      function () {
        const focus = $(document).scrollTop() + 50;
        this.style.background = '';
        if ($(this).position().top <= focus && ($(this).position().top + $(this).outerHeight()) > focus) {
          this.style.background = 'lightseagreen';
          sectionIndex = sections.indexOf(($(this).attr('id')));
        }
      });

Only change here is comparing against $(document).scrollTop() + 50 instead of $(document).scrollTop(). Notice that now the section becomes highlighted quicker, before it touches the top edge of the screen.


问:
MaterialCalendarView: How to get CalendarDay value on decorate method?
I am using MaterialCalendarView (https://github.com/prolificinteractive/material-calendarview) in my app., My objective to create price view (as attached in picture). I have a map which contains selected date & their price.

Please help me to understand how can I get CalendarDay value at decorate method so that I can get price value from map.

```<code> public class DaysDecorator implements DayViewDecorator {
 private final Context context;
 Map<CalendarDay, String> priceMap;

public DaysDecorator(Context context, Map<CalendarDay, String> priceMap){
    this.context = context;
    this.priceMap = priceMap;
}
@Override
public boolean shouldDecorate(CalendarDay day) {
    return priceMap.containsKey(day);
}

 @Override
 public void decorate(DayViewFacade view) {
</code>```

//How to get CalendarDay here

```<code>    int price = priceMap.get();

    view.addSpan(new PriceSpan(35, Color.LTGRAY, 120000));
  }
}
</code>```

答:
I am afraid that you have misunderstood one of the principles behind DayViewDecorator.

If I understand correctly, what you want to do is to set a specific value for the PriceSpan (i.e. the small text/value shown below the date) for each day. This cannot be achieved with a single DayViewDecorator. A DayViewDecorator applies one specific style/drawing/whatever (defined through the decorate()-method) for all days that are in the set of applicable dates (In your case priceMap).

In other words, what happens in decorate(), happens for all those days which resulted in true from a previous call to shouldDecorate().

I'm afraid that you are going to have to use specific decorators for each unique value in your Map.

Body:
I am using MaterialCalendarView (https://github.com/prolificinteractive/material-calendarview) in my app., My objective to create price view (as attached in picture). I have a map which contains selected date & their price.

Please help me to understand how can I get CalendarDay value at decorate method so that I can get price value from map.

 public class DaysDecorator implements DayViewDecorator {
 private final Context context;
 Map<CalendarDay, String> priceMap;

public DaysDecorator(Context context, Map<CalendarDay, String> priceMap){
    this.context = context;
    this.priceMap = priceMap;
}
@Override
public boolean shouldDecorate(CalendarDay day) {
    return priceMap.containsKey(day);
}

 @Override
 public void decorate(DayViewFacade view) {

//How to get CalendarDay here

    int price = priceMap.get();

    view.addSpan(new PriceSpan(35, Color.LTGRAY, 120000));
  }
}


问:
Skip Condtion if value is null
This should be really simple; however, I cannot wrap my head around it using the CASE statement.

```<code>DECLARE @Test INT = NULL
SELECT *
FROM StoreImages
WHERE Quality = 1 AND Ready = @Test
</code>```

I would like to accomplish something similar to this:

```<code>DECLARE @Test INT = NULL
SELECT *
FROM StoreImages
CASE @Test IS NOT NULL
  WHERE Quality = 1 AND Ready = @Test
ELSE
  WHERE Quality = 1
</code>```

UPDATE

I created a schema sample for quickly testing provided answers

```<code>--create a temporary table
CREATE TABLE #ImagesTable(
Quality BIT,
Ready BIT)

-- insert into the temporary table
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);
</code>```

Declaring @Test as null should return all

Declaring @Test as 1 or 0 should return half records

答:
Generally, it's bad practice to use ISNULL's or CASE expression around nullable parameters. Depending on the complexity of the query, it can play havoc for the optimiser, resulting in poor query plan choices.

Rather than using a CASE, use an IF to break out your query:

```<code>DECLARE @Test int = NULL;

IF @Test IS NULL BEGIN
    SELECT *
    FROM #ImagesTable IT
    WHERE IT.Quality = 1;
END ELSE BEGIN
    SELECT *
    FROM #ImagesTable IT
    WHERE IT.Quality = 1
      AND IT.Ready = @Test;
END
</code>```

The first answer Sami is going to cause you problems with that OR. Regardless of the value of your @Test, a row would be returned if it has a Quality of 1.

Edit:
If you have to use something similar to a CASE expression, then the correct syntax would be:

```<code>SELECT *
FROM #ImagesTable IT
WHERE IT.Quality = 1
  AND (IT.Ready = @Test OR @Test IS NULL);
</code>```

Title: Skip Condtion if value is null

Body:
This should be really simple; however, I cannot wrap my head around it using the CASE statement.

DECLARE @Test INT = NULL
SELECT *
FROM StoreImages
WHERE Quality = 1 AND Ready = @Test

I would like to accomplish something similar to this:

DECLARE @Test INT = NULL
SELECT *
FROM StoreImages
CASE @Test IS NOT NULL
  WHERE Quality = 1 AND Ready = @Test
ELSE
  WHERE Quality = 1

UPDATE

I created a schema sample for quickly testing provided answers

--create a temporary table
CREATE TABLE #ImagesTable(
Quality BIT,
Ready BIT)

-- insert into the temporary table
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);

Declaring @Test as null should return all

Declaring @Test as 1 or 0 should return half records

Body:
Generally, it's bad practice to use ISNULL's or CASE expression around nullable parameters. Depending on the complexity of the query, it can play havoc for the optimiser, resulting in poor query plan choices.

Rather than using a CASE, use an IF to break out your query:

DECLARE @Test int = NULL;

IF @Test IS NULL BEGIN
    SELECT *
    FROM #ImagesTable IT
    WHERE IT.Quality = 1;
END ELSE BEGIN
    SELECT *
    FROM #ImagesTable IT
    WHERE IT.Quality = 1
      AND IT.Ready = @Test;
END

The first answer Sami is going to cause you problems with that OR. Regardless of the value of your @Test, a row would be returned if it has a Quality of 1.

Edit:
If you have to use something similar to a CASE expression, then the correct syntax would be:

SELECT *
FROM #ImagesTable IT
WHERE IT.Quality = 1
  AND (IT.Ready = @Test OR @Test IS NULL);


问:
Private properties in JavaScript ES6 classes
Is it possible to create private properties in ES6 classes?

Here's an example.
How can I prevent access to instance.property?

```<code>class Something {
  constructor(){
    this.property = "test";
  }
}

var instance = new Something();
console.log(instance.property); //=> "test"
</code>```

答:
Another way similar to the last two posted </p>

```<code>class Example {
  constructor(foo) {

    // privates
    const self = this;
    this.foo = foo;

    // public interface
    return self.public;
  }

  public = {
    // empty data
    nodata: { data: [] },
    // noop
    noop: () => {},
  }

  // everything else private
  bar = 10
}

const test = new Example('FOO');
console.log(test.foo); // undefined
console.log(test.noop); // { data: [] }
console.log(test.bar); // undefined
</code>```

Body:
Is it possible to create private properties in ES6 classes?

Here's an example.
How can I prevent access to instance.property?

class Something {
  constructor(){
    this.property = "test";
  }
}

var instance = new Something();
console.log(instance.property); //=> "test"

Body:
Another way similar to the last two posted

class Example {
  constructor(foo) {

    // privates
    const self = this;
    this.foo = foo;

    // public interface
    return self.public;
  }

  public = {
    // empty data
    nodata: { data: [] },
    // noop
    noop: () => {},
  }

  // everything else private
  bar = 10
}

const test = new Example('FOO');
console.log(test.foo); // undefined
console.log(test.noop); // { data: [] }
console.log(test.bar); // undefined


问:
How to print word that you want inside a textfile?
I have this program which it prints the text file with numbers:

```<code>with open('addon/entertainment.txt')as f:
    lines = []
    for l_i, line in enumerate(f.read().split('\n'), 1):
        formatted_line = '%s. %s' % (l_i, line)
        print(formatted_line)
        lines.append(formatted_line)
</code>```

Output:

```<code>1. Synchronised Swimming Dance
2. Clown Performance
3. Magic Performance
4. House Dance Performance
5. Live Band Performance
</code>```

What should I do to the program so that I can get entertainment such as :

```<code>1. Magic Performance
2. Live Band Performance
</code>```

thanks

答:
This should work.. Don't have the file to test but it basically prints out all the options, asks them for what line number then prints that line number
(Or if i did it correctly it should)</p>

```<code>with open('addon/entertainment.txt')as f:
lines = []
for l_i, line in enumerate(f.read().split('\n'), 1):
    print(str(num) + " : " + str(line))
uinput = int(input("What would you like to watch? (number)"))
for l_i, line in enumerate(f.read().split('\n'), 1):
    if l_i == uinput:
        formatted_line = '%s. %s' % (l_i, line)
        print(formatted_line)
    print(str(num) + " : " + str(line))
</code>```

Body:
I have this program which it prints the text file with numbers:

with open('addon/entertainment.txt')as f:
    lines = []
    for l_i, line in enumerate(f.read().split('\n'), 1):
        formatted_line = '%s. %s' % (l_i, line)
        print(formatted_line)
        lines.append(formatted_line)

Output:

1. Synchronised Swimming Dance
2. Clown Performance
3. Magic Performance
4. House Dance Performance
5. Live Band Performance

What should I do to the program so that I can get entertainment such as :

1. Magic Performance
2. Live Band Performance

thanks

Body:
This should work.. Don't have the file to test but it basically prints out all the options, asks them for what line number then prints that line number
(Or if i did it correctly it should)

with open('addon/entertainment.txt')as f:
lines = []
for l_i, line in enumerate(f.read().split('\n'), 1):
    print(str(num) + " : " + str(line))
uinput = int(input("What would you like to watch? (number)"))
for l_i, line in enumerate(f.read().split('\n'), 1):
    if l_i == uinput:
        formatted_line = '%s. %s' % (l_i, line)
        print(formatted_line)
    print(str(num) + " : " + str(line))


问:
TEI Documents to HTML with PHP
I've problems with some old documents encoded in TEI and I need to read these documents and print their content into a webpage (then HTML format).
Does there exists some classes or some tools userful in php to convert these files (I'm new with the TEI format) in a readable content?</p>

答: You said that you are looking for some classes in PHP to work with TEI and to transform TEI into HTML. You require an XSLT processor to do that. There is PHP: XSL which supports XSLT 1.0, which is ok for a start. It does not support TEI natively by itself, but you would have to write your own XSL to transform TEI elements into HTML elements. This is probably not the answer you were hoping for. Due to the complexity of TEI and all its modules it is difficult to invent general tools to create HTML from any TEI document, and you did not specify what the subject of your documents is. However, you can trigger transformation with PHP, and very probably you can adopt some XSL files from the resources available on http://www.tei-c.org. I hope this helps.</p>

Title: TEI Documents to HTML with PHP


问:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
My Swift program is crashing with EXC_BAD_INSTRUCTION and one of the following similar errors. What does this error mean, and how do I fix it?

Fatal error: Unexpectedly found nil while unwrapping an Optional value

or

Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

This post is intended to collect answers to "unexpectedly found nil" issues, so that they are not scattered and hard to find. Feel free to add your own answer or edit the existing wiki answer.

答:
Since the above answers clearly explains how to play safely with Optionals.
I will try explain what Optionals are really in swift.

Another way to declare an optional variable is

var i : Optional<Int>

And Optional type is nothing but an enumeration with two cases, i.e

```<code> enum Optional<Wrapped> : ExpressibleByNilLiteral {
    case none
    case some(Wrapped)
    .
    .
    .
}
</code>```

So to assign a nil to our variable 'i'. We can do
var i = Optional<Int>.none
or to assign a value, we will pass some value
var i = Optional<Int>.some(28)

According to swift, 'nil' is the absence of value.
And to create an instance initialized with nil We have to conform to a protocol called ExpressibleByNilLiteral and great if you guessed it, only Optionals conform to ExpressibleByNilLiteral and conforming to other types is discouraged.

ExpressibleByNilLiteral has a single method called init(nilLiteral:) which initializes an instace with nil. You usually wont call this method and according to swift documentation it is discouraged to call this initializer directly as the compiler calls it whenever you initialize an Optional type with nil literal.

Even myself has to wrap (no pun intended) my head around Optionals :D
Happy Swfting All.

Body:
Since the above answers clearly explains how to play safely with Optionals.
I will try explain what Optionals are really in swift.

Another way to declare an optional variable is

var i : Optional<Int>

And Optional type is nothing but an enumeration with two cases, i.e

 enum Optional<Wrapped> : ExpressibleByNilLiteral {
    case none
    case some(Wrapped)
    .
    .
    .
}

So to assign a nil to our variable 'i'. We can do
var i = Optional<Int>.none
or to assign a value, we will pass some value
var i = Optional<Int>.some(28)

According to swift, 'nil' is the absence of value.
And to create an instance initialized with nil We have to conform to a protocol called ExpressibleByNilLiteral and great if you guessed it, only Optionals conform to ExpressibleByNilLiteral and conforming to other types is discouraged.

ExpressibleByNilLiteral has a single method called init(nilLiteral:) which initializes an instace with nil. You usually wont call this method and according to swift documentation it is discouraged to call this initializer directly as the compiler calls it whenever you initialize an Optional type with nil literal.

Even myself has to wrap (no pun intended) my head around Optionals :D
Happy Swfting All.


问:
UIAlertView show when app loads, open
How show a alertview just when the app open, load...

Like everytime that the user open the app, he see the alert ....

答: Show the alertview in the application delegate class, in applicationDidFinishLaunching: and in applicationWillEnterForeground:

Title: UIAlertView show when app loads, open


问:
Powershell ArrayList turns a single array item back into a string
I have a powershell script that generates an ArrayList based on the names of the folders in a given directory. So if the directory looked like the following:

C:\Directory\One

C:\Directory\Two

C:\Directory\Three

$list is an array that contains [One, Two, Three]. The line is as follows:

```<code>[System.Collections.ArrayList]$list = (Get-ChildItem C:\Directory -dir).Name
</code>```

I can then iterate through the array of strings and do various things with them. However this stops working when there is only one folder in the directory. It seems it is no longer an ArrayList and becomes just a string. I get the following error:

```<code>Cannot convert the "Directory" value of type "System.String" to type "System.Collections.ArrayList"
</code>```

What can be done here? Should I be using a different kind of array type?

答:
If you want to use an ArrayList, the constructor is just expecting an Array or another ArrayList. You can build off what @DanielMann said and do something like this:

```<code>New-Item -Path C:\TestDirectory\SubDirectory -Force | Out-Null # Creates one folder in C:\TestDirectory
[System.Collections.ArrayList] $ArrayList = @((Get-ChildItem C:\TestDirectory -Directory).Name)
Write-Host "Total directories: $($ArrayList.Count)"
Remove-Item -Path C:\TestDirectory -Recurse
</code>```

As you can see, I am just wrapping the output of (Get-ChildItem).Name in an array @().

Body:
I have a powershell script that generates an ArrayList based on the names of the folders in a given directory. So if the directory looked like the following:

C:\Directory\One

C:\Directory\Two

C:\Directory\Three

$list is an array that contains [One, Two, Three]. The line is as follows:

[System.Collections.ArrayList]$list = (Get-ChildItem C:\Directory -dir).Name

I can then iterate through the array of strings and do various things with them. However this stops working when there is only one folder in the directory. It seems it is no longer an ArrayList and becomes just a string. I get the following error:

Cannot convert the "Directory" value of type "System.String" to type "System.Collections.ArrayList"

What can be done here? Should I be using a different kind of array type?

Body:
If you want to use an ArrayList, the constructor is just expecting an Array or another ArrayList. You can build off what @DanielMann said and do something like this:

New-Item -Path C:\TestDirectory\SubDirectory -Force | Out-Null # Creates one folder in C:\TestDirectory
[System.Collections.ArrayList] $ArrayList = @((Get-ChildItem C:\TestDirectory -Directory).Name)
Write-Host "Total directories: $($ArrayList.Count)"
Remove-Item -Path C:\TestDirectory -Recurse

As you can see, I am just wrapping the output of (Get-ChildItem).Name in an array @().


问:
Bcrypt stretches (with Devise) and Heroku dynos
I am currently reviewing security of my admin model generated with Devise. It raises a lot of questions on how a web dyno at Heroku processes the password encription.

first question :

My default Devise setup for bcrypt cost is config.stretches = Rails.env.test? ? 1 : 11 Does it mean there are eleven stretches for the test environment ? It seems the default stretches is 11 and I can confirm my hash under development environment is 11 too. So why specifiying 11 for test ?

I plan raising to 12 with config.stretches = 12

second question :

If I raise the strectches, the encryption time will increase. Will it freeze my app and prevent other visitors to make http requests to the app ? How many concurrent http requests can be made to a web dyno and how many concurrent password encryption can also be made to a web dyno (if this is different).

My knowledge of dynos is not deep, but I know a worker dyno can thread multiple Sidekiq workers depending on the processor cores .. Though the dyno don't specify the number of cores, and I don't know if this apply to web dynos too.

Basically I know that raising strectches will increase encrypting time, yet will it affect the whole app efficiency ?

答:
config.stretches = Rails.env.test? ? 1 : 11 will use just 1 for testing, otherwise 11. This is to speed up testing since there isn't any point in making passwords secure in a test environment.

If you plan to use 12, the use config.stretches = Rails.env.test? ? 1 : 12.

More stretches take more computation. Typically this won't be a performance concern, don't optimize or focus on this unless you spot a real problem.


问:
How to stop mongo DB in one command
I need to be able to start/stop MongoDB on the cli. It is quite simple to start:

./mongod

But to stop mongo DB, I need to run open mongo shell first and then type two commands:

$ ./mongo

use admin

db.shutdownServer()

So I don't know how to stop mongo DB in one line. Any help?

答:
create a file called mongostop.bat

save the following code in it

```<code> mongo admin --eval "db.shutdownServer()"
</code>```

run the file mongostop.bat and you successfully have mongo stopped

Title: How to stop mongo DB in one command

Body:
create a file called mongostop.bat

save the following code in it

 mongo admin --eval "db.shutdownServer()"

run the file mongostop.bat and you successfully have mongo stopped


问:
Play a beep sound on button click
OK I've read several answers here but they didn't help me at all (in fact, none of them is being accepted as answer)

Question is how to "Play a beep sound" on "button click"

I am trying to make a website that works on touchscreen device so I want every button click events will play a beep sound, that should be nicer for users who using the website. Beep sound file is here: http://www.soundjay.com/button/beep-07.wav . I only need this work on Google Chrome (supports HTML5)

I understand this need to work on client-side so I tried this:

Javascript:

```<code><script>
    function PlaySound(soundObj) {
        var sound = document.getElementById(soundObj);
        sound.Play();
    }
</script>
</code>```

HTML

```<code><embed src="/beep.wav" autostart="false" type="audio/mpeg" loop="false" width="0" height="0" id="beep" enablejavascript="true" />
<asp:LinkButton ID="lbtnExit" runat="server" OnClick="lbtnExit_Click" OnClientClick="PlaySound('beep')" CssClass="btn btn-lg btn-danger" Text="Exit <i class='fa fa-sign-out' style='font-size: 40px'></i>"></asp:LinkButton>
</code>```

But it doesn't work, nothing happens when I click the button.

答:
Been driving me crazy, but with JQuery I found a solution... not really the best way to do it, but it worked properly for me...

```<code>function ding() {
      $("body").append('<embed src="/ding.mp3" autostart=false autoplay=false type="audio/mpeg" loop="false" width="0" height="0" id="beep" enablejavascript="true" />');
      setTimeout(function(){ $("#beep").remove(); },2000);
}
</code>```

not sure how much of the embed tag is really required, but once it started working, I stopped writing (embed copied from another solution).

Hope this helps someone else (or helps me the next time I forget)

Title: Play a beep sound on button click

Body:
OK I've read several answers here but they didn't help me at all (in fact, none of them is being accepted as answer)

Question is how to "Play a beep sound" on "button click"

I am trying to make a website that works on touchscreen device so I want every button click events will play a beep sound, that should be nicer for users who using the website. Beep sound file is here: http://www.soundjay.com/button/beep-07.wav . I only need this work on Google Chrome (supports HTML5)

I understand this need to work on client-side so I tried this:

Javascript:

HTML

<embed src="/beep.wav" autostart="false" type="audio/mpeg" loop="false" width="0" height="0" id="beep" enablejavascript="true" />
<asp:LinkButton ID="lbtnExit" runat="server" OnClick="lbtnExit_Click" OnClientClick="PlaySound('beep')" CssClass="btn btn-lg btn-danger" Text="Exit "></asp:LinkButton>

But it doesn't work, nothing happens when I click the button.

Body:
Been driving me crazy, but with JQuery I found a solution... not really the best way to do it, but it worked properly for me...

function ding() {
      $("body").append('<embed src="/ding.mp3" autostart=false autoplay=false type="audio/mpeg" loop="false" width="0" height="0" id="beep" enablejavascript="true" />');
      setTimeout(function(){ $("#beep").remove(); },2000);
}

not sure how much of the embed tag is really required, but once it started working, I stopped writing (embed copied from another solution).

Hope this helps someone else (or helps me the next time I forget)


问:
SAS: Variable list contains names with '-' symbol, resulting in error during keep= statement
I have SAS datasets with multiple variables like H9999-999-999-999. However, I need to drop the unnecessary columns and am using a variable list(ParamList) to do that:

```<code>proc sql;
select _NAME_ into :ParamList separated by ' '
from uniquePlanList;
quit;
%put ParamList = &ParamList.;

proc sql;
create table test as
select * from out.seq_summ(keep=BPT_Cat &ParamList.);
run;
</code>```

Because my variables contain '-' symbols I receive the following errors:

ERROR 214-322: Variable name - is not valid.

ERROR 214-322: Variable name 000 is not valid.

ERROR 80-322: Expecting a variable name.

ERROR: Invalid value for the KEEP option.

ERROR: Invalid option name -000.

ERROR: Some options for file OUT.SEQ_SUMM were not processed because of errors or warnings noted above.

I know if I were to list out the variables like this:

(keep=BPT_Cat 'H9999-999-999-999'n 'H9999-999-999-998'n)

Then the code would work. But I have some datasets with hundreds of variables. Is there a better way to drop the unnecessary columns than using a variable list? Or is there some clever way to read in the variable list as a string?
I tried using this:

(keep=BPT_Cat %str(&ParamList.)) but that gave me the same errors as above.

答:
how about:

```<code>proc sql;
select quote(_NAME_)||"n" into :ParamList separated by ' '
from uniquePlanList;
quit;
%put ParamList = &ParamList.;

proc sql;
create table test as
select * from out.seq_summ(keep=BPT_Cat &ParamList.);
run;
</code>```

Don't have SAS with me at the moment can't really test it.

Body:
I have SAS datasets with multiple variables like H9999-999-999-999. However, I need to drop the unnecessary columns and am using a variable list(ParamList) to do that:

proc sql;
select _NAME_ into :ParamList separated by ' '
from uniquePlanList;
quit;
%put ParamList = &ParamList.;

proc sql;
create table test as
select * from out.seq_summ(keep=BPT_Cat &ParamList.);
run;

Because my variables contain '-' symbols I receive the following errors:

ERROR 214-322: Variable name - is not valid.

ERROR 214-322: Variable name 000 is not valid.

ERROR 80-322: Expecting a variable name.

ERROR: Invalid value for the KEEP option.

ERROR: Invalid option name -000.

ERROR: Some options for file OUT.SEQ_SUMM were not processed because of errors or warnings noted above.

I know if I were to list out the variables like this:

(keep=BPT_Cat 'H9999-999-999-999'n 'H9999-999-999-998'n)

Then the code would work. But I have some datasets with hundreds of variables. Is there a better way to drop the unnecessary columns than using a variable list? Or is there some clever way to read in the variable list as a string?
I tried using this:

(keep=BPT_Cat %str(&ParamList.)) but that gave me the same errors as above.

Body:
how about:

proc sql;
select quote(_NAME_)||"n" into :ParamList separated by ' '
from uniquePlanList;
quit;
%put ParamList = &ParamList.;

proc sql;
create table test as
select * from out.seq_summ(keep=BPT_Cat &ParamList.);
run;

Don't have SAS with me at the moment can't really test it.


问:
What C++17 standard say about calling delete on nullptr?
C++03 Standard say's:

5.3.5 Delete

[...] In either alternative, if the value of the operand of delete is the null pointer the operation has no effect.[...]

```<code>char *p = nullptr;
delete p; //no effect
</code>```

It means, it is valid to delete null pointer in c++.

What C++17 standard say about calling delete on nullptr pointer?

答:
Yes it is valid, and it results in a noop. reference

If expression evaluates to a null pointer value, no destructors are called, and the deallocation function is not called.

Body:
C++03 Standard say's:

5.3.5 Delete

[...] In either alternative, if the value of the operand of delete is the null pointer the operation has no effect.[...]

char *p = nullptr;
delete p; //no effect

It means, it is valid to delete null pointer in c++.

What C++17 standard say about calling delete on nullptr pointer?


问:
Socket.io - Prevent server crash if "client" emit wrong data
Currently im working on a project using node.js and socket.io.

If wonder if there is any way to automatically validate data the client emitted to the server. I don't want to validate the data by using if (!...) return; for each variable I want to use in the ongoing function.

for example I have the following code on server.js

```<code>socket.on('haveData', function(data) {
    db.query('SELECT * FROM user WHERE userid = ? LIMIT 1', [data.userid], function(errData, results, fields) {
        if (!errData && results.length) {
            ...
        }
    });
});
</code>```

but now, if I type socket.emit('haveData'); in the console of my browser, the socket.io server is crashing - sure, there is no data emitted

```<code>TypeError: Cannot read property 'userid' of undefined
</code>```

答:
Server-side code MUST validate all data sent from the client.  You simply cannot ever fully trust a client because clients can be modified/hacked or even a rogue client could connect to your server.

In this particular case, all you should need to fix that particular issue is this if (data && data.userid) to check what you are being sent:

```<code>socket.on('haveData', function(data) {
    if (data && data.userid) {
        db.query('SELECT * FROM user WHERE userid = ? LIMIT 1', [data.userid], function(errData, results, fields) {
            if (!errData && results.length) {
                ...
            }

        });
     } else {
         // send some error back or just ignore the faulty request
     }
});
</code>```

If you really wanted to be cautious, you could even use:

```<code>if (data && data.userid && typeof data.userid === "string")
</code>```

This makes sure that data exists, that data.userid exists and is not an empty string and that data.userid is a string.

Body:
Currently im working on a project using node.js and socket.io.

If wonder if there is any way to automatically validate data the client emitted to the server. I don't want to validate the data by using if (!...) return; for each variable I want to use in the ongoing function.

for example I have the following code on server.js

socket.on('haveData', function(data) {
    db.query('SELECT * FROM user WHERE userid = ? LIMIT 1', [data.userid], function(errData, results, fields) {
        if (!errData && results.length) {
            ...
        }
    });
});

but now, if I type socket.emit('haveData'); in the console of my browser, the socket.io server is crashing - sure, there is no data emitted

TypeError: Cannot read property 'userid' of undefined

Body:
Server-side code MUST validate all data sent from the client.  You simply cannot ever fully trust a client because clients can be modified/hacked or even a rogue client could connect to your server.

In this particular case, all you should need to fix that particular issue is this if (data && data.userid) to check what you are being sent:

socket.on('haveData', function(data) {
    if (data && data.userid) {
        db.query('SELECT * FROM user WHERE userid = ? LIMIT 1', [data.userid], function(errData, results, fields) {
            if (!errData && results.length) {
                ...
            }

        });
     } else {
         // send some error back or just ignore the faulty request
     }
});

If you really wanted to be cautious, you could even use:

if (data && data.userid && typeof data.userid === "string")

This makes sure that data exists, that data.userid exists and is not an empty string and that data.userid is a string.


问:
Access members of unkown template type of derived template class through pointer to base class C++
I need to have a map holding different value types. I achieved that using a derived template class Derived of type T derived from B  and declaring my map using a pointer to the base class Base like so:

```<code>class Base {
    public:
    ~Base(){}
};

template <class T>
class Derived: public Base {
     public:
     Derived(T value) {
          this->value = value;
     }
     T value;
 };

 std::map<std::string, std::shared_ptr<Base>> my_map;

 using KeyValuePair = std::pair<std::string, std::shared_ptr<Base>>;

 my_map.insert(KeyValuePair("foo1",std::make_shared<Derived<int>>(10)));
 my_map.insert(KeyValuePair("foo2",std::make_shared<Derived<double>>(20.0)));
 my_map.insert(KeyValuePair("foo3",std::make_shared<Derived<std::string>>("bla")));
</code>```

I now for example want to print the value of a map entry

```<code> for (auto const& x : my_map)
{
    std::cout << *x.get() << std::endl;
}
</code>```

However, I now have the problem that I cannot access the the members in the Derived class by casting x to Derived, because I don't know the type of the template parameter. So the following is not possible:

```<code>std::shared_ptr<Derived<?>> derived = std::dynamic_cast<Derived<?>>(x);
</code>```

I thought about having a virtual function in the Base class which returns the member, but I don't know the return type, so not an option.

I also don't want to specify several virtual functions for several return types, as the whole point of the code is to avoid copying code and having a "generic map"

However, I don't see another solution besides using some fancy boost magic by returning a streamable boost::any like the following, as this removes any information about the type.

```<code> using streamable_any = boost::type_erasure::any<boost::mpl::vector<
 boost::type_erasure::copy_constructible<>,
 boost::type_erasure::destructible<>,
 boost::type_erasure::ostreamable<>>>;
</code>```

What are the possibilities I have to achieve what I want? I suspect that I need to consider a design change.

答:
First of all you have UB in your example, as you hold instances of derived classes through pointer of base, destructor must be virtual.

To fix your current problem with printing values you can add a virtual method:

```<code>class Base {
    public:
    virtual void print( std::ostream &os ) const = 0;
    virtual ~Base(){}
};
</code>```

but that would only fix this particular problem, but accessing values would be still issue. One of solution would be to add a virtual getter that converts all values to std::string. Or always use cascade of dynamic_cast<> (note dynamic cast would require at least one virtual method in Base). But better to use boost::variant which provides functionality to implement visitor pattern and check if this instance holds value of particular type. You would not need inheritance at all in this case.

Body:
I need to have a map holding different value types. I achieved that using a derived template class Derived of type T derived from B  and declaring my map using a pointer to the base class Base like so:

class Base {
    public:
    ~Base(){}
};

template <class T>
class Derived: public Base {
     public:
     Derived(T value) {
          this->value = value;
     }
     T value;
 };

 std::map<std::string, std::shared_ptr<Base>> my_map;

 using KeyValuePair = std::pair<std::string, std::shared_ptr<Base>>;

 my_map.insert(KeyValuePair("foo1",std::make_shared<Derived<int>>(10)));
 my_map.insert(KeyValuePair("foo2",std::make_shared<Derived<double>>(20.0)));
 my_map.insert(KeyValuePair("foo3",std::make_shared<Derived<std::string>>("bla")));

I now for example want to print the value of a map entry

 for (auto const& x : my_map)
{
    std::cout << *x.get() << std::endl;
}

However, I now have the problem that I cannot access the the members in the Derived class by casting x to Derived, because I don't know the type of the template parameter. So the following is not possible:

std::shared_ptr<Derived<?>> derived = std::dynamic_cast<Derived<?>>(x);

I thought about having a virtual function in the Base class which returns the member, but I don't know the return type, so not an option.

I also don't want to specify several virtual functions for several return types, as the whole point of the code is to avoid copying code and having a "generic map"

However, I don't see another solution besides using some fancy boost magic by returning a streamable boost::any like the following, as this removes any information about the type.

 using streamable_any = boost::type_erasure::any<boost::mpl::vector<
 boost::type_erasure::copy_constructible<>,
 boost::type_erasure::destructible<>,
 boost::type_erasure::ostreamable<>>>;

What are the possibilities I have to achieve what I want? I suspect that I need to consider a design change.

Body:
First of all you have UB in your example, as you hold instances of derived classes through pointer of base, destructor must be virtual.

To fix your current problem with printing values you can add a virtual method:

class Base {
    public:
    virtual void print( std::ostream &os ) const = 0;
    virtual ~Base(){}
};

but that would only fix this particular problem, but accessing values would be still issue. One of solution would be to add a virtual getter that converts all values to std::string. Or always use cascade of dynamic_cast<> (note dynamic cast would require at least one virtual method in Base). But better to use boost::variant which provides functionality to implement visitor pattern and check if this instance holds value of particular type. You would not need inheritance at all in this case.


问:
SPWeb.Groups vs SPWeb.AssociatedGroups
I've seen three types of group properties for an SPWeb object - Groups, SiteGroups, AssociatedGroups.

I understand that SiteGroups will fetch all the groups in the current site collection. But what is the difference between Groups and AssociatedGroups. MSDN definition says that Groups will get all the 'cross-site'(!) groups for that web site. AssociatedGroups are fairly easily to understand just from the very name.

So what does Groups return? Can somebody explain me with an example?

答:
I believe msdn has the answer

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.sitegroups.aspx

Gets a collection that contains all the groups in the site collection.

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.groups.aspx

Gets a collection that contains all the groups for the website. The following code example uses the Groups property to return the collection of groups for a specified site in the current site collection.

Which means, the SPGroup has been used in (ie assigned a permission in) the SPWeb somewhere.

Title: SPWeb.Groups vs SPWeb.AssociatedGroups


问:
How to excape % in string like "%SOme;string" in C# CodedUI
i write a CodedUI test in C# for a wpf application. I need to write a value (string like "%Some;"string?"") to the TextBox. I created  a string var newMaterialName = "\"%Some;\"string?\"\""; and wrote it to the TextBox. As a result this string was added like "ome;"string?"" - so "%S" disappeared. I really must write to the TextBox exact string with % sign in it. (%%, ,\%, and \x25 - do not work) If u ever met this problem, give a hint. Thanx.

答:
Try using it like this as a verbatim string:</p>

```<code> var newMaterialName = @"""%Some;string?""";
</code>```

Body:
Try using it like this as a verbatim string:

 var newMaterialName = @"""%Some;string?""";


问:
How do I read a file into a matrix in bash?
I have a text file like this

```<code>A;green;3
B;blue;2
A;red;4
C;red;2
C;blue;3
B;green;3
</code>```

I have to write a script that if started with parameter "B" gives me the color of the row with the biggest number (from the rows starting with B). In this case it would be the last line, so the output would be "green".

How do I separate the elements by ";"-s and newlines and store them into a matrix so I can work with it? Do I even need to do that, or is there an easier solution?

Thanks in advance!

答:
awk to the rescue!

probably not understood what you want to achieve but

```<code>awk -v key="$c" -F\; 'm[$1]<$3{m[$1]=$3; c[$1]=$2} END{print c[key]}' file
</code>```

will pick the highest coded color from the file for the key

some poor usage pattern

```<code>$ for c in A B C;
  do
    echo $c "->"  $(awk -v key="$c" -F\; 'm[$1]<$3 {m[$1]=$3; c[$1]=$2}
                                          END      {print c[key]}' file);
  done;

A -> red
B -> green
C -> blue
</code>```

you can probably implement the rest of the script in awk and do this process once.

Or, perhaps you want an associative array, can be done as below:

```<code>$ declare -A colors;
  while IFS=\; read k c _ ;
  do
     colors[$k]=$c;
  done < <(sort -t\; -k1,1 -k3nr file | uniq -w1)

$ echo ${colors[A]}
red
</code>```

Body:
I have a text file like this

A;green;3
B;blue;2
A;red;4
C;red;2
C;blue;3
B;green;3

I have to write a script that if started with parameter "B" gives me the color of the row with the biggest number (from the rows starting with B). In this case it would be the last line, so the output would be "green".

How do I separate the elements by ";"-s and newlines and store them into a matrix so I can work with it? Do I even need to do that, or is there an easier solution?

Thanks in advance!

Body:
awk to the rescue!

probably not understood what you want to achieve but

awk -v key="$c" -F\; 'm[$1]<$3{m[$1]=$3; c[$1]=$2} END{print c[key]}' file

will pick the highest coded color from the file for the key

some poor usage pattern

$ for c in A B C;
  do
    echo $c "->"  $(awk -v key="$c" -F\; 'm[$1]<$3 {m[$1]=$3; c[$1]=$2}
                                          END      {print c[key]}' file);
  done;

A -> red
B -> green
C -> blue

you can probably implement the rest of the script in awk and do this process once.

Or, perhaps you want an associative array, can be done as below:

$ declare -A colors;
  while IFS=\; read k c _ ;
  do
     colors[$k]=$c;
  done < <(sort -t\; -k1,1 -k3nr file | uniq -w1)

$ echo ${colors[A]}
red


问:
How can this structure have sizeof == 0?
There is an old post asking for a construct for which sizeof would return 0. There are some high score answers from high reputation users saying that by the standard no type or variable can have sizeof 0. And I agree 100% with that.

However there is this new answer which presents this solution:

```<code>struct ZeroMemory {
    int *a[0];
};
</code>```

I was just about to down-vote and comment on it, but time spent here taught me to check even the things that I am 100% sure on. So... to my surprise both gcc and clang show the same results: sizeof(ZeroMemory) == 0. Even more, sizeof a variable is 0:

```<code>ZeroMemory z{};
static_assert(sizeof(z) == 0); // Awkward...
</code>```

Whaaaat...?

Godbolt link

How is this possible?

答:
Zero length arrays are an extension by GCC and Clang. Applying sizeof to zero-length arrays evaluates to zero.

A C++ class (empty) can't have size 0, but note that the class ZeroMemory is not empty. It has a named member with size 0 and applying sizeof will return zero.

Body:
There is an old post asking for a construct for which sizeof would return 0. There are some high score answers from high reputation users saying that by the standard no type or variable can have sizeof 0. And I agree 100% with that.

However there is this new answer which presents this solution:

struct ZeroMemory {
    int *a[0];
};

I was just about to down-vote and comment on it, but time spent here taught me to check even the things that I am 100% sure on. So... to my surprise both gcc and clang show the same results: sizeof(ZeroMemory) == 0. Even more, sizeof a variable is 0:

ZeroMemory z{};
static_assert(sizeof(z) == 0); // Awkward...

Whaaaat...?

Godbolt link

How is this possible?