问:
can't use local json file from my project in $http.get() function
I have this code but it keeps giving me an error

```<code>app.controller('myController',["$scope", '$location', '$http', '$rootScope',function($scope, $location, $http, $rootScope){
    $scope.gridOptions1 = {
    paginationPageSize: 15,
    columnDefs: [
      { name: 'الاسم' },
      { name: 'الجنس' },
      { name: 'الشركة' }
    ]
  };
  $http.get('/data/mydata.json')
  .then(function (data) {
    $scope.gridOptions1.data = data;
  })
</code>```

and this here is my json file:

```<code>[
{
    "الاسم": "سمير",
    "العائلة": "سمراوي",
    "العمر": "32",
    "الجنس": "ذكر"
},
{
    "الاسم": "حمدان",
    "العائلة": "ابو حميد",
    "العمر": "20",
    "الجنس": "ذكر"
},
{
    "الاسم": "خالد",
    "العائلة": "خلدون",
    "العمر": "15",
    "الجنس": "ذكر"
},{

    "الاسم": "سمير",
    "العائلة": "سمراوي",
    "العمر": "32",
    "الجنس": "ذكر"
},
{
    "الاسم": "حمدان",
    "العائلة": "ابو حميد",
    "العمر": "20",
    "الجنس": "ذكر"
},
{
    "الاسم": "خالد",
    "العائلة": "خلدون",
    "العمر": "15",
    "الجنس": "ذكر"
},
{
    "الاسم": "سمير",
    "العائلة": "سمراوي",
    "العمر": "32",
    "الجنس": "ذكر"
},
{
    "الاسم": "حمدان",
    "العائلة": "ابو حميد",
    "العمر": "20",
    "الجنس": "ذكر"
},
{
    "الاسم": "خالد",
    "العائلة": "خلدون",
    "العمر": "15",
    "الجنس": "ذكر"
},
{
    "الاسم": "سمير",
    "العائلة": "سمراوي",
    "العمر": "32",
    "الجنس": "ذكر"
},
{
    "الاسم": "حمدان",
    "العائلة": "ابو حميد",
    "العمر": "20",
    "الجنس": "ذكر"
},
{
    "الاسم": "خالد",
    "العائلة": "خلدون",
    "العمر": "15",
    "الجنس": "ذكر"
},
{
    "الاسم": "سمير",
    "العائلة": "سمراوي",
    "العمر": "32",
    "الجنس": "ذكر"
},
{
    "الاسم": "حمدان",
    "العائلة": "ابو حميد",
    "العمر": "20",
    "الجنس": "ذكر"
},
{
    "الاسم": "خالد",
    "العائلة": "خلدون",
    "العمر": "15",
    "الجنس": "ذكر"
},
{
    "الاسم": "سمير",
    "العائلة": "سمراوي",
    "العمر": "32",
    "الجنس": "ذكر"
},
{
    "الاسم": "حمدان",
    "العائلة": "ابو حميد",
    "العمر": "20",
    "الجنس": "ذكر"
},
{
    "الاسم": "خالد",
    "العائلة": "خلدون",
    "العمر": "15",
    "الجنس": "ذكر"
}
];
</code>```

the file is called mydata.json.
'pardon the language difference'.
What I think my problem is is that I'm not using $http.get() function the right way. I'm not sure weather I can use $http.get() for local urls.
Please help and thank you in advance

答:
you can find your required object in data.data
try using error call back like this to catch the error

```<code>$http.get('/mydata.json')
  .then(function (data) {
    $scope.gridOptions1.data = data;
  },function(err){
    console.log(err);
});
</code>```

Body:
I have this code but it keeps giving me an error

