问:
Maintaining Position of Array During Navigation
I have an array of images that are utilized to replace the DIV background on click.  I have two buttons (basically forward and reverse)and what I am trying to accomplish is that for the forward (or back) buttons to maintain last position of the array prior to executing the function, here is the code;

```<code>var ImagesB = [];
ImagesB[0]="images/image1.png";
ImagesB[1]="images/image2.png";
ImagesB[2]="images/image3.png";

var i = 1;

function updateImgB(){
  var url = 'url(' + ImagesB[i] + ')';
    document.getElementById('DIV1').style.backgroundImage = url;
    i = (i + 1)%(ImagesB.length);
}

function reverseImgB(){
  var url = 'url(' + ImagesB[i] + ')';
    document.getElementById('DIV1).style.backgroundImage = url;
    i = (i - 1)%(ImagesB.length);
    if(i < 0){i = ImagesB.length - 1};
}
</code>```

Currently this works, however say for instance you execute updateImgB, it ends with the next number in the array, eg: i + 1, therefore if I execute the reverseImgB function, it begins on the next image ie: 2, then will work backwards.  It is my intention for it to work backwards from the current image, and vice versa.

Any help appreciated.

答:
Just subtract 1 from i before changing the Image:

```<code>function reverseImgB(){
    i = (i - 1)%(ImagesB.length);
    if(i < 0){i = ImagesB.length - 1};
    var url = 'url(' + ImagesB[i] + ')';
    document.getElementById('DIV1).style.backgroundImage = url;
}
</code>```

Body:
I have an array of images that are utilized to replace the DIV background on click.  I have two buttons (basically forward and reverse)and what I am trying to accomplish is that for the forward (or back) buttons to maintain last position of the array prior to executing the function, here is the code;

var ImagesB = [];
ImagesB[0]="images/image1.png";
ImagesB[1]="images/image2.png";
ImagesB[2]="images/image3.png";

var i = 1;

function updateImgB(){
  var url = 'url(' + ImagesB[i] + ')';
    document.getElementById('DIV1').style.backgroundImage = url;
    i = (i + 1)%(ImagesB.length);
}

function reverseImgB(){
  var url = 'url(' + ImagesB[i] + ')';
    document.getElementById('DIV1).style.backgroundImage = url;
    i = (i - 1)%(ImagesB.length);
    if(i < 0){i = ImagesB.length - 1};
}

Currently this works, however say for instance you execute updateImgB, it ends with the next number in the array, eg: i + 1, therefore if I execute the reverseImgB function, it begins on the next image ie: 2, then will work backwards.  It is my intention for it to work backwards from the current image, and vice versa.

Any help appreciated.

Body:
Just subtract 1 from i before changing the Image:

function reverseImgB(){
    i = (i - 1)%(ImagesB.length);
    if(i < 0){i = ImagesB.length - 1};
    var url = 'url(' + ImagesB[i] + ')';
    document.getElementById('DIV1).style.backgroundImage = url;
}


来源: stackexchange

问:
Simulate app with Firebase services in China
My app uses FireBase services such as notifications, crash reports and more.
I know that some Google services are blocked in China, is there a way for me to simulate (from outside China) how my app will perform in China in order to test what services are blocked and what will be the effect to the app?</p>

答:
All google.com urls are blocked in China. Since all references to Firebase are using google.com, it is pretty much guaranteed that no parts of your app will be able to access any Firebase services when used from inside China. You may use simulators like Dotcom Tools to understand accessibility of Urls from China.

Additionally, you can read here on how to get a China VPN address and then simulate accessing the Firebase services from there: [VPN into China].2

But also do note that Google Playstore is not accessible from China. So users in China cannot download Android app either (unless yours is iOS).

So you will have to find alternative mechanism to distribute and run your app for the Chinese market.

ContentLicense: CC BY-SA 4.0


问:
Finding id's not in other table SQL
Help!

I am trying to find the customer that are in VBSTEST that are not in VMFG9. the tables have identical schema. Whenever i run the query i never get a result returning.

```<code>`SELECT [ROWID]
      ,[ID]
      ,[NAME]
      ,[ADDR_1]
      ,[ADDR_2]
      ,[ADDR_3]
      ,[CITY]
      ,[STATE]
      ,[ZIPCODE]
      ,[COUNTRY]
  FROM [VMFG9].[dbo].[CUSTOMER]
   where NOT EXISTS(
        select v6.[ID]
        from [VBSTEST].[dbo].[CUSTOMER] as v6
        left outer join [VMFG9].[dbo.CUSTOMER] as v9 on  v9.id = v6.[id]
        where v9.id is null);`
</code>```

答:
With your NOT EXISTS you are currently saying, select all rows only when the subquery returns no results (else return nothing).

The subquery itself should be adequate:

```<code>select v6.*
from [VBSTEST].[dbo].[CUSTOMER] as v6
left outer join [VMFG9].[dbo.CUSTOMER] as v9 on  v9.id = v6.[id]
where v9.id is null
</code>```

ContentLicense: CC BY-SA 3.0

Title: Finding id's not in other table SQL

Body:
Help!

I am trying to find the customer that are in VBSTEST that are not in VMFG9. the tables have identical schema. Whenever i run the query i never get a result returning.

`SELECT [ROWID]
      ,[ID]
      ,[NAME]
      ,[ADDR_1]
      ,[ADDR_2]
      ,[ADDR_3]
      ,[CITY]
      ,[STATE]
      ,[ZIPCODE]
      ,[COUNTRY]
  FROM [VMFG9].[dbo].[CUSTOMER]
   where NOT EXISTS(
        select v6.[ID]
        from [VBSTEST].[dbo].[CUSTOMER] as v6
        left outer join [VMFG9].[dbo.CUSTOMER] as v9 on  v9.id = v6.[id]
        where v9.id is null);`

Body:
With your NOT EXISTS you are currently saying, select all rows only when the subquery returns no results (else return nothing).

The subquery itself should be adequate:

select v6.*
from [VBSTEST].[dbo].[CUSTOMER] as v6
left outer join [VMFG9].[dbo.CUSTOMER] as v9 on  v9.id = v6.[id]
where v9.id is null


问:
how to add user and login with google oauth

Im trying to add google oauth2 as my login method in superset. Users cant register by their own, the system admin must provide access for the user deppending on permissions/role.

When a annonymous user loged in, the system must check if the user email exist and what role is applied to him and show the user profile

I already have the google oauth2 linked in superset, i can click in the login google button the login pop apears and enter the email and pasword of an google acount. But when the login is done, it apears a message saying that the user is not authorized.

Login Page

After Login, with console error (page stays loading...)

The question is how i can associate an google user to a superset user, or register an user by this google oauth2 method with the respective role?

答:
One thing you can do is set Flask App Builder's AUTH_USER_REGISTRATION = True and
AUTH_USER_REGISTRATION_ROLE = "some_default_role".

Then if you want to alter the registration flow, I'd recommend setting your own SecurityManager and overriding BaseSecurityManager.auth_user_oauth . I'd copy the source of that method and alter it.

I'd be great if FAB had a pre_registration hook in BaseSecurityManager for this purpose. Maybe it could receive the User object FAB is planning on creating (before it gets created) and could return a list of roles, or None if we want to abort the registration process.


问:
Windows Forms: capturing MouseWheel
I have a Windows Form (working in C#.NET).

The form has a couple of panels top-side and some ComboBoxes and DataGridViews bottom-side.

I want to use the scroll events on the top-side panels, but if selecting a e.g. ComboBox the focus is lost. The panels contain various other controls.

How could I always receive the mouse wheel events when the mouse is over any of the panels ?
So far I tried to use the MouseEnter / MouseEnter events but with no luck.

答:
What you describe sounds like you want to replicate the functionality of for example Microsoft Outlook, where you don't need to actually click to focus the control to use the mouse wheel on it.

This is a relatively advanced problem to solve: it involves implementing the IMessageFilter interface of the containing form, looking for WM_MOUSEWHEEL events and directing them to the control that the mouse is hovering over.

Here's an example (from here):

```<code>using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsApplication1 {
  public partial class Form1 : Form, IMessageFilter {
    public Form1() {
      InitializeComponent();
      Application.AddMessageFilter(this);
    }

    public bool PreFilterMessage(ref Message m) {
      if (m.Msg == 0x20a) {
        // WM_MOUSEWHEEL, find the control at screen position m.LParam
        Point pos = new Point(m.LParam.ToInt32());
        IntPtr hWnd = WindowFromPoint(pos);
        if (hWnd != IntPtr.Zero && hWnd != m.HWnd && Control.FromHandle(hWnd) != null) {
          SendMessage(hWnd, m.Msg, m.WParam, m.LParam);
          return true;
        }
      }
      return false;
    }

    // P/Invoke declarations
    [DllImport("user32.dll")]
    private static extern IntPtr WindowFromPoint(Point pt);
    [DllImport("user32.dll")]
    private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
  }
}
</code>```

Note that this code is active for all the forms in your application, not just the main form.

ContentLicense: CC BY-SA 2.5

Title: Windows Forms: capturing MouseWheel

Body:
What you describe sounds like you want to replicate the functionality of for example Microsoft Outlook, where you don't need to actually click to focus the control to use the mouse wheel on it.

This is a relatively advanced problem to solve: it involves implementing the IMessageFilter interface of the containing form, looking for WM_MOUSEWHEEL events and directing them to the control that the mouse is hovering over.

Here's an example (from here):

using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsApplication1 {
  public partial class Form1 : Form, IMessageFilter {
    public Form1() {
      InitializeComponent();
      Application.AddMessageFilter(this);
    }

    public bool PreFilterMessage(ref Message m) {
      if (m.Msg == 0x20a) {
        // WM_MOUSEWHEEL, find the control at screen position m.LParam
        Point pos = new Point(m.LParam.ToInt32());
        IntPtr hWnd = WindowFromPoint(pos);
        if (hWnd != IntPtr.Zero && hWnd != m.HWnd && Control.FromHandle(hWnd) != null) {
          SendMessage(hWnd, m.Msg, m.WParam, m.LParam);
          return true;
        }
      }
      return false;
    }

    // P/Invoke declarations
    [DllImport("user32.dll")]
    private static extern IntPtr WindowFromPoint(Point pt);
    [DllImport("user32.dll")]
    private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
  }
}

Note that this code is active for all the forms in your application, not just the main form.


问:
Code to find max number from array
I wrote the following code to find the max number from a array of numbers. Apparently there is an error in my code.It is a segmentation error. Please help me identify it.</p>

```<code>#include <stdio.h>
void max(int n,int A[n]);

int main()
{
int n;
int A[n];
max(n,A[n]);
}

void max(int n,int A[n])
{
printf("Enter the number of elements you want in your array\n");
scanf("%d",&n);
int i;
printf("Enter the elements  in your array\n");
for(i=0;i<n;i++)
{
    scanf("%d",&A[i]);
}
int max=A[0];
for(i=1;i<n;i++)
{
    if(A[i]>max)
    {
        max=A[i];
    }
}
printf("%d",max);
}
</code>```

答:
```<code>int n;
int A[n];
</code>```

You have to initialize n otherwise it contains garbage value. And now after this point you run into undefined behavior.

Correct code would be

```<code>#include <stdio.h>
#include <stdlib.h>
void printMax(int n,int A[]);

int main()
{
    size_t n;
    printf("Enter the number of elements you want in your array\n");
    if( scanf("%zu",&n) != 1){
        fprintf(stderr,"Error in input");
    }
    if( n <= 0){
        fprintf(stderr, "%s\n", "Error in input : Enter number >= 0 .");
    }
    int a[n];
    printf("Enter the elements  in your array\n");
    for(size_t i = 0; i < n; i++)
    {
        if( scanf("%d",&a[i]) != 1){
            fprintf(stderr,"%s\n","Error in input");
            exit(1);
        }
    }
    printMax(n,a);
    return 0;
}

void printMax(size_t n,int A[])
{
    int max=A[0];
    for(size_t i = 1; i < n; i++)
        if(A[i] > max)
            max = A[i];

    printf("%d",max);
}
</code>```

Title: Code to find max number from array

Body:
I wrote the following code to find the max number from a array of numbers. Apparently there is an error in my code.It is a segmentation error. Please help me identify it.

#include <stdio.h>
void max(int n,int A[n]);

int main()
{
int n;
int A[n];
max(n,A[n]);
}

void max(int n,int A[n])
{
printf("Enter the number of elements you want in your array\n");
scanf("%d",&n);
int i;
printf("Enter the elements  in your array\n");
for(i=0;i<n;i++)
{
    scanf("%d",&A[i]);
}
int max=A[0];
for(i=1;i<n;i++)
{
    if(A[i]>max)
    {
        max=A[i];
    }
}
printf("%d",max);
}

Body:
int n;
int A[n];

You have to initialize n otherwise it contains garbage value. And now after this point you run into undefined behavior.

Correct code would be

#include <stdio.h>
#include <stdlib.h>
void printMax(int n,int A[]);

int main()
{
    size_t n;
    printf("Enter the number of elements you want in your array\n");
    if( scanf("%zu",&n) != 1){
        fprintf(stderr,"Error in input");
    }
    if( n <= 0){
        fprintf(stderr, "%s\n", "Error in input : Enter number >= 0 .");
    }
    int a[n];
    printf("Enter the elements  in your array\n");
    for(size_t i = 0; i < n; i++)
    {
        if( scanf("%d",&a[i]) != 1){
            fprintf(stderr,"%s\n","Error in input");
            exit(1);
        }
    }
    printMax(n,a);
    return 0;
}

void printMax(size_t n,int A[])
{
    int max=A[0];
    for(size_t i = 1; i < n; i++)
        if(A[i] > max)
            max = A[i];

    printf("%d",max);
}


问:
Read a file line by line and run a java program
I need to run a java program that merge multiple files with a *bam extension. the structure of the program is:

```<code>java -jar mergefiles.jar \
I=file1.bam \
I=file2.bam \
I=file3.bam \
O=output.bam
</code>```

So, I am trying the run this program for all *bam files in a directory. Initially, I try to create a list with the names of the *bam files (filenames.txt)

```<code>file1.bam
file2.bam
file3.bam
</code>```

and using the 'while' command, like:

```<code>while read -r line; do
java -jar MergeFiles.jar \
I=$line \
O=output.bam
done < filenames.txt
</code>```

However, the program executed for each *bam file in the text file but not all together (merge only one file per time, and overwrite the output). So, how I can run the program to merge all *bam files recursively?

Also, there are other option in the bash (e.g. using a loop for) to solve this issue?

Thanks in advance.

答:
In your question you specify that you would like to use all .bam files in a dir, so instead of creating a file with the filenames, you should probably use globbing instead. Here's an example:

```<code>#! /bin/bash
# set nullglob to be safe
shopt -s nullglob
# read the filenames into an array
files=( *.bam )
# check that files actually exist
if (( ${#files[@]} == 0 )); then echo "no files" && exit 1; fi
# expand the array with a replacement
java -jar MergeFiles.jar \
"${files[@]/#/I=}" \
O=output.bam
</code>```

The problem with your current solution is that the while loop will only read one line at a time, calling the command on each line separately.

Body:
I need to run a java program that merge multiple files with a *bam extension. the structure of the program is:

java -jar mergefiles.jar \
I=file1.bam \
I=file2.bam \
I=file3.bam \
O=output.bam

So, I am trying the run this program for all *bam files in a directory. Initially, I try to create a list with the names of the *bam files (filenames.txt)

file1.bam
file2.bam
file3.bam

and using the 'while' command, like:

while read -r line; do
java -jar MergeFiles.jar \
I=$line \
O=output.bam
done < filenames.txt

However, the program executed for each *bam file in the text file but not all together (merge only one file per time, and overwrite the output). So, how I can run the program to merge all *bam files recursively?

Also, there are other option in the bash (e.g. using a loop for) to solve this issue?

Thanks in advance.

Body:
In your question you specify that you would like to use all .bam files in a dir, so instead of creating a file with the filenames, you should probably use globbing instead. Here's an example:

#! /bin/bash
# set nullglob to be safe
shopt -s nullglob
# read the filenames into an array
files=( *.bam )
# check that files actually exist
if (( ${#files[@]} == 0 )); then echo "no files" && exit 1; fi
# expand the array with a replacement
java -jar MergeFiles.jar \
"${files[@]/#/I=}" \
O=output.bam

The problem with your current solution is that the while loop will only read one line at a time, calling the command on each line separately.


问:
Playing a GPX using OpenLayers
I keep a GPX file with timestamps for commercial flights, and I'm trying to create a system whereby I can take a GPX file (from my webserver), overlay it on a map and allow me to play it back in real time.  The idea is to make it like the moving maps you get on an aircraft, so I can overlay it onto videos I make.

Is there any way to do this with OpenLayers?  The GPX part isn't essential - I can get a KML or CSV of the same data, I'd just like to be able to play back in real time!

Thanks in advance :)

答:
Yes, you can parse GPX into OpenLayers and build a vector source, and of course a layer. Look at the OL examples, there is at least one that reads a GPX:

```<code>var vector = new ol.layer.Vector({
  source: new ol.source.Vector({
    url: 'https://openlayers.org/en/v4.6.2/examples/data/gpx/fells_loop.gpx',
    format: new ol.format.GPX()
  })
});
</code>```

By default that would simply display the whole path. By using the timestamp information, you could then use the vector data and move an icon along the path

There are multiple examples available that show how to move an icon along a path:

Marker Animation example

IGC Data example

Title: Playing a GPX using OpenLayers

Body:
Yes, you can parse GPX into OpenLayers and build a vector source, and of course a layer. Look at the OL examples, there is at least one that reads a GPX:

var vector = new ol.layer.Vector({
  source: new ol.source.Vector({
    url: 'https://openlayers.org/en/v4.6.2/examples/data/gpx/fells_loop.gpx',
    format: new ol.format.GPX()
  })
});

By default that would simply display the whole path. By using the timestamp information, you could then use the vector data and move an icon along the path

There are multiple examples available that show how to move an icon along a path:

Marker Animation example

IGC Data example


问:
Python Trig Functions Return Complex Numbers?

I am writing code that accepts the degree by which a motor turns and uses that data to calculate the distance covered by the wheels (using distance = no. of rotations * distance covered per rotation).

It then makes an error adjustment (taking into consideration environmental factors such as friction).

Finally, using trigonometry, it calculates the distance moved along the x-axis and y-axis.

All the above is done by the function straight contained within the class CoordinateManager. This function is called by an instance of another class.

```<code>class CoordinateManager:
    goalcord = [20, 0]

    def __init__(self):
        self.curcord = [0, 0]
        self.theta = 0

    def get_compass_angle(self):
        compass = Sensor(address='in2')
        return compass.value(0)

    def turn(self, iangle, fangle):
        self.theta = self.theta + (fangle-iangle)

    def straight(self, turnangle):
        d = turnangle*2*3.14*2/360
        d = 1.8120132*(d**0.8938054)
        thetarad = radians(self.theta)
        dx = d*sin(thetarad)
        dy = d*cos(thetarad)
        self.curcord[0] += dx
        self.curcord[1] += dy
</code>```

Printing both d and self.theta shows that they contain correct values.

This must mean that the array self.curcord has valid values too. However, this has not been the case. Printing the two elements of self.curcord outputs complex numbers (some big float + another big floatj).

I can think of no logical explanation for this other than that the trigonometric functions must be returning complex numbers. However, I think the chances that a python built-in lib function returns wrong values are extraordinarily slim.

Is there any logical error that I may be overlooking?

Edit: I just tried changing the last two lines to:

```<code>self.curcord[0] += dx
self.curcord[1] += dy
</code>```

I just tried using .real when displaying the values. Even though the values are real now, they are still wrong. I will look further into whether this is caused by some calculation error.

答:
Since you said in the comments above that turnangle can be any integer, the problem can be directly traced to this line:

```<code>d = 1.8120132*(d**0.8938054)
</code>```

Since turnangle can be negative, the value of d before this line is executed can also be negative; a negative value raised to an arbitrary decimal power is in general complex.

Therefore the problem does not lie with the trig functions at all. The above also leads me to believe that when you said

Printing both d and self.theta shows that they contain correct values

... you only did so after this line:

```<code>d = turnangle*2*3.14*2/360
</code>```

This would explain why you wrongly thought the problem must lie elsewhere.

UPDATE:

It is a very bad habit to set a variable to some function of itself like you did. Try to use a different variable name to avoid confusion - as you saw above I had to refer to "this line" rather than by their variable names.

Perhaps something like this would work, assuming that the behaviour of the motor is the same regardless of the sign of turnangle?

```<code>d = sign(d) * 1.8120132 * (abs(d) ** 0.8938054)
</code>```

Body:
I am writing code that accepts the degree by which a motor turns and uses that data to calculate the distance covered by the wheels (using distance = no. of rotations * distance covered per rotation).

It then makes an error adjustment (taking into consideration environmental factors such as friction).

Finally, using trigonometry, it calculates the distance moved along the x-axis and y-axis.

All the above is done by the function straight contained within the class CoordinateManager. This function is called by an instance of another class.

class CoordinateManager:
    goalcord = [20, 0]

    def __init__(self):
        self.curcord = [0, 0]
        self.theta = 0

    def get_compass_angle(self):
        compass = Sensor(address='in2')
        return compass.value(0)

    def turn(self, iangle, fangle):
        self.theta = self.theta + (fangle-iangle)

    def straight(self, turnangle):
        d = turnangle*2*3.14*2/360
        d = 1.8120132*(d**0.8938054)
        thetarad = radians(self.theta)
        dx = d*sin(thetarad)
        dy = d*cos(thetarad)
        self.curcord[0] += dx
        self.curcord[1] += dy

Printing both d and self.theta shows that they contain correct values.

This must mean that the array self.curcord has valid values too. However, this has not been the case. Printing the two elements of self.curcord outputs complex numbers (some big float + another big floatj).

I can think of no logical explanation for this other than that the trigonometric functions must be returning complex numbers. However, I think the chances that a python built-in lib function returns wrong values are extraordinarily slim.

Is there any logical error that I may be overlooking?

Edit: I just tried changing the last two lines to:

self.curcord[0] += dx
self.curcord[1] += dy

I just tried using .real when displaying the values. Even though the values are real now, they are still wrong. I will look further into whether this is caused by some calculation error.

Body:
Since you said in the comments above that turnangle can be any integer, the problem can be directly traced to this line:

d = 1.8120132*(d**0.8938054)

Since turnangle can be negative, the value of d before this line is executed can also be negative; a negative value raised to an arbitrary decimal power is in general complex.

Therefore the problem does not lie with the trig functions at all. The above also leads me to believe that when you said

Printing both d and self.theta shows that they contain correct values

... you only did so after this line:

d = turnangle*2*3.14*2/360

This would explain why you wrongly thought the problem must lie elsewhere.

UPDATE:

It is a very bad habit to set a variable to some function of itself like you did. Try to use a different variable name to avoid confusion - as you saw above I had to refer to "this line" rather than by their variable names.

Perhaps something like this would work, assuming that the behaviour of the motor is the same regardless of the sign of turnangle?

d = sign(d) * 1.8120132 * (abs(d) ** 0.8938054)


问:
Getting 'dispatch is not defined' in redux component
I am trying to get a list of names stored in firebase to save to the redux store when the component loads. This list then gets sent to a dropdown component as props which are rendered as selectable options in the dropdown. For some reason I am getting 'dispatch is not defined' and I am not sure how to fix.

This is my code:

```<code>  //store
  import * as redux from 'redux';
  import thunk from 'redux-thunk';
  import {userReducer, exampleReducer, namesReducer} from 'reducers';

  export var configure = (initialState = {}) => {
    const reducer = redux.combineReducers({
            user: userReducer,
            example: exampleReducer,
            names: namesReducer
        })

  var store = redux.createStore(reducer, initialState, redux.compose(
      redux.applyMiddleware(thunk),
      window.devToolsExtension ? window.devToolsExtension() : f => f
    ));

    return store;
  };

  //reducers
  export var namesReducer = (state = [], action) => {
    switch (action.type) {
      case 'GET_NAMES':
        return [
          action.names
        ]
      default:
      return state;
    }
  }

  //actions
  export var getNames = (names) => {
    return {
        type: 'GET_NAMES',
        names
    }
  };

  export var startGetNames = () => {
    console.log("action started")
    return (dispatch) => {
        var nameRef = firebase.database().ref().child('names');
        return nameRef.once('value').then((snapshot) => {
                var data = snapshot.val();
                _.map(data, function(name) {return finalArr.push(
              {
                display: `${name.first_name} ${name.last_name}`,
                value: name.id
              }
            )});
           dispatch(getNames(finalArr));
        })
      }
  }

  //component
  import _ from 'underscore';
  import React from 'react';
  import { render } from "react-dom";
  import {connect} from 'react-redux';
  import Modal from 'react-responsive-modal';
  var actions = require('actions');
  var firebase = require('firebase/app');
  require('firebase/auth');
  require('firebase/database');
  //components
  import roomBookingForm from 'roomBookingForm';

  import PanelHeader from 'PanelHeader';
  import PanelItem from 'PanelItem';
  import Table from 'Table';
  import TableRow from 'TableRow';
  import TableHeaderCell from 'TableHeaderCell';
  import TextInput from 'TextInput';
  import Dropdown from 'Dropdown';

  class roomBooking extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
      pageTitle: "Appointment Creation",
      openForm: false
    }
  }

  componentWillMount() {
   this.props.clinicians
  }

   onOpenModal = () => {
    this.setState({openForm: true});
  }

   modalClose = () => {
    this.setState({ openForm: false });
  };

    render() {
      return (
        <div className="main-container">
          <div className="options-menu">
            <PanelHeader >
              Options
            </PanelHeader>
              <PanelItem onClick={this.onOpenModal} propClassLeft="left-item" propClassRight="right-item">Create Appointment</PanelItem>
          </div>
        <div>
          <Table className="display-table">
            <TableRow className="display-table-head">
              <TableHeaderCell className="name" displayText="Name" />
            </TableRow>
          </Table>
        </div>
        <roomBookingForm open={this.state.openForm} onClose={this.modalClose} options={this.props.names} />
      </div>
      )
    }
  }

  const mapDispatchToProps = (dispatch) => {
    names : dispatch(actions.startGetNames())
  }

  export default connect()(roomBooking);
</code>```

答:
You have two correction in your code.

1.
 You need to pass mapDispatchToProps in the connect call.

```<code>const mapDispatchToProps = (dispatch) => {
   names : dispatch(actions.startGetNames())
}

export default connect(null,mapDispatchToProps)(roomBooking);
</code>```

2.To call asynchronous action method with react-redux,the right signature is :

```<code>export var startGetNames = () => (dispatch) => {

        return (dispatch) => {
                 //code
            }
        }
</code>```

Body:
I am trying to get a list of names stored in firebase to save to the redux store when the component loads. This list then gets sent to a dropdown component as props which are rendered as selectable options in the dropdown. For some reason I am getting 'dispatch is not defined' and I am not sure how to fix.

This is my code:

  //store
  import * as redux from 'redux';
  import thunk from 'redux-thunk';
  import {userReducer, exampleReducer, namesReducer} from 'reducers';

  export var configure = (initialState = {}) => {
    const reducer = redux.combineReducers({
            user: userReducer,
            example: exampleReducer,
            names: namesReducer
        })

  var store = redux.createStore(reducer, initialState, redux.compose(
      redux.applyMiddleware(thunk),
      window.devToolsExtension ? window.devToolsExtension() : f => f
    ));

    return store;
  };

  //reducers
  export var namesReducer = (state = [], action) => {
    switch (action.type) {
      case 'GET_NAMES':
        return [
          action.names
        ]
      default:
      return state;
    }
  }

  //actions
  export var getNames = (names) => {
    return {
        type: 'GET_NAMES',
        names
    }
  };

  export var startGetNames = () => {
    console.log("action started")
    return (dispatch) => {
        var nameRef = firebase.database().ref().child('names');
        return nameRef.once('value').then((snapshot) => {
                var data = snapshot.val();
                _.map(data, function(name) {return finalArr.push(
              {
                display: `${name.first_name} ${name.last_name}`,
                value: name.id
              }
            )});
           dispatch(getNames(finalArr));
        })
      }
  }

  //component
  import _ from 'underscore';
  import React from 'react';
  import { render } from "react-dom";
  import {connect} from 'react-redux';
  import Modal from 'react-responsive-modal';
  var actions = require('actions');
  var firebase = require('firebase/app');
  require('firebase/auth');
  require('firebase/database');
  //components
  import roomBookingForm from 'roomBookingForm';

  import PanelHeader from 'PanelHeader';
  import PanelItem from 'PanelItem';
  import Table from 'Table';
  import TableRow from 'TableRow';
  import TableHeaderCell from 'TableHeaderCell';
  import TextInput from 'TextInput';
  import Dropdown from 'Dropdown';

  class roomBooking extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
      pageTitle: "Appointment Creation",
      openForm: false
    }
  }

  componentWillMount() {
   this.props.clinicians
  }

   onOpenModal = () => {
    this.setState({openForm: true});
  }

   modalClose = () => {
    this.setState({ openForm: false });
  };

    render() {
      return (

            <PanelHeader >
              Options
            </PanelHeader>
              <PanelItem onClick={this.onOpenModal} propClassLeft="left-item" propClassRight="right-item">Create Appointment</PanelItem>

            <TableRow className="display-table-head">
              <TableHeaderCell className="name" displayText="Name" />
            </TableRow>

        <roomBookingForm open={this.state.openForm} onClose={this.modalClose} options={this.props.names} />

      )
    }
  }

  const mapDispatchToProps = (dispatch) => {
    names : dispatch(actions.startGetNames())
  }

  export default connect()(roomBooking);

Body:
You have two correction in your code.

1.
 You need to pass mapDispatchToProps in the connect call.

const mapDispatchToProps = (dispatch) => {
   names : dispatch(actions.startGetNames())
}

export default connect(null,mapDispatchToProps)(roomBooking);

2.To call asynchronous action method with react-redux,the right signature is :

export var startGetNames = () => (dispatch) => {

        return (dispatch) => {
                 //code
            }
        }


问:
Getting the date goes back one day
I have an entity with the field

```<code>public class MovieReleaseDateEntity {
     @Basic
     @Column(name = "release_date")
     @Temporal(TemporalType.DATE)
     private Date date;
}
</code>```

I save the date in the database

```<code>https://zapodaj.net/14dfcfb70926a.png.html
</code>```

I get it after downloading it from the database

```<code>"date": "2017-12-06T23:00:00.000+0000"
</code>```

The date is withdrawn by one day. Why?

答:
tl;dr

These all represent the very same point on the timeline, the very same simultaneous moment:

2017-12-06T23:00:00.000+0000

2017-12-07T00:00:00.000+01:00

2017-12-07T04:30:00.000+05:30

Details

The Europe/Warsaw time zone is currently one hour ahead of UTC.

"2017-12-06T23:00:00.000+0000"

Your string represents a moment in UTC. Note the +0000, an abbreviation of +00:00, which means an offset of zero hours and zero minutes from UTC. So it is at UTC.

That same  moment as seen thorough the lens of a clock on the wall on Poland is 00:00 on the morning of the next date. That is the first moment of the new day in Poland.

"2017-12-07T00:00:00.000+01:00"

That same moment is later on a wall-clock in India where the people live five and a half hours ahead of UTC.

"2017-12-07T04:30:00.000+05:30"

If an insomniac in Poland called their friend on the west coast of North America, they might catch their friend still on the job in mid-afternoon at 3 PM on the earlier date. There the clock on the wall is eight hours behind UTC.

"2017-12-06T15:00:00.000-08:00"

Parse your input string as an OffsetDateTime object. To view the same moment in other time zones, adding a ZoneId to get a ZonedDateTime. Search Stack Overflow for details as this has been covered many many times already.

Avoid the troublesome flawed old date-time classes such as Date. Use only their replacements, the modern industry-leading java.time classes.

Title: Getting the date goes back one day

Body:
I have an entity with the field

public class MovieReleaseDateEntity {
     @Basic
     @Column(name = "release_date")
     @Temporal(TemporalType.DATE)
     private Date date;
}

I save the date in the database

https://zapodaj.net/14dfcfb70926a.png.html

I get it after downloading it from the database

"date": "2017-12-06T23:00:00.000+0000"

The date is withdrawn by one day. Why?


问:
How to use spark_apply to change NaN values?
After using sdf_pivot I was left with a huge number of NaN values, so in order to proceed with my analysis I need to replace the NaN with 0, I have tried using this:

```<code>data <- data %>%
  spark_apply(function(e) ifelse(is.nan(e),0,e))
</code>```

And this gererates the following error:

```<code>Error in file(con, "r") : cannot open the connection
In addition: Warning message:
In file(con, "r") :
  cannot open file
'C:\.........\file18dc5a1c212e_spark.log':Permission denied
</code>```

I'm using Spark 2.2.0 and the latest version of sparklyr

Does anyone have an idea on how to fix this issue?
Thanks

答:
You seem to have two different problems here.

Permissions issues. Make sure that you have required permissions and correctly use winutils if necessary.

NULL replacement.

The latter one can solved using built-in functions and there is no need for inefficient spark_apply:

```<code>df <- copy_to(sc,
  data.frame(id=c(1, 1, 2, 3), key=c("a", "b", "a", "d"), value=1:4))

pivoted <- sdf_pivot(df, id ~ key)
pivoted
</code>```

# Source:   table<sparklyr_tmp_f0550e429aa> [?? x 4]
# Database: spark_connection
     id     a     b     d
  <dbl> <dbl> <dbl> <dbl>
1     1     1     1   NaN
2     3   NaN   NaN     1
3     2     1   NaN   NaN
```

<pre class="lang-r prettyprint-override"><code>pivoted %>% na.replace(0)
</code>```

# Source:   table<sparklyr_tmp_f0577e16bf1> [?? x 4]
# Database: spark_connection
     id     a     b     d
  <dbl> <dbl> <dbl> <dbl>
1     1     1     1     0
2     3     0     0     1
3     2     1     0     0
```

Tested with sparklyr 0.7.0-9105.

Body:
After using sdf_pivot I was left with a huge number of NaN values, so in order to proceed with my analysis I need to replace the NaN with 0, I have tried using this:

data <- data %>%
  spark_apply(function(e) ifelse(is.nan(e),0,e))

And this gererates the following error:

Error in file(con, "r") : cannot open the connection
In addition: Warning message:
In file(con, "r") :
  cannot open file
'C:\.........\file18dc5a1c212e_spark.log':Permission denied

I'm using Spark 2.2.0 and the latest version of sparklyr

Does anyone have an idea on how to fix this issue?
Thanks

Body:
You seem to have two different problems here.

Permissions issues. Make sure that you have required permissions and correctly use winutils if necessary.

NULL replacement.

The latter one can solved using built-in functions and there is no need for inefficient spark_apply:

df <- copy_to(sc,
  data.frame(id=c(1, 1, 2, 3), key=c("a", "b", "a", "d"), value=1:4))

pivoted <- sdf_pivot(df, id ~ key)
pivoted

# Source:   table<sparklyr_tmp_f0550e429aa> [?? x 4]
# Database: spark_connection
     id     a     b     d
  <dbl> <dbl> <dbl> <dbl>
1     1     1     1   NaN
2     3   NaN   NaN     1
3     2     1   NaN   NaN

pivoted %>% na.replace(0)

# Source:   table<sparklyr_tmp_f0577e16bf1> [?? x 4]
# Database: spark_connection
     id     a     b     d
  <dbl> <dbl> <dbl> <dbl>
1     1     1     1     0
2     3     0     0     1
3     2     1     0     0

Tested with sparklyr 0.7.0-9105.


问:
Thread safe code for Simpledate
can you please tell me if the following code is thread safe and how I could test it:

```<code>      private static final SimpleDateFormat sdf = new SimpleDateFormat("MMddHHmmss");
     Calendar cal = new GregorianCalendar();
  TimeZone timezone = cal.getTimeZone();

     AppCalendar qCal = new AppCalendar(timezone);
    qCal.setDateToday();
    qCal.setTimeNow();

    }

public static String createTempName(final TimeZone timeZone) {
    final AppCalendar calendar = new AppCalendar(timeZone);
    calendar.setDateToday();
    calendar.setTimeNow();
    synchronized (sdf) {
        return sdf.format(calendar.getTime());
    }
}
</code>```

I mention that my code runs on JVM 7 and I have to use Date types provided by this context. Unfortunately not being able to use thred save LocalDate from Java 8. I am using the string returned from method createTempName as a unique key in database column. appCalendar is class that extends java.util.GregorianCalendar.

Sincerely,

答: Yes, it is thread safe. You can test it as done in "Java DateFormat is not threadsafe" what does this leads to?. If performace is an issue I would recommend changing   synchronization to ThreadLocal as in Making DateFormat Threadsafe. What to use, synchronized or Thread local.</p>

Title: Thread safe code for Simpledate

Body:
can you please tell me if the following code is thread safe and how I could test it:

      private static final SimpleDateFormat sdf = new SimpleDateFormat("MMddHHmmss");
     Calendar cal = new GregorianCalendar();
  TimeZone timezone = cal.getTimeZone();

     AppCalendar qCal = new AppCalendar(timezone);
    qCal.setDateToday();
    qCal.setTimeNow();

    }

public static String createTempName(final TimeZone timeZone) {
    final AppCalendar calendar = new AppCalendar(timeZone);
    calendar.setDateToday();
    calendar.setTimeNow();
    synchronized (sdf) {
        return sdf.format(calendar.getTime());
    }
}

I mention that my code runs on JVM 7 and I have to use Date types provided by this context. Unfortunately not being able to use thred save LocalDate from Java 8. I am using the string returned from method createTempName as a unique key in database column. appCalendar is class that extends java.util.GregorianCalendar.

Sincerely,


问:
Rails 3, update linked model in controller on record creation
In my rails app I have the Posts Model, which has_many Comments.

Everytime a new comment is posted, I'd like the updated_at column in the Posts model to be updated.

I assume I need to do this in the create method of the Comments controller.

Does anyone have some idea of the specific way to do this?

```<code>   @post = Post.find_by_id(@comment.post_id)
   @post.save!
</code>```

Did not work.

Thanks!

-Elliot

答:
You want to keep as much as possible out of the controller. The controller is only for directing user input and output to the right places.

Also, you wouldn't want to be calling self.post.update_attributes from the Comment because that would be tying in too many Post-specific details.

```<code># in comment.rb
after_save :update_post_activity

def update_post_activity
  self.post.update_activity if self.post?
end

# in post.rb
def update_activity
  self.update_attributes(:updated_at => Time.now)
end
</code>```

Body:
In my rails app I have the Posts Model, which has_many Comments.

Everytime a new comment is posted, I'd like the updated_at column in the Posts model to be updated.

I assume I need to do this in the create method of the Comments controller.

Does anyone have some idea of the specific way to do this?

   @post = Post.find_by_id(@comment.post_id)
   @post.save!

Did not work.

Thanks!

-Elliot

Body:
You want to keep as much as possible out of the controller. The controller is only for directing user input and output to the right places.

Also, you wouldn't want to be calling self.post.update_attributes from the Comment because that would be tying in too many Post-specific details.

# in comment.rb
after_save :update_post_activity

def update_post_activity
  self.post.update_activity if self.post?
end

# in post.rb
def update_activity
  self.update_attributes(:updated_at => Time.now)
end


问:
Why does async: false inside a listener, stop all execution?
I've been staring at this issue for a few hours. I had a boilerplate code sample I was working off as follows

```<code>$('.save_stuff').on("click", function(e)
{
    e.preventDefault();
    e.stopPropagation();

    preprocessAddProvisioning();

    var mac = $('#c_mac_address').val();
    var make = $('#c_make').html();
    var model = $('#c_model option:selected').text();
    var regex = /[a-zA-Z0-9]{12}/g;

    if (mac.match(regex) && validateNewDevice())
    {
        $.ajax({
            url: "/SomeUrl",
            dataType: 'json',
            type: 'POST',
            async: false,
            data:
            {
                mac: mac,
                model: model,
                make: make
            },
            success: function(data)
            {
                if (data.success)
                {
                    $('#someValue').hide();
                    $('#modalNewDevice').modal('hide');

                    if (someValue !== undefined && !someValue.snom_mac_success)
                    {
                        window.location.href = "/SomeUrl?id="+someValue.newId+"&someValue=false";
                    }
                    else
                    {
                        window.location.href = "/SomeUrl?id="+data.newId;
                    }
                }
                else
                {
                    $('#c_msg').html(data.msg);
                    $('#c_msg').closest('.form-group').addClass('has-error');
                }
            },
            error: function()
            {

            }
        });
    }
});
</code>```

With the method called being;

```<code>function preprocessAddProvisioning()
{
    $('#mac_load').show('fast');
}
</code>```

Can someone tell me why, async: false, stops preprocessAddProvisioning() being called? I realize it's implication when thinking about the context of the ajax request, but not of the context of the listener.

Many thanks

答:
The AJAX request doesn't prevent preprocessAddProvisioning() from executing. It blocks the UI thread and prevents the window from updating, so it appears that preprocessAddProvisioning() has done nothing. On top of that, .show('fast') uses an animation, which would require not just one UI update, but many over a period of several milliseconds. With the JavaScript execution stopped, jQuery can't even try to carry out that animation, let alone have the window display it.

Demonstration of a window failing to update due to a blocked UI thread:

document.getElementsByTagName('input')[0].addEventListener('click', function (){
    var div = document.getElementsByTagName('div')[0];
    // hide div
    div.style.display = 'none';

    // block thread for 3 seconds
    var dt = new Date();
    while (new Date() - dt < 3000) {}
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div { width: 100px; height: 100px; background-color: red; }</code>```

<input type="button" value="Click me" />```
</div>
</div>
</p>

<p>Moral of the story: don't use <code>async: false</code>, but if you absolutely have to, you can use a timeout to ensure that your loader has finished displaying <em>before</em> you make the AJAX request:</p>

```setTimeout(function () {
    makeTheAjaxRequest();
}, 500);
```

Bear in mind that if your loader involves an animated .gif or anything like that, the .gif will be frozen while the UI thread is blocked.

An even more precise option would be to use the complete callback on .show() to continue executing your steps once the animation is complete, but all that's likely to accomplish is spaghetti-fying your code. The real answer is to not use async: false.

Body:
I've been staring at this issue for a few hours. I had a boilerplate code sample I was working off as follows

$('.save_stuff').on("click", function(e)
{
    e.preventDefault();
    e.stopPropagation();

    preprocessAddProvisioning();

    var mac = $('#c_mac_address').val();
    var make = $('#c_make').html();
    var model = $('#c_model option:selected').text();
    var regex = /[a-zA-Z0-9]{12}/g;

    if (mac.match(regex) && validateNewDevice())
    {
        $.ajax({
            url: "/SomeUrl",
            dataType: 'json',
            type: 'POST',
            async: false,
            data:
            {
                mac: mac,
                model: model,
                make: make
            },
            success: function(data)
            {
                if (data.success)
                {
                    $('#someValue').hide();
                    $('#modalNewDevice').modal('hide');

                    if (someValue !== undefined && !someValue.snom_mac_success)
                    {
                        window.location.href = "/SomeUrl?id="+someValue.newId+"&someValue=false";
                    }
                    else
                    {
                        window.location.href = "/SomeUrl?id="+data.newId;
                    }
                }
                else
                {
                    $('#c_msg').html(data.msg);
                    $('#c_msg').closest('.form-group').addClass('has-error');
                }
            },
            error: function()
            {

            }
        });
    }
});

With the method called being;

function preprocessAddProvisioning()
{
    $('#mac_load').show('fast');
}

Can someone tell me why, async: false, stops preprocessAddProvisioning() being called? I realize it's implication when thinking about the context of the ajax request, but not of the context of the listener.

Many thanks

Body:
The AJAX request doesn't prevent preprocessAddProvisioning() from executing. It blocks the UI thread and prevents the window from updating, so it appears that preprocessAddProvisioning() has done nothing. On top of that, .show('fast') uses an animation, which would require not just one UI update, but many over a period of several milliseconds. With the JavaScript execution stopped, jQuery can't even try to carry out that animation, let alone have the window display it.

Demonstration of a window failing to update due to a blocked UI thread:

document.getElementsByTagName('input')[0].addEventListener('click', function (){
    var div = document.getElementsByTagName('div')[0];
    // hide div
    div.style.display = 'none';

    // block thread for 3 seconds
    var dt = new Date();
    while (new Date() - dt < 3000) {}
});

div { width: 100px; height: 100px; background-color: red; }

<div>

</div>
<input type="button" value="Click me" />

Moral of the story: don't use async: false, but if you absolutely have to, you can use a timeout to ensure that your loader has finished displaying before you make the AJAX request:

setTimeout(function () {
    makeTheAjaxRequest();
}, 500);

Bear in mind that if your loader involves an animated .gif or anything like that, the .gif will be frozen while the UI thread is blocked.

An even more precise option would be to use the complete callback on .show() to continue executing your steps once the animation is complete, but all that's likely to accomplish is spaghetti-fying your code. The real answer is to not use async: false.


问:
Get simple recursive from table with id_parent
I guess my brain starts to slow down, but I want to get a recursive array of my results from this table :

```<code>|id|int(11)|
|name|varchar(150)|
|type|tinyint(4)|
|id_parent|mediumint(9)|

|1|Marque forte|1|0|
|2|Communication|2|1|
|3|Respect du CI|0|2|
|4|Stratégie digitale|0|2
|5|Expérience de marque|2|1|
|6|Gastronomie|0|5|
</code>```

I want an array like :

```<code>array('id' => array('name' => $name, 'childs' => array( ... ), 'id' => ...)
</code>```

I just want to order my dataset in one array.

I tried this so far :

```<code>// returns array of objects - codeigniter result
$dbResult = $this->db->get_where('table')->result();

// will contains the array
$this->data['tree'] = array();
$this->getRecursive(0, 0, $dbResult);
....

private function getRecursive($parent, $niveau, $result)
{
    foreach ($result AS $row)
    {
        if ($parent == $row->id_parent)
        {
            $this->data['tree'][] = array($row->name => $this->getRecursive($row->id, ($niveau + 1), $result));
        }
    }
}
</code>```

Which gives me weird result ...

答:
Please try this. I have used the $source array for testing. Since I did not get my result set from an actual database, you will have to make some changes in order to adjust it with your code (eg. change $row['id_parent'] to $row->id_parent and so on). However, conceptually it should work.

```<code><?php
        $source = [
                ['name' => 'A', 'id' => 1, 'id_parent' => 0],
                ['name' => 'B', 'id' => 2, 'id_parent' => 1],
                ['name' => 'C', 'id' => 3, 'id_parent' => 1],
                ['name' => 'D', 'id' => 4, 'id_parent' => 2],
                ['name' => 'E', 'id' => 5, 'id_parent' => 3],
                ['name' => 'F', 'id' => 5, 'id_parent' => 0],
        ];

        function getRecursive($source, $parent) {
            $result = [];
            foreach ($source as $row) {
                if ($parent == $row['id_parent']) {
                    $result[] = [
                                'id' => $row['id'],
                                'name' => $row['name'],
                                'childs' => getRecursive($source, $row['id'] )
                            ];
                        }
                }
                return $result;
        }

        print_r(getRecursive($source, 0));
</code>```

Body:
I guess my brain starts to slow down, but I want to get a recursive array of my results from this table :

|id|int(11)|
|name|varchar(150)|
|type|tinyint(4)|
|id_parent|mediumint(9)|

|1|Marque forte|1|0|
|2|Communication|2|1|
|3|Respect du CI|0|2|
|4|Stratégie digitale|0|2
|5|Expérience de marque|2|1|
|6|Gastronomie|0|5|

I want an array like :

array('id' => array('name' => $name, 'childs' => array( ... ), 'id' => ...)

I just want to order my dataset in one array.

I tried this so far :

// returns array of objects - codeigniter result
$dbResult = $this->db->get_where('table')->result();

// will contains the array
$this->data['tree'] = array();
$this->getRecursive(0, 0, $dbResult);
....

private function getRecursive($parent, $niveau, $result)
{
    foreach ($result AS $row)
    {
        if ($parent == $row->id_parent)
        {
            $this->data['tree'][] = array($row->name => $this->getRecursive($row->id, ($niveau + 1), $result));
        }
    }
}

Which gives me weird result ...

Body:
Please try this. I have used the $source array for testing. Since I did not get my result set from an actual database, you will have to make some changes in order to adjust it with your code (eg. change $row['id_parent'] to $row->id_parent and so on). However, conceptually it should work.

<?php
        $source = [
                ['name' => 'A', 'id' => 1, 'id_parent' => 0],
                ['name' => 'B', 'id' => 2, 'id_parent' => 1],
                ['name' => 'C', 'id' => 3, 'id_parent' => 1],
                ['name' => 'D', 'id' => 4, 'id_parent' => 2],
                ['name' => 'E', 'id' => 5, 'id_parent' => 3],
                ['name' => 'F', 'id' => 5, 'id_parent' => 0],
        ];

        function getRecursive($source, $parent) {
            $result = [];
            foreach ($source as $row) {
                if ($parent == $row['id_parent']) {
                    $result[] = [
                                'id' => $row['id'],
                                'name' => $row['name'],
                                'childs' => getRecursive($source, $row['id'] )
                            ];
                        }
                }
                return $result;
        }

        print_r(getRecursive($source, 0));


问:
ImageMagick supported formats no value
I have installed download and install ImageMagick-6.8.3-7-Q16-x86-dll.exe from the link http://imagemagick.org/script/binary-releases.php#windows and I am using Windows 7 and PHP 5.3.8.

When in install this it got installed correctly in my machine and convert commands works perfectly. On my convert config what shows is here:

But on my phpinfo section I get:

ImageMagick supported formats has no value

I got all the image magick values like this https://www.evernote.com/shard/s297/sh/12397c86-d016-4ca4-9415-fd541daeca39/2fc504bf5ddba5693efd3249402b2b5c.

I don't know why it is getting as no value i have installed the same ImageMagick-6.8.3-7-Q16-x86-dll.exe on php 5.3.8 in my 32 bit windows7 machine . The php_imagick.dll i downloded from other website. I don't know what is the issue i am having in install imagemaagick, if it is the issue with php_imagick.dll version can anybody suggest proper php_imagick version for this configuration?

答:
I had the same problem, and tried everything. You do not need - as I thought - ImageMagick installed on your system to run the Imagick module for PHP. You simply need to make sure you include both the CORE_RL_* dlls as well as the IM_MOD_* dlls in the apache/bin directory, and then also the php_imagick.dll in the php/ext directory.

I'm running PHP 7.0.25 x86 via XAMPP on Windows, and these instructions were incredibly simple and helpful:

https://mlocati.github.io/articles/php-windows-imagick.html

Title: ImageMagick supported formats no value


问:
Hierarchical clustering with SciPy: merge the points with greatest distance first
I have a problem using the hierarchy package in SciPy. Here there is an example of what my distance matrix is:

```<code>[[  0.,  40.,  33.,  28.],
 [ 40.,   0.,  35.,  28.],
 [ 33.,  35.,   0.,  28.],
 [ 28.,  28.,  28.,   0.]]
</code>```

I transform the matrix into a vector and I want a hierarchy that merges the highest value in the matrix, thus it should merge in order ((0-1)-2)-3). To do that I am using the 'complete' parameter, as it is written in the documentation that this is used to take the maximum, but it actually produce:  ((0-3)-2)-1)

This is the code the computes the linkage matrix:

```<code>Z = linkage(distArray, 'complete')
</code>```

Any advice?

答:
You misunderstood the meaning of 'complete' method. It only means that the distance between two clusters of points, say {A, B} and {C, D}, is taken to be the maximum of pairwise distances AC, AD, BC, BD. This does not change the fact that hierarchical clustering combines nearby clusters, those with smallest distance from each other. There is no clustering method for "combine points if they are very far apart".

If you want large entries in your distance matrix (call it D) to mean "these are similar" then you have to transform D to invert the order relation between distances. In other words, the matrix you have measures similarity of objects and you need a measure of dissimilarity.

The simplest thing to do is to change the sign; linkage does not actually require distances to be positive.

```<code>from scipy.cluster.hierarchy import linkage
from scipy.spatial.distance import squareform

linkage(-squareform(D), 'complete')
</code>```

returns

```<code>array([[  0.,   1., -40.,   2.],
       [  2.,   4., -33.,   3.],
       [  3.,   5., -28.,   4.]])
</code>```

indicating linkage ((0-1)-2)-3.

If negative values are an issue, there are other transformations which don't produce negative numbers:

```<code>linkage(D.max() - squareform(D), 'complete')
</code>```

or

```<code>linkage(squareform(D)**(-1), 'complete')
</code>```

All these will return the same hierarchy as long as 'complete' is the method'.

Of course, now that you know that 'complete' is not necessarily the thing you need, you may want to consider other methods as well, and then the effect of transformation imposed on D may change the outcome. Do what makes sense in your context, considering what D actually represents.

Body:
I have a problem using the hierarchy package in SciPy. Here there is an example of what my distance matrix is:

[[  0.,  40.,  33.,  28.],
 [ 40.,   0.,  35.,  28.],
 [ 33.,  35.,   0.,  28.],
 [ 28.,  28.,  28.,   0.]]

I transform the matrix into a vector and I want a hierarchy that merges the highest value in the matrix, thus it should merge in order ((0-1)-2)-3). To do that I am using the 'complete' parameter, as it is written in the documentation that this is used to take the maximum, but it actually produce:  ((0-3)-2)-1)

This is the code the computes the linkage matrix:

Z = linkage(distArray, 'complete')

Any advice?

Body:
You misunderstood the meaning of 'complete' method. It only means that the distance between two clusters of points, say {A, B} and {C, D}, is taken to be the maximum of pairwise distances AC, AD, BC, BD. This does not change the fact that hierarchical clustering combines nearby clusters, those with smallest distance from each other. There is no clustering method for "combine points if they are very far apart".

If you want large entries in your distance matrix (call it D) to mean "these are similar" then you have to transform D to invert the order relation between distances. In other words, the matrix you have measures similarity of objects and you need a measure of dissimilarity.

The simplest thing to do is to change the sign; linkage does not actually require distances to be positive.

from scipy.cluster.hierarchy import linkage
from scipy.spatial.distance import squareform

linkage(-squareform(D), 'complete')

returns

array([[  0.,   1., -40.,   2.],
       [  2.,   4., -33.,   3.],
       [  3.,   5., -28.,   4.]])

indicating linkage ((0-1)-2)-3.

If negative values are an issue, there are other transformations which don't produce negative numbers:

linkage(D.max() - squareform(D), 'complete')

or

linkage(squareform(D)**(-1), 'complete')

All these will return the same hierarchy as long as 'complete' is the method'.

Of course, now that you know that 'complete' is not necessarily the thing you need, you may want to consider other methods as well, and then the effect of transformation imposed on D may change the outcome. Do what makes sense in your context, considering what D actually represents.


问:
Move view up when keyboard is presented
The Question:

I have a ViewController that has a subclass with a UIScrollView in it.

In the scrollView there are 3 UITextFields. 2 of them with a numberPad keyboard and 1 with a UIPickerView keyboard.

The problem is that when the keyboards are presented, it hides the UITextFields. So what I'm trying to do is to move the UIViewController's view up when the keyboards are being shown.

What I've already tried:

I've searched this question on SO and I've found some answers, based on them I've wrote this code:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    //Keyboard notifications
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

//MARK: - keyboards

@objc fileprivate func keyboardWillShow(notification: Notification) {
    self.changeViewOriginBasedOnKeyboardPosition(notification: notification)
}

@objc fileprivate func keyboardWillHide(notification: Notification) {
    self.changeViewOriginBasedOnKeyboardPosition(notification: notification)
}

fileprivate func changeViewOriginBasedOnKeyboardPosition(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        let keyboardAnimationDuration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
        UIView.animate(withDuration: keyboardAnimationDuration != 0 ? keyboardAnimationDuration : 0.2, animations: {
            if self.controllerContentView.frame.origin.y == 0  {
                self.controllerContentView.frame.origin.y = -keyboardSize.height
            } else {
                self.controllerContentView.frame.origin.y = 0
            }
        })
    }
}

fileprivate func dismissKeyboard() {
    self.view.endEditing(true)
}

//Touch handling

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.dismissKeyboard()
}
</code>```

The problem with what I've tried:

Sometimes it works great, but sometimes the view "jumps" back up/"jumps" down and I can't understand why.

Does anybody see any problem with my code that can cause this bug?

Thank you!

答:
You need to set height as per your keyboard hide. There is four observer for Keyboard available.

```<code>1) UIKeyboardWillShow
2) UIKeyboardDidShow
3) UIKeyboardWillHide
4) UIKeyboardDidHide
</code>```

You need to register keyboard observer:

```<code>NotificationCenter.default.addObserver(self, selector: #selector(keyboardShowNotification), name:NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardHideNotification), name:NSNotification.Name.UIKeyboardWillHide, object: nil)
</code>```

Here is method observer method:

```<code>func keyboardShowNotification(notification:NSNotification){

    var userInfo = notification.userInfo!
    var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
    keyboardFrame = self.view.convert(keyboardFrame, from: nil)

    var contentInset:UIEdgeInsets = YOUR_SCROLLVIEW_OBJ.contentInset
    contentInset.bottom = keyboardFrame.size.height
    YOUR_SCROLLVIEW_OBJ.contentInset = contentInset
}

func keyboardHideNotification(notification:NSNotification){
    let contentInset:UIEdgeInsets = UIEdgeInsets.zero
    YOUR_SCROLLVIEW_OBJ = contentInset
}
</code>```

Another best key to handle keyboard is IQKeyboardManager. You just have to add them to your application and it will handle everything.

Title: Move view up when keyboard is presented

Body:
The Question:

I have a ViewController that has a subclass with a UIScrollView in it.

In the scrollView there are 3 UITextFields. 2 of them with a numberPad keyboard and 1 with a UIPickerView keyboard.

The problem is that when the keyboards are presented, it hides the UITextFields. So what I'm trying to do is to move the UIViewController's view up when the keyboards are being shown.

What I've already tried:

I've searched this question on SO and I've found some answers, based on them I've wrote this code:

override func viewDidLoad() {
    super.viewDidLoad()

    //Keyboard notifications
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

//MARK: - keyboards

@objc fileprivate func keyboardWillShow(notification: Notification) {
    self.changeViewOriginBasedOnKeyboardPosition(notification: notification)
}

@objc fileprivate func keyboardWillHide(notification: Notification) {
    self.changeViewOriginBasedOnKeyboardPosition(notification: notification)
}

fileprivate func changeViewOriginBasedOnKeyboardPosition(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        let keyboardAnimationDuration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
        UIView.animate(withDuration: keyboardAnimationDuration != 0 ? keyboardAnimationDuration : 0.2, animations: {
            if self.controllerContentView.frame.origin.y == 0  {
                self.controllerContentView.frame.origin.y = -keyboardSize.height
            } else {
                self.controllerContentView.frame.origin.y = 0
            }
        })
    }
}

fileprivate func dismissKeyboard() {
    self.view.endEditing(true)
}

//Touch handling

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.dismissKeyboard()
}

The problem with what I've tried:

Sometimes it works great, but sometimes the view "jumps" back up/"jumps" down and I can't understand why.

Does anybody see any problem with my code that can cause this bug?

Thank you!

Body:
You need to set height as per your keyboard hide. There is four observer for Keyboard available.

1) UIKeyboardWillShow
2) UIKeyboardDidShow
3) UIKeyboardWillHide
4) UIKeyboardDidHide