app.controller('myController',["$scope", '$location', '$http', '$rootScope',function($scope, $location, $http, $rootScope){
    $scope.gridOptions1 = {
    paginationPageSize: 15,
    columnDefs: [
      { name: 'الاسم' },
      { name: 'الجنس' },
      { name: 'الشركة' }
    ]
  };
  $http.get('/data/mydata.json')
  .then(function (data) {
    $scope.gridOptions1.data = data;
  })

and this here is my json file:

[
{
    "الاسم": "سمير",
    "العائلة": "سمراوي",
    "العمر": "32",
    "الجنس": "ذكر"
},
{
    "الاسم": "حمدان",
    "العائلة": "ابو حميد",
    "العمر": "20",
    "الجنس": "ذكر"
},
{
    "الاسم": "خالد",
    "العائلة": "خلدون",
    "العمر": "15",
    "الجنس": "ذكر"
},{

    "الاسم": "سمير",
    "العائلة": "سمراوي",
    "العمر": "32",
    "الجنس": "ذكر"
},
{
    "الاسم": "حمدان",
    "العائلة": "ابو حميد",
    "العمر": "20",
    "الجنس": "ذكر"
},
{
    "الاسم": "خالد",
    "العائلة": "خلدون",
    "العمر": "15",
    "الجنس": "ذكر"
},
{
    "الاسم": "سمير",
    "العائلة": "سمراوي",
    "العمر": "32",
    "الجنس": "ذكر"
},
{
    "الاسم": "حمدان",
    "العائلة": "ابو حميد",
    "العمر": "20",
    "الجنس": "ذكر"
},
{
    "الاسم": "خالد",
    "العائلة": "خلدون",
    "العمر": "15",
    "الجنس": "ذكر"
},
{
    "الاسم": "سمير",
    "العائلة": "سمراوي",
    "العمر": "32",
    "الجنس": "ذكر"
},
{
    "الاسم": "حمدان",
    "العائلة": "ابو حميد",
    "العمر": "20",
    "الجنس": "ذكر"
},
{
    "الاسم": "خالد",
    "العائلة": "خلدون",
    "العمر": "15",
    "الجنس": "ذكر"
},
{
    "الاسم": "سمير",
    "العائلة": "سمراوي",
    "العمر": "32",
    "الجنس": "ذكر"
},
{
    "الاسم": "حمدان",
    "العائلة": "ابو حميد",
    "العمر": "20",
    "الجنس": "ذكر"
},
{
    "الاسم": "خالد",
    "العائلة": "خلدون",
    "العمر": "15",
    "الجنس": "ذكر"
},
{
    "الاسم": "سمير",
    "العائلة": "سمراوي",
    "العمر": "32",
    "الجنس": "ذكر"
},
{
    "الاسم": "حمدان",
    "العائلة": "ابو حميد",
    "العمر": "20",
    "الجنس": "ذكر"
},
{
    "الاسم": "خالد",
    "العائلة": "خلدون",
    "العمر": "15",
    "الجنس": "ذكر"
}
];

the file is called mydata.json.
'pardon the language difference'.
What I think my problem is is that I'm not using $http.get() function the right way. I'm not sure weather I can use $http.get() for local urls.
Please help and thank you in advance

Body:
you can find your required object in data.data
try using error call back like this to catch the error

$http.get('/mydata.json')
  .then(function (data) {
    $scope.gridOptions1.data = data;
  },function(err){
    console.log(err);
});


来源: stackexchange

问:
how to redirect to another page, that generates a gridview, after clicking a button in the first page
i have some different buttons in a page after clicking them i want them to redirect me to a page that has a gridview , but for each button it gives a different gridview which are generated by datatables . may you help to find ,how can i do that in asp.net, vb ??
i did two pages at the gridview page i made methods that are binding different gridviews for each button , and in the first page where i have the button click events i did the redirecting to this gridview page and called the corresponding methods. it redirects me but doen't give me any gridview at all :( </p>

答:
You can redirect by using

```<code> Response.Redirect("GridView.aspx")
</code>```

At the same time you can use only one aspx by using session

```<code>Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

Session.Add("CheckButton", Button1Clicked)
Response.Redirect("GridView.aspx")

End Sub

Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

Session.Add("CheckButton", Button2Clicked)
Response.Redirect("GridView.aspx")

End Sub
</code>```

After that at your GridView.aspx on your pageload

```<code>    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    Dim CheckButton As String = Session("CheckButton")

    Dim query As String

    If (CheckButton = "Button1Clicked") Then

    query = "SELECT * FROM Table1"

    Else If (CheckButton = "Button2Clicked") Then

    query = "SELECT * FROM Table2"

    Else

    Response.Write("<script>alert('Error!')</script>")

    End If

    SqlDataSource1.SelectCommand = query
    SqlDataSource1.DataBind()

    End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can redirect by using

 Response.Redirect("GridView.aspx")

At the same time you can use only one aspx by using session

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

Session.Add("CheckButton", Button1Clicked)
Response.Redirect("GridView.aspx")

End Sub

Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

Session.Add("CheckButton", Button2Clicked)
Response.Redirect("GridView.aspx")

End Sub

After that at your GridView.aspx on your pageload

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    Dim CheckButton As String = Session("CheckButton")

    Dim query As String

    If (CheckButton = "Button1Clicked") Then

    query = "SELECT * FROM Table1"

    Else If (CheckButton = "Button2Clicked") Then

    query = "SELECT * FROM Table2"

    Else

    Response.Write("<script>alert('Error!')</script>")

    End If

    SqlDataSource1.SelectCommand = query
    SqlDataSource1.DataBind()

    End Sub


问:
React inherit html from super class
I am building a series of gadgets and want to have a super class where some general gadget UI is defined such as a header bar container min/max/close button and maybe a footer and only the content area of the gadgets are defined in subclasses.

Any suggestions?

thanks

答:
I don't think you need to use inheritance here at all. There's a good discussion on the React Docs about Composition vs Inheritance.

It sounds to me like you should have a 'parent' component that defines the header/footer etc, and props.children to render the content. For example:

html

```<code><Gadget>
  <GadgetOne></GadgetOne>
</Gadget>
</code>```

js

```<code>function Gadget(props) {
  return (<div><header />{props.children}<footer /></div>);
}

function GadgetOne(props) {
  return (<div>...</div>);
</code>```

Title: React inherit html from super class

Body:
I don't think you need to use inheritance here at all. There's a good discussion on the React Docs about Composition vs Inheritance.

It sounds to me like you should have a 'parent' component that defines the header/footer etc, and props.children to render the content. For example:

html

<Gadget>
  <GadgetOne></GadgetOne>
</Gadget>

js

function Gadget(props) {
  return (<div><header />{props.children}<footer /></div>);
}

function GadgetOne(props) {
  return (<div>...</div>);


问:
Hide divs on click - multiple boxes
I have a bit long info submission form. I have an option that someone click "add another", there is a notification box display with text like "Success!" like that with close button. Please check this image.

Therefore I have three "add another" buttons and three success alerts. When someone click close, that alert message needs to be disappear.

The problem

I used javascript for that success box. It does these things.

Click "Add another" button, appears success box.
 Click close button on
  success box, box disappears.

Here is my code.

document.querySelector(".add-box").addEventListener("click", function() {
  document.querySelector(".add-box-wrap").style.display = "inline-block";
});

document.querySelector(".add-box1").addEventListener("click", function() {
  document.querySelector(".add-box-wrap1").style.display = "inline-block";
});

document.querySelector(".add-box2").addEventListener("click", function() {
  document.querySelector(".add-box-wrap2").style.display = "inline-block";
});

$(".claim-btn-close").click(function() {
  $(".add-box-wrap").hide();
});

$(".claim-btn-close1").click(function() {
  $(".add-box-wrap1").hide();
});

$(".claim-btn-close2").click(function() {
  $(".add-box-wrap2").hide();
});

function hide(target) {
  document.getElementsByClassName(target).style.display = 'none';
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--Success form-->
<div class="add-box-wrap">
  <div class="claim-btn-close" onclick="hide('.claim-btn-close')">
    <i class="fa fa-times" aria-hidden="true"></i>
  </div>
  Success!
</div>

<!--Add another button -->
<div class="col-lg-10 col-md-10 col-sm-12 no-padding">
  Add another<i class="fa fa-plus"></i>
</div></code>```

See.. there is a major problem with code repeating. (I didn't repeat html codes, just post here one example) I would like to know the best practice to achieve things like this.

答:
You can use DOM relationship to target the desired element. Bind event handlers using a common class then use .closest() to traverse up desired element.

```<code>$(".claim-btn-close").click(function(){
    $(this).closest(".add-box-wrap").hide();
});
</code>```

If element are dynamically generate use Event Delegation approach.

```<code>$(staticParentElemet).on('click',".claim-btn-close",function(){
    $(this).closest(".add-box-wrap").hide();
});
</code>```

Title: Hide divs on click - multiple boxes

Body:
I have a bit long info submission form. I have an option that someone click "add another", there is a notification box display with text like "Success!" like that with close button. Please check this image.

Therefore I have three "add another" buttons and three success alerts. When someone click close, that alert message needs to be disappear.

The problem

I used javascript for that success box. It does these things.

Click "Add another" button, appears success box.
 Click close button on
  success box, box disappears.

Here is my code.

document.querySelector(".add-box").addEventListener("click", function() {
  document.querySelector(".add-box-wrap").style.display = "inline-block";
});

document.querySelector(".add-box1").addEventListener("click", function() {
  document.querySelector(".add-box-wrap1").style.display = "inline-block";
});

document.querySelector(".add-box2").addEventListener("click", function() {
  document.querySelector(".add-box-wrap2").style.display = "inline-block";
});

$(".claim-btn-close").click(function() {
  $(".add-box-wrap").hide();
});

$(".claim-btn-close1").click(function() {
  $(".add-box-wrap1").hide();
});

$(".claim-btn-close2").click(function() {
  $(".add-box-wrap2").hide();
});

function hide(target) {
  document.getElementsByClassName(target).style.display = 'none';
};

  Success!

  Add another

See.. there is a major problem with code repeating. (I didn't repeat html codes, just post here one example) I would like to know the best practice to achieve things like this.

Body:
You can use DOM relationship to target the desired element. Bind event handlers using a common class then use .closest() to traverse up desired element.

$(".claim-btn-close").click(function(){
    $(this).closest(".add-box-wrap").hide();
});

If element are dynamically generate use Event Delegation approach.

$(staticParentElemet).on('click',".claim-btn-close",function(){
    $(this).closest(".add-box-wrap").hide();
});


问:
Why does redeclaring a function identifier within a try block throw a SyntaxError?
The following lines of JavaScript

```<code>try {
    function _free() {}
    var _free = 1;
} finally { }
</code>```

result in the following error:

```<code> Uncaught SyntaxError: Identifier '_free' has already been declared
</code>```

However, the following two blocks of JavaScript code don't:

Without the try block scope:

```<code>function _free() {}
var _free = 1;
</code>```

Within a function scope:

```<code>function a() {
    function _free() {}
    var _free = 1;
}
</code>```

But why?

(Testing environment: Chromium 61.0.3126.0)

答:
To expand on Bergis answer, there is a difference in how the code is interpreted in ES5 and ES6 since block-scoped function declarations were added.

Input:

```<code>function test() {
    try {
        function _free() { }
        var _free = 1;
    } finally { }
}
</code>```

Since ES5 does not support block-level functions, _free is hoisted to the parent function:

```<code>function test() {
    var _free = function _free() { }
    try {
        var _free = 1;
    } finally { }
}
</code>```

In ES6, the function is declared at block-level, and semantically equal to a let/const declaration:

```<code>function test() {
    try {
        let _free = function _free() { }
        var _free = 1;
    } finally { }
}
</code>```

This throws an error because var _free tries to declare a variable which is already declared.
For example, this throws in ES6 as well:

```<code>let _free;
var _free = 1;    // SyntaxError: Indentifier '_free' has already been declared
</code>```

While this is fine:

```<code>var _free;
var _free = 1;    // No SyntaxError
</code>```

Setting the value of the already declared identifier is fine:

```<code>let _free;
_free = 1;
</code>```

Therefore, to set the declared identifier _free to 1, you need to skip the second declaration:

```<code>try {
    function _free() { }
    _free = 1;
} finally { }
</code>```

Body:
The following lines of JavaScript

try {
    function _free() {}
    var _free = 1;
} finally { }

result in the following error:

 Uncaught SyntaxError: Identifier '_free' has already been declared

However, the following two blocks of JavaScript code don't:

Without the try block scope:

function _free() {}
var _free = 1;

Within a function scope:

function a() {
    function _free() {}
    var _free = 1;
}

But why?

(Testing environment: Chromium 61.0.3126.0)

Body:
To expand on Bergis answer, there is a difference in how the code is interpreted in ES5 and ES6 since block-scoped function declarations were added.

Input:

function test() {
    try {
        function _free() { }
        var _free = 1;
    } finally { }
}

Since ES5 does not support block-level functions, _free is hoisted to the parent function:

function test() {
    var _free = function _free() { }
    try {
        var _free = 1;
    } finally { }
}

In ES6, the function is declared at block-level, and semantically equal to a let/const declaration:

function test() {
    try {
        let _free = function _free() { }
        var _free = 1;
    } finally { }
}

This throws an error because var _free tries to declare a variable which is already declared.
For example, this throws in ES6 as well:

let _free;
var _free = 1;    // SyntaxError: Indentifier '_free' has already been declared

While this is fine:

var _free;
var _free = 1;    // No SyntaxError

Setting the value of the already declared identifier is fine:

let _free;
_free = 1;

Therefore, to set the declared identifier _free to 1, you need to skip the second declaration:

try {
    function _free() { }
    _free = 1;
} finally { }


问:
Objective -C Call back doesnot working with an unfortunate background crash
I'm trying to send a call back listener from a completion block. I initiate callback in custom UIView & completion block executes from parent viewcontroller (where UIView subviewed). Here is the code... (I dont want to use delegate)

Declaration of Call-Back in ViewController.h

```<code>typedef void(^ExportCompletion)(BOOL success, NSURL* url);
@property (nonatomic, copy) ExportCompletion exportBlock;
-(void) exportCompletionBlock:(ExportCompletion)callback;
</code>```

Initialization & Implementation of Call-Back in ViewController.m

```<code>-(void) exportCompletionBlock:(ExportCompletion)callback
{
    if (callback) {
        self.exportBlock = callback;
    }
}
</code>```

Implementation (call) from Completion handler (its also in ViewController.m)

```<code>-(void)blockAlertAppear:(float)progress{
    if(EXPORT_SESSION_COMPLETED!=progress)
        doing something...
    if(EXPORT_SESSION_COMPLETED==progress){
        self.exportBlock(YES, mCompositor.url);
    }
}
</code>```

Call back operation in uicustomview... CustomUIView.m

```<code>-(void) initUIView{
    [(ViewController*)[[self superview] nextResponder] exportCompletionBlock:^(BOOL success, NSURL *url) {
    if (success) {
        doing something...
    }
}];
</code>```

I can use delegate here but I want to use call back. I'm very new with call back. I like to know why I'm having the crash (its from background - so dont get the reason) & how do I optimize the code?

答: Why your last method calls "initUIView" ??? If you init new View , View dont have Superview , before you not added to superview ([viewController.view addsubview:yourView]). I think, if you print  [(ViewController*)[[self superview] nextResponder] in NSLog , you'll see Nil. And it's reason for Crash</p>

Body:
I'm trying to send a call back listener from a completion block. I initiate callback in custom UIView & completion block executes from parent viewcontroller (where UIView subviewed). Here is the code... (I dont want to use delegate)

Declaration of Call-Back in ViewController.h

typedef void(^ExportCompletion)(BOOL success, NSURL* url);
@property (nonatomic, copy) ExportCompletion exportBlock;
-(void) exportCompletionBlock:(ExportCompletion)callback;

Initialization & Implementation of Call-Back in ViewController.m

-(void) exportCompletionBlock:(ExportCompletion)callback
{
    if (callback) {
        self.exportBlock = callback;
    }
}

Implementation (call) from Completion handler (its also in ViewController.m)

-(void)blockAlertAppear:(float)progress{
    if(EXPORT_SESSION_COMPLETED!=progress)
        doing something...
    if(EXPORT_SESSION_COMPLETED==progress){
        self.exportBlock(YES, mCompositor.url);
    }
}

Call back operation in uicustomview... CustomUIView.m

-(void) initUIView{
    [(ViewController*)[[self superview] nextResponder] exportCompletionBlock:^(BOOL success, NSURL *url) {
    if (success) {
        doing something...
    }
}];

I can use delegate here but I want to use call back. I'm very new with call back. I like to know why I'm having the crash (its from background - so dont get the reason) & how do I optimize the code?


问:
How to detect eye blink using Google vision API in android ?
i'm using the vision API for face detection, now i want to implement eye blink but still vision api detect eye blinking in image(photo) of a person(not live).

In addition, I am using a Tracker to keep track of the eye state over time, to detect the sequence of events that indicate a blink of left eye:

left eyes open -> left eyes closed -> left eyes open

The GraphicFaceTracker class is defined as below :

```<code>private class GraphicFaceTracker extends Tracker<Face> {
        private GraphicOverlay mOverlay;
        private FaceGraphic mFaceGraphic;
        private Context context ;

        GraphicFaceTracker(Context context, GraphicOverlay overlay) {
            mOverlay = overlay;
            this.context= context;
            mFaceGraphic = new FaceGraphic(overlay);
        }

        private final float OPEN_THRESHOLD = 0.85f;
        private final float CLOSE_THRESHOLD = 0.4f;

        private int state = 0;

        void blink(float value, final int eyeNo, String whichEye) {
            switch (state) {
                case 0:
                    if (value > OPEN_THRESHOLD) {
                        // Both eyes are initially open
                        state = 1;
                    }
                    break;

                case 1:
                    if (value < CLOSE_THRESHOLD ) {
                        // Both eyes become closed
                        state = 2;
                    }
                    break;

                case 2:
                    if (value > OPEN_THRESHOLD)  {
                        // Both eyes are open again
                        Log.i("BlinkTracker", "blink occurred!");

                        mCameraSource.takePicture(null, new CameraSource.PictureCallback() {
                            @Override
                            public void onPictureTaken(byte[] bytes) {
                                Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                                Log.d("BITMAP", bmp.getWidth() + "x" + bmp.getHeight());
                                System.out.println(bmp.getWidth() + "x" + bmp.getHeight());
                            }
                        });
                        state = 0;
                    }
                    break;
            }

        }

        /**
         * Start tracking the detected face instance within the face overlay.
         */
        @Override
        public void onNewItem(int faceId, Face item) {
            mFaceGraphic.setId(faceId);
        }

        /**
         * Update the position/characteristics of the face within the overlay.
         */
        @Override
        public void onUpdate(FaceDetector.Detections<Face> detectionResults, Face face) {
            mOverlay.add(mFaceGraphic);
            mFaceGraphic.updateFace(face);

            float left = face.getIsLeftEyeOpenProbability();
            float right = face.getIsRightEyeOpenProbability();
            if (left == Face.UNCOMPUTED_PROBABILITY)  {
                // At least one of the eyes was not detected.
                return;
            }
            blink(left,0,"left");

            if(right == Face.UNCOMPUTED_PROBABILITY ){
                return ;
            }
        }
}
</code>```

I have enabled "classifications" in order to have the detector indicate if eyes are open/closed :

```<code>FaceDetector detector = new FaceDetector.Builder(context)
            .setProminentFaceOnly(true) // optimize for single, relatively large face
            .setTrackingEnabled(true) // enable face tracking
            .setClassificationType(/* eyes open and smile */ FaceDetector.ALL_CLASSIFICATIONS)
            .setMode(FaceDetector.FAST_MODE) // for one face this is OK
            .build();
</code>```

The tracker is then added as a processor for receiving face updates over time from the detector. For example, this configuration would be used to track whether the largest face in view has blinked:

```<code>Tracker<Face> tracker = new GraphicFaceTracker(this,mGraphicOverlay);
detector.setProcessor(new LargestFaceFocusingProcessor.Builder(detector, tracker).build());
</code>```

But the above code detects blink in image of a person . But the image of a person cannot blink . How can I detect blink by camera ?

答:
You can pass your detector to camera source and process blink detection from the surface view.</p>

```<code>public class LivelinessScanFragment extends Fragment {

    SurfaceView cameraView;
    CameraSource cameraSource;
    final int RequestCameraPermissionID = 1001;
    FaceDetector detector;

       @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        switch (requestCode) {
            case RequestCameraPermissionID: {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                        return;
                    }
                    try {
                        cameraSource.start(cameraView.getHolder());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public LivelinessScanFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

            // Inflate the layout for this fragment
            View rootView = inflater.inflate(R.layout.fragment_liveliness_scan, container, false);

            cameraView = (SurfaceView)rootView.findViewById(R.id.surface_view);

            detector = new FaceDetector.Builder(getActivity())
                .setProminentFaceOnly(true) // optimize for single, relatively large face
                .setTrackingEnabled(true) // enable face tracking
                .setClassificationType(/* eyes open and smile */ FaceDetector.ALL_CLASSIFICATIONS)
                .setMode(FaceDetector.FAST_MODE) // for one face this is OK
                .build();

            if (!detector.isOperational()) {
                Log.w("MainActivity", "Detector Dependencies are not yet available");
            } else {
                cameraSource = new CameraSource.Builder(Application.getContext(), detector)
                        .setFacing(CameraSource.CAMERA_FACING_FRONT)
                        .setRequestedFps(2.0f)
                        .setRequestedPreviewSize(1280, 1024)
                        .setAutoFocusEnabled(true)
                        .build();

                cameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
                    @Override
                    public void surfaceCreated(SurfaceHolder surfaceHolder) {
                        try {
                            if (ActivityCompat.checkSelfPermission(Application.getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {

                                ActivityCompat.requestPermissions(getActivity(),
                                        new String[]{Manifest.permission.CAMERA}, RequestCameraPermissionID);
                                return;
                            }
                            cameraSource.start(cameraView.getHolder());
                            detector.setProcessor(
                                    new LargestFaceFocusingProcessor(detector, new GraphicFaceTracker()));

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {

                    }

                    @Override
                    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
                        cameraSource.stop();
                    }
                });

            }

            return rootView;
        }

    private class GraphicFaceTracker extends Tracker<Face> {

        private final float OPEN_THRESHOLD = 0.85f;
        private final float CLOSE_THRESHOLD = 0.4f;

        private int state = 0;

        void blink(float value) {
            switch (state) {
                case 0:
                    if (value > OPEN_THRESHOLD) {
                        // Both eyes are initially open
                        state = 1;
                    }
                    break;

                case 1:
                    if (value < CLOSE_THRESHOLD ) {
                        // Both eyes become closed
                        state = 2;
                    }
                    break;

                case 2:
                    if (value > OPEN_THRESHOLD)  {
                        // Both eyes are open again
                        Log.i("BlinkTracker", "blink occurred!");
                        state = 0;

                    }
                    break;
            }

        }

        /**
         * Update the position/characteristics of the face within the overlay.
         */
        @Override
        public void onUpdate(FaceDetector.Detections<Face> detectionResults, Face face) {

            float left = face.getIsLeftEyeOpenProbability();
            float right = face.getIsRightEyeOpenProbability();
            if ((left == Face.UNCOMPUTED_PROBABILITY) ||
                    (right == Face.UNCOMPUTED_PROBABILITY)) {
                // One of the eyes was not detected.
                return;
            }

            float value = Math.min(left, right);
            blink(value);
        }
    }

}
</code>```

Body:
i'm using the vision API for face detection, now i want to implement eye blink but still vision api detect eye blinking in image(photo) of a person(not live).

In addition, I am using a Tracker to keep track of the eye state over time, to detect the sequence of events that indicate a blink of left eye:

left eyes open -> left eyes closed -> left eyes open

The GraphicFaceTracker class is defined as below :

private class GraphicFaceTracker extends Tracker<Face> {
        private GraphicOverlay mOverlay;
        private FaceGraphic mFaceGraphic;
        private Context context ;

        GraphicFaceTracker(Context context, GraphicOverlay overlay) {
            mOverlay = overlay;
            this.context= context;
            mFaceGraphic = new FaceGraphic(overlay);
        }

        private final float OPEN_THRESHOLD = 0.85f;
        private final float CLOSE_THRESHOLD = 0.4f;

        private int state = 0;

        void blink(float value, final int eyeNo, String whichEye) {
            switch (state) {
                case 0:
                    if (value > OPEN_THRESHOLD) {
                        // Both eyes are initially open
                        state = 1;
                    }
                    break;

                case 1:
                    if (value < CLOSE_THRESHOLD ) {
                        // Both eyes become closed
                        state = 2;
                    }
                    break;

                case 2:
                    if (value > OPEN_THRESHOLD)  {
                        // Both eyes are open again
                        Log.i("BlinkTracker", "blink occurred!");

                        mCameraSource.takePicture(null, new CameraSource.PictureCallback() {
                            @Override
                            public void onPictureTaken(byte[] bytes) {
                                Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                                Log.d("BITMAP", bmp.getWidth() + "x" + bmp.getHeight());
                                System.out.println(bmp.getWidth() + "x" + bmp.getHeight());
                            }
                        });
                        state = 0;
                    }
                    break;
            }

        }

        /**
         * Start tracking the detected face instance within the face overlay.
         */
        @Override
        public void onNewItem(int faceId, Face item) {
            mFaceGraphic.setId(faceId);
        }

        /**
         * Update the position/characteristics of the face within the overlay.
         */
        @Override
        public void onUpdate(FaceDetector.Detections<Face> detectionResults, Face face) {
            mOverlay.add(mFaceGraphic);
            mFaceGraphic.updateFace(face);

            float left = face.getIsLeftEyeOpenProbability();
            float right = face.getIsRightEyeOpenProbability();
            if (left == Face.UNCOMPUTED_PROBABILITY)  {
                // At least one of the eyes was not detected.
                return;
            }
            blink(left,0,"left");

            if(right == Face.UNCOMPUTED_PROBABILITY ){
                return ;
            }
        }
}

I have enabled "classifications" in order to have the detector indicate if eyes are open/closed :

FaceDetector detector = new FaceDetector.Builder(context)
            .setProminentFaceOnly(true) // optimize for single, relatively large face
            .setTrackingEnabled(true) // enable face tracking
            .setClassificationType(/* eyes open and smile */ FaceDetector.ALL_CLASSIFICATIONS)
            .setMode(FaceDetector.FAST_MODE) // for one face this is OK
            .build();

The tracker is then added as a processor for receiving face updates over time from the detector. For example, this configuration would be used to track whether the largest face in view has blinked:

Tracker<Face> tracker = new GraphicFaceTracker(this,mGraphicOverlay);
detector.setProcessor(new LargestFaceFocusingProcessor.Builder(detector, tracker).build());

But the above code detects blink in image of a person . But the image of a person cannot blink . How can I detect blink by camera ?

Body:
You can pass your detector to camera source and process blink detection from the surface view.

public class LivelinessScanFragment extends Fragment {

    SurfaceView cameraView;
    CameraSource cameraSource;
    final int RequestCameraPermissionID = 1001;
    FaceDetector detector;

       @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        switch (requestCode) {
            case RequestCameraPermissionID: {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                        return;
                    }
                    try {
                        cameraSource.start(cameraView.getHolder());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public LivelinessScanFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

            // Inflate the layout for this fragment
            View rootView = inflater.inflate(R.layout.fragment_liveliness_scan, container, false);

            cameraView = (SurfaceView)rootView.findViewById(R.id.surface_view);

            detector = new FaceDetector.Builder(getActivity())
                .setProminentFaceOnly(true) // optimize for single, relatively large face
                .setTrackingEnabled(true) // enable face tracking
                .setClassificationType(/* eyes open and smile */ FaceDetector.ALL_CLASSIFICATIONS)
                .setMode(FaceDetector.FAST_MODE) // for one face this is OK
                .build();

            if (!detector.isOperational()) {
                Log.w("MainActivity", "Detector Dependencies are not yet available");
            } else {
                cameraSource = new CameraSource.Builder(Application.getContext(), detector)
                        .setFacing(CameraSource.CAMERA_FACING_FRONT)
                        .setRequestedFps(2.0f)
                        .setRequestedPreviewSize(1280, 1024)
                        .setAutoFocusEnabled(true)
                        .build();

                cameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
                    @Override
                    public void surfaceCreated(SurfaceHolder surfaceHolder) {
                        try {
                            if (ActivityCompat.checkSelfPermission(Application.getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {

                                ActivityCompat.requestPermissions(getActivity(),
                                        new String[]{Manifest.permission.CAMERA}, RequestCameraPermissionID);
                                return;
                            }
                            cameraSource.start(cameraView.getHolder());
                            detector.setProcessor(
                                    new LargestFaceFocusingProcessor(detector, new GraphicFaceTracker()));

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {

                    }

                    @Override
                    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
                        cameraSource.stop();
                    }
                });

            }

            return rootView;
        }

    private class GraphicFaceTracker extends Tracker<Face> {

        private final float OPEN_THRESHOLD = 0.85f;
        private final float CLOSE_THRESHOLD = 0.4f;

        private int state = 0;

        void blink(float value) {
            switch (state) {
                case 0:
                    if (value > OPEN_THRESHOLD) {
                        // Both eyes are initially open
                        state = 1;
                    }
                    break;

                case 1:
                    if (value < CLOSE_THRESHOLD ) {
                        // Both eyes become closed
                        state = 2;
                    }
                    break;

                case 2:
                    if (value > OPEN_THRESHOLD)  {
                        // Both eyes are open again
                        Log.i("BlinkTracker", "blink occurred!");
                        state = 0;

                    }
                    break;
            }

        }

        /**
         * Update the position/characteristics of the face within the overlay.
         */
        @Override
        public void onUpdate(FaceDetector.Detections<Face> detectionResults, Face face) {

            float left = face.getIsLeftEyeOpenProbability();
            float right = face.getIsRightEyeOpenProbability();
            if ((left == Face.UNCOMPUTED_PROBABILITY) ||
                    (right == Face.UNCOMPUTED_PROBABILITY)) {
                // One of the eyes was not detected.
                return;
            }

            float value = Math.min(left, right);
            blink(value);
        }
    }

}


问:
How to exit hotkey function and continue the script (AutoHotKey)?
Thanks for reading. :)

Let's give an example of what I say. I press shift+g and I execute one function. In the middle of executing it, I want to stop it by pressing shift+h, then execute another function, and then return the script so as it to stay waiting for another keystroke.

I thought about reloading the program, but I couldn't execute the following commands that way. Or, I could execute another program and reload the first one, but it is getting too complicated.

Any ideas will be greatly appreciated! :)

答:
As pointed out the easiest way is to put the script in a separate file and run it as an external program. something like this:

```<code>RunWait %A_AhkPath% test1.ahk
</code>```

Then in test1.apk put ExitApp in a hotkey. like this:

```<code>+t::
msgbox killing myself!
Exitapp
</code>```

very simple!

Body:
As pointed out the easiest way is to put the script in a separate file and run it as an external program. something like this:

RunWait %A_AhkPath% test1.ahk

Then in test1.apk put ExitApp in a hotkey. like this:

+t::
msgbox killing myself!
Exitapp

very simple!


问:
Upgrade App Engine servlet-api-2.5 to servlet-api-3.1?
With the recent announcement of support for Servlet 3.1, I cannot figure out how to modify the App Engine Standard environment to use 3.1 instead of 2.5 in a non-Maven build.

It seems there is no way to upgrade to 3.1?

https://cloudplatform.googleblog.com/2017/06/Google-App-Engine-standard-now-supports-Java-8.html

答:
Here is a full example given here: https://github.com/GoogleCloudPlatform/getting-started-java/tree/master/appengine-standard-java8/helloworld

Running procedure is also attached.

For Gradle Users:

For non-maven users, you can use gradle.

In gradle build file, line number 39 denotes: https://github.com/GoogleCloudPlatform/getting-started-java/blob/master/appengine-standard-java8/helloworld/build.gradle#L39

```<code>providedCompile 'javax.servlet:javax.servlet-api:3.1.0'
</code>```

Running locally:

gradle appengineRun

If you do not have gradle installed, you can run using ./gradlew appengineRun.

To use visit: http://localhost:8080/

For Maven Users

In pom.xml, line number 62 to 70 denotes that it is using servlet version 3.1.0: https://github.com/GoogleCloudPlatform/getting-started-java/blob/master/appengine-standard-java8/helloworld/pom.xml#L66

```<code><!-- [START servlet] -->
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.1.0</version>
  <type>jar</type>
  <scope>provided</scope>
</dependency>
<!-- [END servlet] -->
</code>```

Hope it will clarify you.

Body:
Here is a full example given here: https://github.com/GoogleCloudPlatform/getting-started-java/tree/master/appengine-standard-java8/helloworld

Running procedure is also attached.

For Gradle Users:

For non-maven users, you can use gradle.

In gradle build file, line number 39 denotes: https://github.com/GoogleCloudPlatform/getting-started-java/blob/master/appengine-standard-java8/helloworld/build.gradle#L39

providedCompile 'javax.servlet:javax.servlet-api:3.1.0'

Running locally:

gradle appengineRun

If you do not have gradle installed, you can run using ./gradlew appengineRun.

To use visit: http://localhost:8080/

For Maven Users

In pom.xml, line number 62 to 70 denotes that it is using servlet version 3.1.0: https://github.com/GoogleCloudPlatform/getting-started-java/blob/master/appengine-standard-java8/helloworld/pom.xml#L66

<!-- [START servlet] -->
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.1.0</version>
  <type>jar</type>
  <scope>provided</scope>
</dependency>
<!-- [END servlet] -->

Hope it will clarify you.


问:
Hive Jdbc connection errors with NoClassDefFoundError
I am writing Jdbc program to connect with hive database but
I am getting error as:

Exception in thread "main" java.lang.NoClassDefFoundError:
  org/apache/hadoop/conf/Configuration  at
  org.apache.hive.jdbc.HiveConnection.createUnderlyingTransport(HiveConnection.java:418)
    at
  org.apache.hive.jdbc.HiveConnection.createBinaryTransport(HiveConnection.java:438)
    at
  org.apache.hive.jdbc.HiveConnection.openTransport(HiveConnection.java:225)
    at
  org.apache.hive.jdbc.HiveConnection.(HiveConnection.java:182)
    at org.apache.hive.jdbc.HiveDriver.connect(HiveDriver.java:107)     at
  java.sql.DriverManager.getConnection(DriverManager.java:571)  at
  java.sql.DriverManager.getConnection(DriverManager.java:215)  at
  com.nucsoft.client.HiveJdbc.main(HiveJdbc.java:31)

答:
You're missing the Configuration class. hadoop-core jar was changed to hadoop-common in Hadoop 2. Here's the dependency and a link to download the JAR:

```<code><dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-common</artifactId>
    <version>2.7.3</version>
</dependency>
</code>```

Body:
You're missing the Configuration class. hadoop-core jar was changed to hadoop-common in Hadoop 2. Here's the dependency and a link to download the JAR:

<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-common</artifactId>
    <version>2.7.3</version>
</dependency>


问:
Angular 2 login not working in safari and firefox
For some reason the login part of my application is not working on safari and firefox.

I get this error while trying to auth.

Now the code is working perfectly in chrome.

Signin Service.ts

```<code>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Http, Headers, RequestOptions } from '@angular/http';

import { HttpWrapper } from '../../../shared/services/http-wrapper.service';
import { SERVER_URL } from '../../../shared/config/config';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class SigninService {

  constructor(
    private http_native: Http,
    private http: HttpWrapper
  ) { };

  public login(user: { email: string, password: string }): Observable<any> {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    headers.append('Accept', 'application/json;q=0.9,*/*;q=0.8')

    let options = new RequestOptions({ headers: headers });
    return this.http_native.post(`${SERVER_URL}users/login`, JSON.stringify(user), options)
      .catch((error: any) => {
        return Observable.throw(error);
      })
      .map((response: Response) => {
        return response.json();
      })
  };
</code>```

SinginComponent.ts

```<code> public login($event): void {
    $event.preventDefault();

    if (this.signinForm.valid) {
      this.signinFormIsValid = true;
      let { email, password } = this.signinForm.value;

      this.signinService.login({ email, password })
        .subscribe((response: any) => {
          console.log('response', response);
          sessionStorage.setItem('user', JSON.stringify(response));
          this.loginDispatcherService.setUser(response);

          this.availableParties = response.associatedPartyIds;
          this.tokenId = response.authenticationTokenId;
          this.stepOne = false;
          this.stepTwo = true;

        });
    } else {
      this.signinFormIsValid = false;
    }
  };
</code>```

Any suggestions are welcomed.

答:
you need to upgrade the es6-shim.

check this -> https://www.npmjs.com/package/es6-shim

Body:
For some reason the login part of my application is not working on safari and firefox.

I get this error while trying to auth.

Now the code is working perfectly in chrome.

Signin Service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Http, Headers, RequestOptions } from '@angular/http';

import { HttpWrapper } from '../../../shared/services/http-wrapper.service';
import { SERVER_URL } from '../../../shared/config/config';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class SigninService {

  constructor(
    private http_native: Http,
    private http: HttpWrapper
  ) { };

  public login(user: { email: string, password: string }): Observable<any> {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    headers.append('Accept', 'application/json;q=0.9,*/*;q=0.8')

    let options = new RequestOptions({ headers: headers });
    return this.http_native.post(`${SERVER_URL}users/login`, JSON.stringify(user), options)
      .catch((error: any) => {
        return Observable.throw(error);
      })
      .map((response: Response) => {
        return response.json();
      })
  };

SinginComponent.ts

 public login($event): void {
    $event.preventDefault();

    if (this.signinForm.valid) {
      this.signinFormIsValid = true;
      let { email, password } = this.signinForm.value;

      this.signinService.login({ email, password })
        .subscribe((response: any) => {
          console.log('response', response);
          sessionStorage.setItem('user', JSON.stringify(response));
          this.loginDispatcherService.setUser(response);

          this.availableParties = response.associatedPartyIds;
          this.tokenId = response.authenticationTokenId;
          this.stepOne = false;
          this.stepTwo = true;

        });
    } else {
      this.signinFormIsValid = false;
    }
  };

Any suggestions are welcomed.


问:
Create a bar plot in pandas with dates on x-axis, one bar for each value in other column
I have the following pandas dataframe:

```<code>>>> df
>>> StartDate         Port  Count
2011-08-10 11:07:10   3128  10
2011-08-10 11:07:40     80   1
2011-08-10 11:07:40    443   1
2011-08-10 11:07:40   3128  10
2011-08-10 11:08:00    443   1
2011-08-10 11:08:00   3128   9
2011-08-10 11:08:20     80   1
</code>```

I want to create a histogram where on x-axis will be 'StartDate' periods, on y-axis will be count and there will be one column for each value from the 'Port' column.

I tried using groupby() with df.plot.bar(), but it does not give me the result I want. How could I do it?

Ok, not the best drawing, but should give the idea. y-axis is a count, each bar represents the value from the 'Port' column. On x-axis are dates from the first column

Body:
I have the following pandas dataframe:

>>> df
>>> StartDate         Port  Count
2011-08-10 11:07:10   3128  10
2011-08-10 11:07:40     80   1
2011-08-10 11:07:40    443   1
2011-08-10 11:07:40   3128  10
2011-08-10 11:08:00    443   1
2011-08-10 11:08:00   3128   9
2011-08-10 11:08:20     80   1

I want to create a histogram where on x-axis will be 'StartDate' periods, on y-axis will be count and there will be one column for each value from the 'Port' column.

I tried using groupby() with df.plot.bar(), but it does not give me the result I want. How could I do it?

Ok, not the best drawing, but should give the idea. y-axis is a count, each bar represents the value from the 'Port' column. On x-axis are dates from the first column

Body:
I believe you need set_index + unstack for reshaping and last use DataFrame.plot.bar:

df1 = df.set_index(['StartDate','Port'])['Count'].unstack(fill_value=0)
print (df1)
Port                 80    443   3128
StartDate
2011-08-10 11:07:10     0     0    10
2011-08-10 11:07:40     1     1    10
2011-08-10 11:08:00     0     1     9
2011-08-10 11:08:20     1     0     0

df1.plot.bar()

Alternative solution  with pivot:

df1 = df.pivot(index='StartDate', columns='Port', values='Count')
print (df1)
Port                 80    443   3128
StartDate
2011-08-10 11:07:10   NaN   NaN  10.0
2011-08-10 11:07:40   1.0   1.0  10.0
2011-08-10 11:08:00   NaN   1.0   9.0
2011-08-10 11:08:20   1.0   NaN   NaN

df1.plot.bar()


问:
Docker swarm constantly shuts down containers
I have created a docker swarm manager node on 3 machines - one windows 10 machine and 2 Ubuntu machines. Things are working as expected on windows 10 and one of the Ubuntu machines. However on the last machine (Ubuntu 16.04, a virtual one on Linode) after installing everything, following the instructions here and using the docker-ce version 17.06.0~ce-0~ubuntu I am not able to start any service or stack properly - all of the service/stack containers shutdown in a second. No logs from the containers themselves - they seem to be stopped immediatelly after they have started. If the restart_policy is set to on-failure containers start and shutdown like crazy. Replicas are set to 1 (default). Starting any service and then checking services status with

```<code>docker service ps *service-name*
</code>```

shows an error in the rightmost column

```<code>starting container failed: suвЂ¦
</code>```

Other than the swarm docker run works just fine -

```<code>docker run hello-world
</code>```

produces the desired output. So do any other containers started via docker run.

答:
It seems the issue is the fact that Linode is using by default their own signed kernels, which are causing issues for other people too. This was revealed because when inspecting the stack network most options seemed to be set to null. A further search suggests that there is an issue with Linode's kernels which causes the swarm networking to fail.

To prevent any such issues you can just use the default kernels by editing the machine in question and setting its kernel to GRUB2. Lots of helpful info here.

Body:
I have created a docker swarm manager node on 3 machines - one windows 10 machine and 2 Ubuntu machines. Things are working as expected on windows 10 and one of the Ubuntu machines. However on the last machine (Ubuntu 16.04, a virtual one on Linode) after installing everything, following the instructions here and using the docker-ce version 17.06.0~ce-0~ubuntu I am not able to start any service or stack properly - all of the service/stack containers shutdown in a second. No logs from the containers themselves - they seem to be stopped immediatelly after they have started. If the restart_policy is set to on-failure containers start and shutdown like crazy. Replicas are set to 1 (default). Starting any service and then checking services status with

docker service ps *service-name*

shows an error in the rightmost column

starting container failed: suвЂ¦

Other than the swarm docker run works just fine -

docker run hello-world

produces the desired output. So do any other containers started via docker run.


问:
Trouble with my While Loop
Beginner in Java here and I'm creating a program that will calculate the area and volume of a sphere after a value for the radius has been given. If the radius is <= 0, then it should display an error message in the form of a JOptionPane and then return to asking for the radius, however, I am struggling with the while loop.

Here is my code:

```<code>public static void main(String[] args) {
    String volume = "V = (4(pi)r^3)/3";
    String area = "V = 4(pi)r^2";
    JOptionPane.showMessageDialog(null, "Formulas for a Sphere:"+"\n"+"V = (4(pi)r^3)/3"+"\n"+"A = 4(pi)r^2");
    Double radius = Double.parseDouble(JOptionPane.showInputDialog("Enter Radius(cm)"));
    while(radius <= 0) {
        JOptionPane.showMessageDialog(null, "Please insert a valid radius.");
    }
    JOptionPane.showMessageDialog(null, volume + " = " + Math.round((4*3.1415*Math.pow(radius,3)/3)) + "cm" +
            "\n" + area + " = " + Math.round(4*3.1415*Math.pow(radius,2)));
</code>```

答:
Another possibility (just to avoid duplicating code):</p>

```<code>while (true) {
    Double radius = Double.parseDouble(JOptionPane.showInputDialog("Enter  Radius(cm)"));
    if (radius > 0)
        break;
    JOptionPane.showMessageDialog(null, "Please insert a valid radius.");
}
</code>```

Title: Trouble with my While Loop

Body:
Beginner in Java here and I'm creating a program that will calculate the area and volume of a sphere after a value for the radius has been given. If the radius is <= 0, then it should display an error message in the form of a JOptionPane and then return to asking for the radius, however, I am struggling with the while loop.

Here is my code:

public static void main(String[] args) {
    String volume = "V = (4(pi)r^3)/3";
    String area = "V = 4(pi)r^2";
    JOptionPane.showMessageDialog(null, "Formulas for a Sphere:"+"\n"+"V = (4(pi)r^3)/3"+"\n"+"A = 4(pi)r^2");
    Double radius = Double.parseDouble(JOptionPane.showInputDialog("Enter Radius(cm)"));
    while(radius <= 0) {
        JOptionPane.showMessageDialog(null, "Please insert a valid radius.");
    }
    JOptionPane.showMessageDialog(null, volume + " = " + Math.round((4*3.1415*Math.pow(radius,3)/3)) + "cm" +
            "\n" + area + " = " + Math.round(4*3.1415*Math.pow(radius,2)));

Body:
Another possibility (just to avoid duplicating code):

while (true) {
    Double radius = Double.parseDouble(JOptionPane.showInputDialog("Enter  Radius(cm)"));
    if (radius > 0)
        break;
    JOptionPane.showMessageDialog(null, "Please insert a valid radius.");
}


问:
WordPress Admin Dashboard Hanging after Upgrading PHP / MySQL
So, long story short, the latest version of Apache was causing some errors with my particular setup so I did a quick on-the-fly upgrade to PHP 7.1.6, swapped to mpm-event, and started using PHP-FPM. I guess it probably reinstalled MySQL somewhere in there too.

The front end of my WordPress site seemed relatively fine after the upgrade. The admin dashboard is okay sometimes -- but every so often trying to post a new page, or do something similar it will hang indefinitely. If I restart Apache it snaps back to attention, but nothing short of restarting the service seems to do the trick.

During this time, the frontend of my site will also start hanging until I restart Apache.

Obviously, there's something wrong with my configuration somewhere, but I'm having a really tough time pinpointing what it is. The front-end of my site is super quick until I do something on the back-end that decides to stall it all out.

I've been checking every error log I can think of, but I don't see anything happening in the apache2 error log when this happens. As far as I can tell I enabled PHP-fpm error logging but I don't see anything showing up there either.

How can I figure out what's going wrong at this point?

Any help would really be appreciated. I've spent at least fifteen hours trying to figure this out already with zero progress.

Thanks, guys.

```<code>php -v
PHP 7.1.6-1~ubuntu16.04.1+deb.sury.org+1 (cli) (built: Jun  9 2017 08:26:34) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies
with Zend OPcache v7.1.6-1~ubuntu16.04.1+deb.sury.org+1, Copyright (c) 1999-2017, by Zend Technologies

apache2 -v
Server version: Apache/2.4.26 (Ubuntu)
Server built:   2017-06-30T08:42:23
</code>```

/var/log/apache2/error.log -- not reporting any errors.

/var/log/fpm-php.www.log -- empty.

/var/log/mysql.err -- empty.

/var/log/mysql.log -- empty.

```<code>/var/log/php7.1-fpm.log

[04-Jul-2017 02:08:40] NOTICE: fpm is running, pid 741
[04-Jul-2017 02:08:40] NOTICE: ready to handle connections
[04-Jul-2017 02:08:40] NOTICE: systemd monitor interval set to 10000ms
</code>```

PHP modules --

```<code>php -m
[PHP Modules]
calendar
Core
ctype
curl
date
dom
exif
fileinfo
filter
ftp
gd
gettext
hash
iconv
igbinary
json
libxml
mbstring
mcrypt
memcached
msgpack
mysqli
mysqlnd
openssl
pcntl
pcre
PDO
pdo_mysql
Phar
posix
readline
redis
Reflection
session
shmop
SimpleXML
sockets
SPL
standard
sysvmsg
sysvsem
sysvshm
tidy
tokenizer
wddx
xml
xmlreader
xmlwriter
xsl
Zend OPcache
zlib

[Zend Modules]
Zend OPcache
</code>```

a2query -m:

```<code>a2query -m
dir (enabled by maintainer script)
headers (enabled by site administrator)
env (enabled by maintainer script)
authz_host (enabled by maintainer script)
reqtimeout (enabled by maintainer script)
include (enabled by site administrator)
rewrite (enabled by site administrator)
auth_basic (enabled by maintainer script)
alias (enabled by maintainer script)
authz_core (enabled by maintainer script)
asis (enabled by site administrator)
status (enabled by maintainer script)
cache (enabled by site administrator)
echo (enabled by site administrator)
autoindex (enabled by maintainer script)
authz_user (enabled by maintainer script)
fastcgi (enabled by maintainer script)
actions (enabled by site administrator)
filter (enabled by maintainer script)
mime (enabled by maintainer script)
expires (enabled by site administrator)
setenvif (enabled by maintainer script)
mpm_event (enabled by site administrator)
socache_shmcb (enabled by site administrator)
authn_file (enabled by maintainer script)
proxy (enabled by site administrator)
access_compat (enabled by maintainer script)
ssl (enabled by site administrator)
deflate (enabled by maintainer script)
authn_core (enabled by maintainer script)
suexec (enabled by site administrator)
negotiation (enabled by maintainer script)
proxy_fcgi (enabled by site administrator)
speling (enabled by site administrator)
http2 (enabled by maintainer script)
info (enabled by site administrator)
proxy_http2 (enabled by site administrator)
</code>```

I'm not sure what it is, but /var/log/apport.log contains a few errors like this:

```<code>ERROR: apport (pid 12399) Tue Jul  4 00:26:27 2017: called for pid 12251, signal 11, core limit 0
ERROR: apport (pid 12399) Tue Jul  4 00:26:27 2017: executable: /usr/sbin/apache2 (command line "/usr/sbin/apache2 -k start")
ERROR: apport (pid 12399) Tue Jul  4 00:26:27 2017: is_closing_session(): no DBUS_SESSION_BUS_ADDRESS in environment
ERROR: apport (pid 12399) Tue Jul  4 00:26:27 2017: apport: report /var/crash/_usr_sbin_apache2.0.crash already exists and unseen, doing nothing to avoid disk usage DoS
</code>```

/var/log/kern.log:

```<code>Jul  4 02:08:39 localhost kernel: [    2.667815] ppdev: user-space parallel port driver
Jul  4 02:08:39 localhost kernel: [    2.691111] Request for unknown module key 'Magrathea: Glacier signing key: d120c47c14beb62ead6703d41712cc110575d297' err -11
Jul  4 02:08:39 localhost kernel: [    2.716583] Request for unknown module key 'Magrathea: Glacier signing key: d120c47c14beb62ead6703d41712cc110575d297' err -11
Jul  4 02:08:39 localhost kernel: [    2.717334] Request for unknown module key 'Magrathea: Glacier signing key: d120c47c14beb62ead6703d41712cc110575d297' err -11
Jul  4 02:08:40 localhost kernel: [    5.345061] audit: type=1400 audit(1499148520.484:8): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/proc/874/status" pid=874 comm="mysqld" requeste$
Jul  4 02:08:40 localhost kernel: [    5.345262] audit: type=1400 audit(1499148520.484:9): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/sys/devices/system/node/" pid=874 comm="mysqld"$
Jul  4 02:08:40 localhost kernel: [    5.345373] audit: type=1400 audit(1499148520.484:10): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/proc/874/status" pid=874 comm="mysqld" request$
Jul  4 02:08:40 localhost kernel: [    5.391287] random: nonblocking pool is initialized
Jul  4 02:08:40 localhost kernel: [    5.577297] Request for unknown module key 'Magrathea: Glacier signing key: d120c47c14beb62ead6703d41712cc110575d297' err -11
Jul  4 02:10:10 localhost kernel: [   95.097387] perf interrupt took too long (2626 > 2500), lowering kernel.perf_event_max_sample_rate to 50000
Jul  4 02:26:07 localhost kernel: [ 1052.647086] audit: type=1400 audit(1499149567.761:11): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/proc/1445/status" pid=1445 comm="mysqld" reque$
Jul  4 02:26:07 localhost kernel: [ 1052.647352] audit: type=1400 audit(1499149567.761:12): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/sys/devices/system/node/" pid=1445 comm="mysql$
Jul  4 02:26:07 localhost kernel: [ 1052.647513] audit: type=1400 audit(1499149567.761:13): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/proc/1445/status" pid=1445 comm="mysqld" reque$
Jul  4 02:26:23 localhost kernel: [ 1067.895962] audit: type=1400 audit(1499149583.008:14): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/proc/1446/status" pid=1446 comm="mysqld" reque$
Jul  4 02:26:23 localhost kernel: [ 1067.896241] audit: type=1400 audit(1499149583.012:15): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/sys/devices/system/node/" pid=1446 comm="mysql$
Jul  4 02:26:23 localhost kernel: [ 1067.896340] audit: type=1400 audit(1499149583.012:16): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/proc/1446/status" pid=1446 comm="mysqld" reque$
Jul  4 02:31:19 localhost kernel: [ 1364.640301] perf interrupt took too long (5248 > 5000), lowering kernel.perf_event_max_sample_rate to 25000
Jul  4 02:37:26 localhost kernel: [ 1731.575398] audit: type=1400 audit(1499150246.686:17): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/proc/1540/status" pid=1540 comm="mysqld" reque$
Jul  4 02:37:26 localhost kernel: [ 1731.575508] audit: type=1400 audit(1499150246.686:18): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/sys/devices/system/node/" pid=1540 comm="mysql$
Jul  4 02:37:26 localhost kernel: [ 1731.575596] audit: type=1400 audit(1499150246.686:19): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/proc/1540/status" pid=1540 comm="mysqld" reque$
Jul  4 02:42:49 localhost kernel: [ 2054.276362] perf interrupt took too long (10122 > 10000), lowering kernel.perf_event_max_sample_rate to 12500
Jul  4 04:00:02 localhost kernel: [ 6687.106794] perf interrupt took too long (20184 > 20000), lowering kernel.perf_event_max_sample_rate to 6250
</code>```

Will get more information edited in shortly.

答:
Go to "wp-config.php" and set "WP_DEBUG" to true just like in the following example:

define( 'WP_DEBUG', true );

Now refresh the frontend and the backend page in order to be able to see the PHP errors.

You can also go to the admin area, Settings, Permalinks and click once again on the "save" button. This will override the .htaccess file.

You can install a log service, search on google for logly or sentry. Those might help also.

Body:
So, long story short, the latest version of Apache was causing some errors with my particular setup so I did a quick on-the-fly upgrade to PHP 7.1.6, swapped to mpm-event, and started using PHP-FPM. I guess it probably reinstalled MySQL somewhere in there too.

The front end of my WordPress site seemed relatively fine after the upgrade. The admin dashboard is okay sometimes -- but every so often trying to post a new page, or do something similar it will hang indefinitely. If I restart Apache it snaps back to attention, but nothing short of restarting the service seems to do the trick.

During this time, the frontend of my site will also start hanging until I restart Apache.

Obviously, there's something wrong with my configuration somewhere, but I'm having a really tough time pinpointing what it is. The front-end of my site is super quick until I do something on the back-end that decides to stall it all out.

I've been checking every error log I can think of, but I don't see anything happening in the apache2 error log when this happens. As far as I can tell I enabled PHP-fpm error logging but I don't see anything showing up there either.

How can I figure out what's going wrong at this point?

Any help would really be appreciated. I've spent at least fifteen hours trying to figure this out already with zero progress.

Thanks, guys.

php -v
PHP 7.1.6-1~ubuntu16.04.1+deb.sury.org+1 (cli) (built: Jun  9 2017 08:26:34) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies
with Zend OPcache v7.1.6-1~ubuntu16.04.1+deb.sury.org+1, Copyright (c) 1999-2017, by Zend Technologies

apache2 -v
Server version: Apache/2.4.26 (Ubuntu)
Server built:   2017-06-30T08:42:23

/var/log/apache2/error.log -- not reporting any errors.

/var/log/fpm-php.www.log -- empty.

/var/log/mysql.err -- empty.

/var/log/mysql.log -- empty.

/var/log/php7.1-fpm.log

[04-Jul-2017 02:08:40] NOTICE: fpm is running, pid 741
[04-Jul-2017 02:08:40] NOTICE: ready to handle connections
[04-Jul-2017 02:08:40] NOTICE: systemd monitor interval set to 10000ms

PHP modules --

php -m
[PHP Modules]
calendar
Core
ctype
curl
date
dom
exif
fileinfo
filter
ftp
gd
gettext
hash
iconv
igbinary
json
libxml
mbstring
mcrypt
memcached
msgpack
mysqli
mysqlnd
openssl
pcntl
pcre
PDO
pdo_mysql
Phar
posix
readline
redis
Reflection
session
shmop
SimpleXML
sockets
SPL
standard
sysvmsg
sysvsem
sysvshm
tidy
tokenizer
wddx
xml
xmlreader
xmlwriter
xsl
Zend OPcache
zlib

[Zend Modules]
Zend OPcache

a2query -m:

a2query -m
dir (enabled by maintainer script)
headers (enabled by site administrator)
env (enabled by maintainer script)
authz_host (enabled by maintainer script)
reqtimeout (enabled by maintainer script)
include (enabled by site administrator)
rewrite (enabled by site administrator)
auth_basic (enabled by maintainer script)
alias (enabled by maintainer script)
authz_core (enabled by maintainer script)
asis (enabled by site administrator)
status (enabled by maintainer script)
cache (enabled by site administrator)
echo (enabled by site administrator)
autoindex (enabled by maintainer script)
authz_user (enabled by maintainer script)
fastcgi (enabled by maintainer script)
actions (enabled by site administrator)
filter (enabled by maintainer script)
mime (enabled by maintainer script)
expires (enabled by site administrator)
setenvif (enabled by maintainer script)
mpm_event (enabled by site administrator)
socache_shmcb (enabled by site administrator)
authn_file (enabled by maintainer script)
proxy (enabled by site administrator)
access_compat (enabled by maintainer script)
ssl (enabled by site administrator)
deflate (enabled by maintainer script)
authn_core (enabled by maintainer script)
suexec (enabled by site administrator)
negotiation (enabled by maintainer script)
proxy_fcgi (enabled by site administrator)
speling (enabled by site administrator)
http2 (enabled by maintainer script)
info (enabled by site administrator)
proxy_http2 (enabled by site administrator)

I'm not sure what it is, but /var/log/apport.log contains a few errors like this:

ERROR: apport (pid 12399) Tue Jul  4 00:26:27 2017: called for pid 12251, signal 11, core limit 0
ERROR: apport (pid 12399) Tue Jul  4 00:26:27 2017: executable: /usr/sbin/apache2 (command line "/usr/sbin/apache2 -k start")
ERROR: apport (pid 12399) Tue Jul  4 00:26:27 2017: is_closing_session(): no DBUS_SESSION_BUS_ADDRESS in environment
ERROR: apport (pid 12399) Tue Jul  4 00:26:27 2017: apport: report /var/crash/_usr_sbin_apache2.0.crash already exists and unseen, doing nothing to avoid disk usage DoS

/var/log/kern.log:

Jul  4 02:08:39 localhost kernel: [    2.667815] ppdev: user-space parallel port driver
Jul  4 02:08:39 localhost kernel: [    2.691111] Request for unknown module key 'Magrathea: Glacier signing key: d120c47c14beb62ead6703d41712cc110575d297' err -11
Jul  4 02:08:39 localhost kernel: [    2.716583] Request for unknown module key 'Magrathea: Glacier signing key: d120c47c14beb62ead6703d41712cc110575d297' err -11
Jul  4 02:08:39 localhost kernel: [    2.717334] Request for unknown module key 'Magrathea: Glacier signing key: d120c47c14beb62ead6703d41712cc110575d297' err -11
Jul  4 02:08:40 localhost kernel: [    5.345061] audit: type=1400 audit(1499148520.484:8): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/proc/874/status" pid=874 comm="mysqld" requeste$
Jul  4 02:08:40 localhost kernel: [    5.345262] audit: type=1400 audit(1499148520.484:9): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/sys/devices/system/node/" pid=874 comm="mysqld"$
Jul  4 02:08:40 localhost kernel: [    5.345373] audit: type=1400 audit(1499148520.484:10): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/proc/874/status" pid=874 comm="mysqld" request$
Jul  4 02:08:40 localhost kernel: [    5.391287] random: nonblocking pool is initialized
Jul  4 02:08:40 localhost kernel: [    5.577297] Request for unknown module key 'Magrathea: Glacier signing key: d120c47c14beb62ead6703d41712cc110575d297' err -11
Jul  4 02:10:10 localhost kernel: [   95.097387] perf interrupt took too long (2626 > 2500), lowering kernel.perf_event_max_sample_rate to 50000
Jul  4 02:26:07 localhost kernel: [ 1052.647086] audit: type=1400 audit(1499149567.761:11): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/proc/1445/status" pid=1445 comm="mysqld" reque$
Jul  4 02:26:07 localhost kernel: [ 1052.647352] audit: type=1400 audit(1499149567.761:12): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/sys/devices/system/node/" pid=1445 comm="mysql$
Jul  4 02:26:07 localhost kernel: [ 1052.647513] audit: type=1400 audit(1499149567.761:13): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/proc/1445/status" pid=1445 comm="mysqld" reque$
Jul  4 02:26:23 localhost kernel: [ 1067.895962] audit: type=1400 audit(1499149583.008:14): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/proc/1446/status" pid=1446 comm="mysqld" reque$
Jul  4 02:26:23 localhost kernel: [ 1067.896241] audit: type=1400 audit(1499149583.012:15): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/sys/devices/system/node/" pid=1446 comm="mysql$
Jul  4 02:26:23 localhost kernel: [ 1067.896340] audit: type=1400 audit(1499149583.012:16): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/proc/1446/status" pid=1446 comm="mysqld" reque$
Jul  4 02:31:19 localhost kernel: [ 1364.640301] perf interrupt took too long (5248 > 5000), lowering kernel.perf_event_max_sample_rate to 25000
Jul  4 02:37:26 localhost kernel: [ 1731.575398] audit: type=1400 audit(1499150246.686:17): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/proc/1540/status" pid=1540 comm="mysqld" reque$
Jul  4 02:37:26 localhost kernel: [ 1731.575508] audit: type=1400 audit(1499150246.686:18): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/sys/devices/system/node/" pid=1540 comm="mysql$
Jul  4 02:37:26 localhost kernel: [ 1731.575596] audit: type=1400 audit(1499150246.686:19): apparmor="DENIED" operation="open" profile="/usr/sbin/mysqld" name="/proc/1540/status" pid=1540 comm="mysqld" reque$
Jul  4 02:42:49 localhost kernel: [ 2054.276362] perf interrupt took too long (10122 > 10000), lowering kernel.perf_event_max_sample_rate to 12500
Jul  4 04:00:02 localhost kernel: [ 6687.106794] perf interrupt took too long (20184 > 20000), lowering kernel.perf_event_max_sample_rate to 6250

Will get more information edited in shortly.


问:
I'm trying to get a count of records from a related entity that match a criteria
I have an entity matches which has a related to-many entity sets. I want to get a count of how many sets have the attribute 'set_finished' set to YES for a particular match. I'm trying to do this with:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY set_finished == YES"];
 NSUInteger numberOfFinishedSets = [[[match valueForKeyPath:@"sets"] filteredArrayUsingPredicate:predicate ] count];

The second line crashes with this error, which I don't understand. Can anyone shed some light on this for me? Thanks.

2010-12-20 13:17:13.814
  DartScorer[2154:207] * Terminating
  app due to uncaught exception
  'NSInvalidArgumentException', reason:
  '-[_NSFaultingMutableSet
  filteredArrayUsingPredicate:]:
  unrecognized selector sent to instance
  0x617fb20'

答:
_NSFaultingMutableSet is kind of an empty set (if you will print the set you will see that xcode prints the entity name but not its content. it does that because :

Faulting reduces the amount of memory
  your application consumes. A fault is
  a placeholder object that represents a
  managed object that has not yet been
  fully realized, or a collection object
  that represents a relationship:

A managed object fault is an instance
  of the appropriate class, but its
  persistent variables are not yet
  initialized. A relationship fault is a
  subclass of the collection class that
  represents the relationship. Faulting
  allows Core Data to put boundaries on
  the object graph. Because a fault is
  not realized, a managed object fault
  consumes less memory, and managed
  objects related to a fault are not
  required to be represented in memory
  at all.

i think you should create a Set to hold the objects you want to filter, and then filter the array tou have created.

hope it helps
shani

ContentLicense: CC BY-SA 2.5


问:
Jquery How to automatically assign an ascending integer for each row starting from 1
Right now, when the rows no is entered and the button is clicked, respective no of rows will be added.

Now, i'd like to assign an ascending integer for each row starting from 1,
any idea guys?

$('#add-row').click(function() {
  var $tbody, $row, additionalRows;
  var numNewRows = parseInt($('#insert-rows-amnt').val(), 10);

  if (isNaN(numNewRows) || numNewRows <= 0) {
    alert('Please enter number of injection');
  } else {

    $tbody = $('table tbody');
    $row = $tbody.find('tr:last');

    additionalRows = new Array(numNewRows + 0).join($row[0].outerHTML);

    $tbody.append(additionalRows);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="number" id="insert-rows-amnt" name="insert-rows-amnt" value="<?php echo $tam ?>" />
<button id="add-row" type="button">Rows no</button>
<table>
  <tbody>
    <tr>
      <td><input type="text" style="width: 100px" name="vaccineid[]"> </td>
      <td><input type="text" style="width: 160px" name="vaccinename1[]"></td>

    </tr>
</table>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script></code>```

答:
I changed the table body to include index on the table first column starting from 1

$('#add-row').click(function() {
  var $tbody, $row, additionalRows;
  var numNewRows = parseInt($('#insert-rows-amnt').val(), 10);

  if (isNaN(numNewRows) || numNewRows <= 0) {
    alert('Please enter number of injection');
  } else {

    $tbody = $('table tbody');
    $row = $tbody.find('tr:last');
    var lastRowIndex=($row.index()==-1? 0:$row.index()) +1 ;
    additionalRows = new Array(numNewRows);
    for(i=0;i<numNewRows;i++)
    {
    additionalRows[i]=`

    ${lastRowIndex}

      <input type="text" style="width: 100px" name="vaccineid[]">
      <input type="text" style="width:160px"name="vaccinename1[]">

`
      lastRowIndex=lastRowIndex+1;
    }

    $tbody.append(additionalRows.join());
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="insert-rows-amnt" name="insert-rows-amnt" value="<?php echo $tam ?>" />
<button id="add-row" type="button">Rows no</button>
<table>
  <tbody>

</table></code>```

Body:
Right now, when the rows no is entered and the button is clicked, respective no of rows will be added.

Now, i'd like to assign an ascending integer for each row starting from 1,
any idea guys?

$('#add-row').click(function() {
  var $tbody, $row, additionalRows;
  var numNewRows = parseInt($('#insert-rows-amnt').val(), 10);

  if (isNaN(numNewRows) || numNewRows <= 0) {
    alert('Please enter number of injection');
  } else {

    $tbody = $('table tbody');
    $row = $tbody.find('tr:last');

    additionalRows = new Array(numNewRows + 0).join($row[0].outerHTML);

    $tbody.append(additionalRows);
  }
});

<input type="number" id="insert-rows-amnt" name="insert-rows-amnt" value="<?php echo $tam ?>" />
<button id="add-row" type="button">Rows no</button>

      <input type="text" style="width: 100px" name="vaccineid[]">
      <input type="text" style="width: 160px" name="vaccinename1[]">

Body:
I changed the table body to include index on the table first column starting from 1

$('#add-row').click(function() {
  var $tbody, $row, additionalRows;
  var numNewRows = parseInt($('#insert-rows-amnt').val(), 10);

  if (isNaN(numNewRows) || numNewRows <= 0) {
    alert('Please enter number of injection');
  } else {

    $tbody = $('table tbody');
    $row = $tbody.find('tr:last');
    var lastRowIndex=($row.index()==-1? 0:$row.index()) +1 ;
    additionalRows = new Array(numNewRows);
    for(i=0;i<numNewRows;i++)
    {
    additionalRows[i]=` <tr>
    <td>${lastRowIndex}</td>
      <td>
      <input type="text" style="width: 100px" name="vaccineid[]"></td>
      <td><input type="text" style="width:160px"name="vaccinename1[]">       </td>
     </tr>`
      lastRowIndex=lastRowIndex+1;
    }

    $tbody.append(additionalRows.join());
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="insert-rows-amnt" name="insert-rows-amnt" value="<?php echo $tam ?>" />
<button id="add-row" type="button">Rows no</button>
<table>
  <tbody>

</table>


问:
Position fixed element outside of  is inserted inside of
When I put an element like
 outside of  element, which is set as "position: fixed", it appears inside of .

I'm told that the "position: fixed" makes its element put into  even if it's outside of it.

Is that correct? and what's good and bad when do code like this?

答:
HTML doesn't allow a
 element to appear outside the  element.

HTML's parsing rules (and error recovery) will move the element back inside the .

CSS has nothing to do with it.

Follow the specification. Write valid HTML.

Title: Position fixed element outside of <body> is inserted inside of <body>

Body:
HTML doesn't allow a <div> element to appear outside the <body> element.

HTML's parsing rules (and error recovery) will move the element back inside the <body>.

CSS has nothing to do with it.

Follow the specification. Write valid HTML.


问:
How can I select * WHERE & receive other results connected to the found primary keys?
So I've got the following tables setup:

thread:

id

created_at

thread_users:

id

thread_id -> FK thread

user_id -> FK users (the user who is in the thread)

joined_at

users:

id

name

etc...other relevant details for user

Current functionality: When a user clicks on another user (e.g there FRIEND in the app), it will open the message thread between the 2 users (it should grab the msgs between the 2 users). To determine WHICH thread to use (we need to find the thread_id between the 2 users), we must query the thread_users table using the HTTP_REQUEST_USER (user who sent the GET request) & and the user_id PARAM passed in the http GET request.

Once I do this: select * from thread_users where user_id = HTTP_REQUEST_USER_ID OR user_id = GET_REQUEST_PARAM_USER_ID

It will return a bunch of threads that the users are in, I then group the returned results using the lodash groupBy method: (which basically MOVES all the results into there corresponding thread objects - E.g 6: [ { user1 }, { user2 } ] - This represents the thread_id 6)

```<code>const groupedThreads = _.groupBy(foundThreadUsers, 'thread_id');
</code>```

From here I loop through each of the found threads (groupedThreads will contain objects THAT contain the arrays of user in each of the threads)

```<code>Object.keys(groupedThreads).forEach((key) => {
      const thr = groupedThreads[key].filter(tu => tu.user_id === currentUserId || tu.user_id === userId);
      console.log(thr, 'FOUND THREAD inside loop after filter');
      /**
       * @TODO add something here which will take into account pluralbot
       */
      if (thr.length === 2) {
        foundThread = thr[0];
      }
    });
</code>```

However, this bit of logic doesn't work:

```<code>if (thr.length === 2) {
   foundThread = thr[0];
}
</code>```

Because the select * from ... (query listed above ^^), only returns the thread_users that match the user ids passed into the where user_id = x OR user_id = y.

I want to be able to select * from thread_users where user_id = HTTP_REQUEST_USER_ID OR user_id = GET_REQUEST_PARAM_USER_ID BUT also return the other users WHO match the found thread_users.thread_id. Is this possible? Or is there another way I could find the thread between the 2 users?

答:
This is the trivial solution using a normal relational data model. (you could combine the two EXISTS() conditions) :

```<code>SELECT *
FROM thread th
WHERE EXISTS (
        SELECT *
        FROM user_thread ut
        WHERE ut.thread_id = th.id
        AND ut.user_id = ***user1***
        )
AND EXISTS (
        SELECT *
        FROM user_thread ut
        WHERE ut.thread_id = th.id
        AND ut.user_id = ***user2***
        )
        ;
</code>```

Body:
So I've got the following tables setup:

thread:

id

created_at

thread_users:

id

thread_id -> FK thread

user_id -> FK users (the user who is in the thread)

joined_at

users:

id

name

etc...other relevant details for user

Current functionality: When a user clicks on another user (e.g there FRIEND in the app), it will open the message thread between the 2 users (it should grab the msgs between the 2 users). To determine WHICH thread to use (we need to find the thread_id between the 2 users), we must query the thread_users table using the HTTP_REQUEST_USER (user who sent the GET request) & and the user_id PARAM passed in the http GET request.

Once I do this: select * from thread_users where user_id = HTTP_REQUEST_USER_ID OR user_id = GET_REQUEST_PARAM_USER_ID

It will return a bunch of threads that the users are in, I then group the returned results using the lodash groupBy method: (which basically MOVES all the results into there corresponding thread objects - E.g 6: [ { user1 }, { user2 } ] - This represents the thread_id 6)

const groupedThreads = _.groupBy(foundThreadUsers, 'thread_id');

From here I loop through each of the found threads (groupedThreads will contain objects THAT contain the arrays of user in each of the threads)

Object.keys(groupedThreads).forEach((key) => {
      const thr = groupedThreads[key].filter(tu => tu.user_id === currentUserId || tu.user_id === userId);
      console.log(thr, 'FOUND THREAD inside loop after filter');
      /**
       * @TODO add something here which will take into account pluralbot
       */
      if (thr.length === 2) {
        foundThread = thr[0];
      }
    });

However, this bit of logic doesn't work:

if (thr.length === 2) {
   foundThread = thr[0];
}

Because the select * from ... (query listed above ^^), only returns the thread_users that match the user ids passed into the where user_id = x OR user_id = y.

I want to be able to select * from thread_users where user_id = HTTP_REQUEST_USER_ID OR user_id = GET_REQUEST_PARAM_USER_ID BUT also return the other users WHO match the found thread_users.thread_id. Is this possible? Or is there another way I could find the thread between the 2 users?

Body:
This is the trivial solution using a normal relational data model. (you could combine the two EXISTS() conditions) :

SELECT *
FROM thread th
WHERE EXISTS (
        SELECT *
        FROM user_thread ut
        WHERE ut.thread_id = th.id
        AND ut.user_id = ***user1***
        )
AND EXISTS (
        SELECT *
        FROM user_thread ut
        WHERE ut.thread_id = th.id
        AND ut.user_id = ***user2***
        )
        ;


问:
How to fix RequestError: Error: connect ETIMEDOUT while running Mocha JS/NodeJS test from behind proxy
I am getting the below error while trying to run Mocha JS test case which runs npm request-promise to call a REST service. I was able to connect to the REST URI endpoint through ARC client bur it failed with below error while running through organization's proxy-</p>

```<code>     RequestError: Error: connect ETIMEDOUT SERVER_IP:SERVER_PORT
  at new RequestError (<Some_Path>\errors.js:14:15)
  at Request.plumbing.callback (<Some_Path>\plumbing.js:87:29)
  at Request.RP$callback [as _callback] (<Some_Path>\plumbing.js:46:31)
  at self.callback (<Some_Path>\request.js:188:22)
  at Request.onRequestError (<Some_Path>\request\request.js:884:8)
  at TLSSocket.socketErrorListener (_http_client.js:309:9)
  at emitErrorNT (net.js:1277:8)
  at _combinedTickCallback (internal/process/next_tick.js:80:11)
  at process._tickCallback (internal/process/next_tick.js:104:9)
</code>```

答:
I fixed this issue with adding the following in the request-promise options-

proxy:'http://PROXY_SERVER_IP:PORT#'

I hope this helps.

Cheers,
Kunal

Body:
I am getting the below error while trying to run Mocha JS test case which runs npm request-promise to call a REST service. I was able to connect to the REST URI endpoint through ARC client bur it failed with below error while running through organization's proxy-

     RequestError: Error: connect ETIMEDOUT SERVER_IP:SERVER_PORT
  at new RequestError (<Some_Path>\errors.js:14:15)
  at Request.plumbing.callback (<Some_Path>\plumbing.js:87:29)
  at Request.RP$callback [as _callback] (<Some_Path>\plumbing.js:46:31)
  at self.callback (<Some_Path>\request.js:188:22)
  at Request.onRequestError (<Some_Path>\request\request.js:884:8)
  at TLSSocket.socketErrorListener (_http_client.js:309:9)
  at emitErrorNT (net.js:1277:8)
  at _combinedTickCallback (internal/process/next_tick.js:80:11)
  at process._tickCallback (internal/process/next_tick.js:104:9)


问:
"GoogleApiClient has an optional Plus.API and is not connected to Plus"
I am using google login for my android app, off lately i am getting Runtime exception reports with error "GoogleApiClient has an optional Plus.API and is not connected to Plus. Use GoogleApiClient.hasConnectedApi(Plus.API) to guard this call."

答:
In activity result obtained from google sign in use this </p>

```<code>if (mGoogleApiClient.hasConnectedApi(Plus.API)) {
            Person person  = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
            if (person != null) {
                //Take the required action
                Log.i(TAG, "Display Name: " + person.getDisplayName());
                Log.i(TAG, "Gender: " + person.getGender());
                Log.i(TAG, "About Me: " + person.getAboutMe());
                Log.i(TAG, "Birthday: " + person.getBirthday());
                Log.i(TAG, "Current Location: " + person.getCurrentLocation());
                Log.i(TAG, "Language: " + person.getLanguage());
            } else {
                Log.e(TAG, "Error!");
            }
</code>```

Body:
In activity result obtained from google sign in use this

if (mGoogleApiClient.hasConnectedApi(Plus.API)) {
            Person person  = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
            if (person != null) {
                //Take the required action
                Log.i(TAG, "Display Name: " + person.getDisplayName());
                Log.i(TAG, "Gender: " + person.getGender());
                Log.i(TAG, "About Me: " + person.getAboutMe());
                Log.i(TAG, "Birthday: " + person.getBirthday());
                Log.i(TAG, "Current Location: " + person.getCurrentLocation());
                Log.i(TAG, "Language: " + person.getLanguage());
            } else {
                Log.e(TAG, "Error!");
            }


问:
typescript: call public function
I'm new in typescript. In my node-express app, I want to call public function. But this is always undefined, so when I call public function, it throw always error. My code is given below:

app.ts

```<code> import * as express from 'express';
 import User from './user/ctrl';
 class App {
    public express: express.Application;
    constructor() {
       this.express = express();
       this.routes();
    }
    private routes():void {
       let router = express.Router();
       router.get('/', User.index);
       this.express.use('/', router);
    }
 }

export default new App().express;
</code>```

./user/ctrl.ts

```<code>class User {
   public demo:string;
   constructor() {
      this.demo = "this is text";
   }

   public infox() {
       console.log("demoo test : ", this.demo);
   }

   public index(req:any, res:any) {
       console.log(this) // output: undefined
       this.infox(); // throw an error.
   }
}

const user = new User();
export default user;
</code>```

Server run at port 3000.

Any suggestion??

答:
When you passed a reference the User.index function, the this inside it will change based on how it is called. Or when strict mode is on this will be undefined.

Change router.get('/', User.index); to router.get('/', (req, res) => User.index(req, res));. Notice that User.index is wrapped inside an arrow function which captures the correct this when User.index is called.

See red flags for this in TypeScript

Title: typescript: call public function

Body:
I'm new in typescript. In my node-express app, I want to call public function. But this is always undefined, so when I call public function, it throw always error. My code is given below:

app.ts

 import * as express from 'express';
 import User from './user/ctrl';
 class App {
    public express: express.Application;
    constructor() {
       this.express = express();
       this.routes();
    }
    private routes():void {
       let router = express.Router();
       router.get('/', User.index);
       this.express.use('/', router);
    }
 }

export default new App().express;

./user/ctrl.ts

class User {
   public demo:string;
   constructor() {
      this.demo = "this is text";
   }

   public infox() {
       console.log("demoo test : ", this.demo);
   }

   public index(req:any, res:any) {
       console.log(this) // output: undefined
       this.infox(); // throw an error.
   }
}

const user = new User();
export default user;

Server run at port 3000.

Any suggestion??


问:
Sort RDD according to an Array() content
I have RDD[(Int , Array[Double])]
eg:

```<code>1, Array(2.0,5.0,6.3)
5, Array(1.0,3.3,9.5)
1, Array(5.0,4.2,3.1)
2, Array(9.6,6.3,2.3)
1, Array(8.5,2.5,1.2)
5, Array(6.0,2.4,7.8)
2, Array(7.8,9.1,4.2)
</code>```

I have to collect the distinct value of the 1st column and arrange the whole RDD according to that array.

```<code>val label_array = rdd.map(_._1).collect.distinct
</code>```

Output: Array(1,5,2) and now I have to arrange data according to label_array.

Required Output

```<code>1, Array(2.0,5.0,6.3)
1, Array(5.0,4.2,3.1)
1, Array(8.5,2.5,1.2)
5, Array(1.0,3.3,9.5)
5, Array(6.0,2.4,7.8)
2, Array(9.6,6.3,2.3)
2, Array(7.8,9.1,4.2)
</code>```

I have tried

```<code>val ordering = (1,5,2).productIterator.toList.zipWithIndex.toMap
rdd.sortBy{case (k,v) => ordering(k)}
</code>```

But how to get the required output as the Array will be varying(elements and size difference). How can I sort RDD according to array format?

答:
More easier way is to create a new RDD with distinct 1st column and join with the previous original column

Below is the simple example

```<code>val rdd = spark.sparkContext.parallelize(Seq(
        (1, Array(2.0,5.0,6.3)),
        (5, Array(1.0,3.3,9.5)),
        (1, Array(5.0,4.2,3.1)),
        (2, Array(9.6,6.3,2.3)),
        (1, Array(8.5,2.5,1.2)),
        (5, Array(6.0,2.4,7.8)),
        (2, Array(7.8,9.1,4.2))
      )
    )

    val distinct = rdd.map(v => (v._1, 1))distinct()
    //(v._1, 1)this is done because you need key value to join

    //now join distinct with previous original RDD
    distinct.join(rdd).map(v => (v._1, v._2._2))
</code>```

Output:

```<code>1, Array(2.0,5.0,6.3)
1, Array(5.0,4.2,3.1)
1, Array(8.5,2.5,1.2)
5, Array(1.0,3.3,9.5)
5, Array(6.0,2.4,7.8)
2, Array(9.6,6.3,2.3)
2, Array(7.8,9.1,4.2)
</code>```

Body:
I have RDD[(Int , Array[Double])]
eg:

1, Array(2.0,5.0,6.3)
5, Array(1.0,3.3,9.5)
1, Array(5.0,4.2,3.1)
2, Array(9.6,6.3,2.3)
1, Array(8.5,2.5,1.2)
5, Array(6.0,2.4,7.8)
2, Array(7.8,9.1,4.2)

I have to collect the distinct value of the 1st column and arrange the whole RDD according to that array.

val label_array = rdd.map(_._1).collect.distinct

Output: Array(1,5,2) and now I have to arrange data according to label_array.

Required Output

1, Array(2.0,5.0,6.3)
1, Array(5.0,4.2,3.1)
1, Array(8.5,2.5,1.2)
5, Array(1.0,3.3,9.5)
5, Array(6.0,2.4,7.8)
2, Array(9.6,6.3,2.3)
2, Array(7.8,9.1,4.2)

I have tried

val ordering = (1,5,2).productIterator.toList.zipWithIndex.toMap
rdd.sortBy{case (k,v) => ordering(k)}

But how to get the required output as the Array will be varying(elements and size difference). How can I sort RDD according to array format?

Body:
More easier way is to create a new RDD with distinct 1st column and join with the previous original column

Below is the simple example

val rdd = spark.sparkContext.parallelize(Seq(
        (1, Array(2.0,5.0,6.3)),
        (5, Array(1.0,3.3,9.5)),
        (1, Array(5.0,4.2,3.1)),
        (2, Array(9.6,6.3,2.3)),
        (1, Array(8.5,2.5,1.2)),
        (5, Array(6.0,2.4,7.8)),
        (2, Array(7.8,9.1,4.2))
      )
    )

    val distinct = rdd.map(v => (v._1, 1))distinct()
    //(v._1, 1)this is done because you need key value to join

    //now join distinct with previous original RDD
    distinct.join(rdd).map(v => (v._1, v._2._2))

Output:

1, Array(2.0,5.0,6.3)
1, Array(5.0,4.2,3.1)
1, Array(8.5,2.5,1.2)
5, Array(1.0,3.3,9.5)
5, Array(6.0,2.4,7.8)
2, Array(9.6,6.3,2.3)
2, Array(7.8,9.1,4.2)


问:
How to make tensorflow oneHot in c++?
In my image detection python code i am using this

```<code>xlabel = tf.one_hot(1, nClass).eval()
</code>```

Now i am using c++ to get the model working on iOS.
Can anyone give me the c++ code snippet to which can do the same thing?
My aim is to get oneHot object whose size is lets say 60. on value is 1 and off value is 0.

答:
i couldn't do it from Tensorflow C++ direct API but i found a work around. If it can help someone else like me here it is:

```<code>std::vector<float> oneHotVec;
for(int i = 0; i < 62 ; i++)
{
    if (i == question)
        oneHotVec.push_back(1.0f);
    else
        oneHotVec.push_back(0.0f);
}
tensorflow::Tensor z(tensorflow::DT_FLOAT, tensorflow::TensorShape({1, 62}));
for (auto j = 0; j < 62; j++)
{
    z.matrix<float>().operator()(0, j) = oneHotVec.at(j);
}
</code>```

Here "z" is one hot vector that tensor needs.

Title: How to make tensorflow oneHot in c++?

Body:
In my image detection python code i am using this

xlabel = tf.one_hot(1, nClass).eval()

Now i am using c++ to get the model working on iOS.
Can anyone give me the c++ code snippet to which can do the same thing?
My aim is to get oneHot object whose size is lets say 60. on value is 1 and off value is 0.

Body:
i couldn't do it from Tensorflow C++ direct API but i found a work around. If it can help someone else like me here it is:

std::vector<float> oneHotVec;
for(int i = 0; i < 62 ; i++)
{
    if (i == question)
        oneHotVec.push_back(1.0f);
    else
        oneHotVec.push_back(0.0f);
}
tensorflow::Tensor z(tensorflow::DT_FLOAT, tensorflow::TensorShape({1, 62}));
for (auto j = 0; j < 62; j++)
{
    z.matrix<float>().operator()(0, j) = oneHotVec.at(j);
}

Here "z" is one hot vector that tensor needs.