You need to register keyboard observer:

NotificationCenter.default.addObserver(self, selector: #selector(keyboardShowNotification), name:NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardHideNotification), name:NSNotification.Name.UIKeyboardWillHide, object: nil)

Here is method observer method:

func keyboardShowNotification(notification:NSNotification){

    var userInfo = notification.userInfo!
    var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
    keyboardFrame = self.view.convert(keyboardFrame, from: nil)

    var contentInset:UIEdgeInsets = YOUR_SCROLLVIEW_OBJ.contentInset
    contentInset.bottom = keyboardFrame.size.height
    YOUR_SCROLLVIEW_OBJ.contentInset = contentInset
}

func keyboardHideNotification(notification:NSNotification){
    let contentInset:UIEdgeInsets = UIEdgeInsets.zero
    YOUR_SCROLLVIEW_OBJ = contentInset
}

Another best key to handle keyboard is IQKeyboardManager. You just have to add them to your application and it will handle everything.


问:
ggplot, bar chart - issue calculating proportions with 2 variables

Suppose I have the below data. I want to create a bar plot, which shows the proportion that said '1' in winter, and 1 in 'spring', and then '2' in Winter and '2' in spring. data example.

So:

x% said 1 in Winter
x% said 1 in Spring

x% said 2 in Winter
x% said 2 in Spring

The chart I have so far is here chart example.

The issue with this is that I don't want all the bars to add up to 100. I want the red (spring bars) to add to 100%, and the green (winter) bars to add to 100.

So instead of the proportion being based on winter and spring combined, winter and spring proportions should be calculated seperately, but appear on the same chart.

Here is my code so far:

```<code>ggplot(data = a, aes(x = Answer, y = (..count..)/sum(..count..))) +
geom_bar(aes(fill = season), position = "dodge") +
theme_minimal() +
scale_y_continuous(labels=scales::percent,limits= c(0, 1))+
labs (x="%")
</code>```

The issue is that:

The two green bars should add to 100%
The two red bars should add up to 100%

Thanks  in advance!

答:
My approach would be to calculate the frequencies direct in the data.frame and then plot:

```<code>### example data
a <- data.frame(
  Answer = c(1,2,2,1,1,2,1,2,1,2,2,2,1),
  season = c("Winter", "Spring", "Spring", "Winter", "Spring", "Winter",
          "Spring", "Spring", "Spring", "Spring", "Spring", "Spring", "Winter")
)

library(tidyverse)

a <- a %>% group_by(season, Answer) %>%
  summarise(n = n()) %>%
  mutate(freq = n/sum(n))

ggplot(data = a, aes(x = Answer, y = freq)) +
  geom_bar(aes(fill = season),stat = "identity", position = "dodge") +
  theme_minimal() +
  scale_y_continuous(labels=scales::percent,limits= c(0, 1))+
  labs (y="%")
</code>```

Body:
Suppose I have the below data. I want to create a bar plot, which shows the proportion that said '1' in winter, and 1 in 'spring', and then '2' in Winter and '2' in spring. data example.

So:

x% said 1 in Winter
x% said 1 in Spring

x% said 2 in Winter
x% said 2 in Spring

The chart I have so far is here chart example.

The issue with this is that I don't want all the bars to add up to 100. I want the red (spring bars) to add to 100%, and the green (winter) bars to add to 100.

So instead of the proportion being based on winter and spring combined, winter and spring proportions should be calculated seperately, but appear on the same chart.

Here is my code so far:

ggplot(data = a, aes(x = Answer, y = (..count..)/sum(..count..))) +
geom_bar(aes(fill = season), position = "dodge") +
theme_minimal() +
scale_y_continuous(labels=scales::percent,limits= c(0, 1))+
labs (x="%")

The issue is that:

The two green bars should add to 100%
The two red bars should add up to 100%

Thanks  in advance!

Body:
My approach would be to calculate the frequencies direct in the data.frame and then plot:

### example data
a <- data.frame(
  Answer = c(1,2,2,1,1,2,1,2,1,2,2,2,1),
  season = c("Winter", "Spring", "Spring", "Winter", "Spring", "Winter",
          "Spring", "Spring", "Spring", "Spring", "Spring", "Spring", "Winter")
)

library(tidyverse)

a <- a %>% group_by(season, Answer) %>%
  summarise(n = n()) %>%
  mutate(freq = n/sum(n))

ggplot(data = a, aes(x = Answer, y = freq)) +
  geom_bar(aes(fill = season),stat = "identity", position = "dodge") +
  theme_minimal() +
  scale_y_continuous(labels=scales::percent,limits= c(0, 1))+
  labs (y="%")


问:
Dynamic ID - selenium, python. How to match start with and contains?
I've got id="phone_123456_option". There's no fully static part in code to find the element in other way. I can't also use only start-with, for sure I need also refer to option. So I guess I need to match start-with and contains (or ends-with?) in one line of code using xpath. Does anybody know how to do it properly?

In python and selenium now I can use:

```<code>driver.find_element_by_id("phone_123456_option").click()
</code>```

I need to create a python, not xml, xpath:
//*[@id="phone_123456_option"] - How to properly remove dynamic number and refer to phone and option?

答:
The simplest way to do this:</p>

```<code>driver.find_element_by_xpath("//div[starts-with(@id, 'phone') and contains(@id, 'option')]").click()
</code>```

Body:
I've got id="phone_123456_option". There's no fully static part in code to find the element in other way. I can't also use only start-with, for sure I need also refer to option. So I guess I need to match start-with and contains (or ends-with?) in one line of code using xpath. Does anybody know how to do it properly?

In python and selenium now I can use:

driver.find_element_by_id("phone_123456_option").click()

I need to create a python, not xml, xpath:
//*[@id="phone_123456_option"] - How to properly remove dynamic number and refer to phone and option?

Body:
The simplest way to do this:

driver.find_element_by_xpath("//div[starts-with(@id, 'phone') and contains(@id, 'option')]").click()


问:
Excel Function checking street name in full addresses
I have two sheets in excel, on containing full addresses and one containing street names. I need to create a lookup function that checks each full address to see if it contains one of the street names in the other sheet.

Normally i would use this =VLOOKUP or =Countif function to return a value if the cell exist in the lookup matrix, but they both check the whole content of the cell. while i only need to see if it contains a specific part.

Example cells would be.

Full Adresse Sheet1 A1:

Alpha street 34, fictional city Zip230

Lookup Sheet2 columns A:

Alpha Street

Beta Street

...

trying to create a function that check if any string in Column A Sheet2 exisit inside the string in Sheet1 A1. Even better if the function is not case sensitive.

答:
If found this stackoverflow question that might be helpful:

Excel: Search for a list of strings within a particular string using array formulas?

Tweaking the array formula provided in the answer, I think you could try something like this:

```<code>=IFERROR(INDEX(streetLookup!$B$1:$B$7,MAX(IF(ISERROR(FIND(streetLookup!$B$1:$B$7,A1)),-1,1)*(ROW(streetLookup!$B$1:$B$7)-ROW(streetLookup!$B$1)+1))),"")
</code>```

A few notes:

The formula assumes the addresses are in column A and that there's a sheet named "streetLookup".

For the lookup sheet I put the street names in column B only so that it's a little more clear in the above formula what sheet each range refers to.

I don't have a ton of experience with array formulas, but after playing around with this I noticed that I had to use a defined range (i.e. couldn't just use the entire column). I think it's because the formula will not work as expected if there are any empty cells within the range.

Since this is an array formula, remember to use ctrl+shift+enter

Body:
If found this stackoverflow question that might be helpful:

Excel: Search for a list of strings within a particular string using array formulas?

Tweaking the array formula provided in the answer, I think you could try something like this:

=IFERROR(INDEX(streetLookup!$B$1:$B$7,MAX(IF(ISERROR(FIND(streetLookup!$B$1:$B$7,A1)),-1,1)*(ROW(streetLookup!$B$1:$B$7)-ROW(streetLookup!$B$1)+1))),"")

A few notes:

The formula assumes the addresses are in column A and that there's a sheet named "streetLookup".

For the lookup sheet I put the street names in column B only so that it's a little more clear in the above formula what sheet each range refers to.

I don't have a ton of experience with array formulas, but after playing around with this I noticed that I had to use a defined range (i.e. couldn't just use the entire column). I think it's because the formula will not work as expected if there are any empty cells within the range.

Since this is an array formula, remember to use ctrl+shift+enter


问:
How to always run some ansible roles after previous failures?
I have a set of playbooks that do look like

```<code>- name: Run test
  hosts: tester
  roles:
    - { role: setup_repos }
    - { role: setup_environment }
    - { role: install_packages }
    - { role: run_tests }
    - { role: collect_logs }
</code>```

The current problem is that all over the first 4 roles we have ignore_errors: true which is not a good practice as it makes very hard to read the output and to debug.

The only reason why ignore_errors was abused was because we wanted to be able to perform the collect_logs at the end, regardless the outcome.

How can we refactor this in order to remove the ignore_errors and have a more of a fail-fast strategy.

Please note that we have lots of playbooks calling collect_logs role, so "moving code inside playbook" is not really a way to reuse it.

答: On ansible 2.4 or newer one should replace role: block with tasks like role_include or role_import, which gives you the ability to use normal logic used by tasks. You could use handlers, ignore_errors, and so on.

Body:
I have a set of playbooks that do look like

- name: Run test
  hosts: tester
  roles:
    - { role: setup_repos }
    - { role: setup_environment }
    - { role: install_packages }
    - { role: run_tests }
    - { role: collect_logs }

The current problem is that all over the first 4 roles we have ignore_errors: true which is not a good practice as it makes very hard to read the output and to debug.

The only reason why ignore_errors was abused was because we wanted to be able to perform the collect_logs at the end, regardless the outcome.

How can we refactor this in order to remove the ignore_errors and have a more of a fail-fast strategy.

Please note that we have lots of playbooks calling collect_logs role, so "moving code inside playbook" is not really a way to reuse it.


问:
connect my noSQL(mongoDB) database with my nodeJS project. But it is not working fine
I am trying to connect my nodejs with mongoDB but it is not working fine as the following result below.
**

```<code>(node:11776) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your o
wn promise library instead: http://mongoosejs.com/docs/promises.html

{ MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0
.1:27017]
    at Pool.<anonymous> (D:\KIT\YEAR II\Project\Nodejs\Vidjot\node_modules\mongodb-core\lib\topologies\server.js:336:3
5)
    at emitOne (events.js:116:13)
    at Pool.emit (events.js:211:7)
    at Connection.<anonymous> (D:\KIT\YEAR II\Project\Nodejs\Vidjot\node_modules\mongodb-core\lib\connection\pool.js:2
80:12)
    at Object.onceWrapper (events.js:317:30)
    at emitTwo (events.js:126:13)
    at Connection.emit (events.js:214:7)
    at Socket.<anonymous> (D:\KIT\YEAR II\Project\Nodejs\Vidjot\node_modules\mongodb-core\lib\connection\connection.js
:187:49)
    at Object.onceWrapper (events.js:315:30)
    at emitOne (events.js:116:13)
    at Socket.emit (events.js:211:7)
    at emitErrorNT (internal/streams/destroy.js:64:8)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)
  name: 'MongoError',
  message: 'failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1
:27017]' }
</code>```

**
Here is my source code

答:
Make sure your mongo server is running @ localhost:27017 and you have directories created to store data.
 start using this command:</p>

```<code>>mongod --port 27017 --dbpath c:\data\db
</code>```

Body:
I am trying to connect my nodejs with mongoDB but it is not working fine as the following result below.
**

(node:11776) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your o
wn promise library instead: http://mongoosejs.com/docs/promises.html

{ MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0
.1:27017]
    at Pool.<anonymous> (D:\KIT\YEAR II\Project\Nodejs\Vidjot\node_modules\mongodb-core\lib\topologies\server.js:336:3
5)
    at emitOne (events.js:116:13)
    at Pool.emit (events.js:211:7)
    at Connection.<anonymous> (D:\KIT\YEAR II\Project\Nodejs\Vidjot\node_modules\mongodb-core\lib\connection\pool.js:2
80:12)
    at Object.onceWrapper (events.js:317:30)
    at emitTwo (events.js:126:13)
    at Connection.emit (events.js:214:7)
    at Socket.<anonymous> (D:\KIT\YEAR II\Project\Nodejs\Vidjot\node_modules\mongodb-core\lib\connection\connection.js
:187:49)
    at Object.onceWrapper (events.js:315:30)
    at emitOne (events.js:116:13)
    at Socket.emit (events.js:211:7)
    at emitErrorNT (internal/streams/destroy.js:64:8)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)
  name: 'MongoError',
  message: 'failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1
:27017]' }

**
Here is my source code

Body:
Make sure your mongo server is running @ localhost:27017 and you have directories created to store data.
 start using this command:

>mongod --port 27017 --dbpath c:\data\db


问:
Fieldset and disabling all child inputs - Work around for IE
I have a fieldset that has a ui-view under it.

Each view had lots of fields(a field is a directive that wraps an input) under it.

It looks something like this:

```<code><fieldset ng-disabled='myCondition'>
   <div ui-view></div> // this changes with lot's of fields that look like <div field='text-box'></div>
</fieldset>
</code>```

Now, this worked great, the fields get disabled on all browsers except IE.

I've done some google and seen that ie doesn't support fieldset + disabled and I'm looking for a quick workaround.

I've tried some things that were close but not perfect and I assume I'm not the first one that needs a solution(even though I didn't find anything on google).

答:
This is a fix to disable fieldsets in IE11:
https://connect.microsoft.com/IE/feedbackdetail/view/962368/can-still-edit-input-type-text-within-fieldset-disabled

Detect IE:
Detecting IE11 using CSS Capability/Feature Detection

```<code>_:-ms-lang(x), fieldset[disabled].ie10up
        {
            pointer-events: none;
            opacity: .65;
        }
</code>```

Body:
I have a fieldset that has a ui-view under it.

Each view had lots of fields(a field is a directive that wraps an input) under it.

It looks something like this:

<fieldset ng-disabled='myCondition'>

 // this changes with lot's of fields that look like

</fieldset>

Now, this worked great, the fields get disabled on all browsers except IE.

I've done some google and seen that ie doesn't support fieldset + disabled and I'm looking for a quick workaround.

I've tried some things that were close but not perfect and I assume I'm not the first one that needs a solution(even though I didn't find anything on google).

Body:
This is a fix to disable fieldsets in IE11:
https://connect.microsoft.com/IE/feedbackdetail/view/962368/can-still-edit-input-type-text-within-fieldset-disabled

Detect IE:
Detecting IE11 using CSS Capability/Feature Detection

_:-ms-lang(x), fieldset[disabled].ie10up
        {
            pointer-events: none;
            opacity: .65;
        }


问:
WCF with discovery fails with socket not valid in its context on XP?
I'm trying to use WCF's discovery mechanism in .NET 4.0.  It works on Windows 7 but fails on an XP machine with a socket exception saying that "the requested address is not valid in its context" (the endpoint is soap.udp://239.255.255.250:3702).

Is the Windows 7 vs XP a red herring?  netstat doesn't seem to show any conflicts.  What am I missing here?

I've created a simplified test service that shows the problem using the following config:

```<code><configuration>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata/>
          <serviceDiscovery />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior>
          <endpointDiscovery />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <services>
      <service name="HelloWorldService">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost/Demo"/>
          </baseAddresses>
        </host>
        <endpoint kind="mexEndpoint" />
        <endpoint kind="udpDiscoveryEndpoint" />
        <endpoint contract="Test.IHelloWorld"
                  address="/Hello"
                  binding="basicHttpBinding" />
      </service>
    </services>
  </system.serviceModel>
</configuration>
</code>```

答:
There is an issue logged on Microsoft Connect. Unfortunately there is currently no workaround and Microsoft response is

The exception you are mentioning is
  normally hit when trying to bind the
  socket to an IP address that isn't
  valid. Can you please check this and
  if possible try on a machine with a
  different OS. There are currently no
  known limitations of the WCF Discovery
  feature on XP.

Body:
I'm trying to use WCF's discovery mechanism in .NET 4.0.  It works on Windows 7 but fails on an XP machine with a socket exception saying that "the requested address is not valid in its context" (the endpoint is soap.udp://239.255.255.250:3702).

Is the Windows 7 vs XP a red herring?  netstat doesn't seem to show any conflicts.  What am I missing here?

I've created a simplified test service that shows the problem using the following config:

<configuration>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata/>
          <serviceDiscovery />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior>
          <endpointDiscovery />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <services>
      <service name="HelloWorldService">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost/Demo"/>
          </baseAddresses>
        </host>
        <endpoint kind="mexEndpoint" />
        <endpoint kind="udpDiscoveryEndpoint" />
        <endpoint contract="Test.IHelloWorld"
                  address="/Hello"
                  binding="basicHttpBinding" />
      </service>
    </services>
  </system.serviceModel>
</configuration>


问:
Image hover overlay: handle the opacity of nested element
I have this situation which doesn't work as desired:

.work-container {
  width: 100%;
  position: relative;
}

img {
  width: 100%;
  height: auto;
}

.overlay-info {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  opacity: 0;
  transition: .5s ease;
  background: #eee;
}

.overlay-info:hover {
  opacity: .75;
}

.go-to {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="work-container">
  <img src="http://lorempixel.com/320/240" class="img-responsive">
  <div class="overlay-info">
    <div class="go-to">
      <button type="button" class="btn btn-secondary">Secondary</button>
    </div>
  </div>
</div></code>```

When hovering over the image, the .overlay-info div gets the opacity of .75 (it starts at 0), but I'd like for the button to have the opacity of 1. Any ideas?

答: you should use rgba instead of opacity, if you use opacity, children of the element which set opacity will inherit</p>

Body:
I have this situation which doesn't work as desired:

.work-container {
  width: 100%;
  position: relative;
}

img {
  width: 100%;
  height: auto;
}

.overlay-info {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  opacity: 0;
  transition: .5s ease;
  background: #eee;
}

.overlay-info:hover {
  opacity: .75;
}

.go-to {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
}

      <button type="button" class="btn btn-secondary">Secondary</button>

When hovering over the image, the .overlay-info div gets the opacity of .75 (it starts at 0), but I'd like for the button to have the opacity of 1. Any ideas?


问:
Redirect to a default page, if any get request page takes too long to reply
I was wondering if I can redirect any request coming to server to a default page, if my server for some reason has not been able to respond.

For example, for this route:

```<code>app.post('/login',ensureAuthenticated,(req,res)=>{
    // My route logic
});
</code>```

some unexpected error occurred (database unable to connect), I could send them to the my home page.

答:
```<code>app.post('/login',ensureAuthenticated,(req,res)=>{
    // My route logic
    setTimeout(() => {
      res.redirect('/default-page')
    }, 2000)
});
</code>```

Using the setTimeout function, if the API didn't respond in 2 seconds res.redirect with execute and redirect your page to a default url.

Body:
I was wondering if I can redirect any request coming to server to a default page, if my server for some reason has not been able to respond.

For example, for this route:

app.post('/login',ensureAuthenticated,(req,res)=>{
    // My route logic
});

some unexpected error occurred (database unable to connect), I could send them to the my home page.

Body:
app.post('/login',ensureAuthenticated,(req,res)=>{
    // My route logic
    setTimeout(() => {
      res.redirect('/default-page')
    }, 2000)
});

Using the setTimeout function, if the API didn't respond in 2 seconds res.redirect with execute and redirect your page to a default url.


问:
Can we achieve Consul loadbalancing without haproxy?
Can we achieve the round-robin in consul? Below I have done some attempts to achieve but didn't succeed.

When I try with consul load balancing, by launching 2 container and registering with same name in consul. After this I did curl to DNS provided by consul (tomcat.test.service.consul) and its getting load balancing.

But when I hit DNS in browser it is not working. If there is only one container then it works, as soon as I launch new container (load balance) it's returning a blank page.

Please let me know if I am going wrong somewhere or if I use a wrong configuration?

答:
I find the solution here with iptables

https://tech.iheart.com/load-balancing-services-using-consul-and-iptables-204cde23b072