问:
Create ActiveX checkbox in specific cell
In my Sheet 1, Column A has some values and I need to create a Active X checkbox for all the values in Sheet 2 in a specific cell. First I need to check whether Active X checkbox is there for the value or not, If its not there, I need to create. I already tried the below code, But its creating the duplicate checkboxes.

```<code>Sub Addcheckbox()
Dim rng As Range, cell As Range
Dim rr As Integer
Dim tf As Boolean
Dim shpTemp As Shape

Set rng = Range("A1:A8")
Set Destrng = Range("A2:A9")
rr = 2
For Each cell In Worksheets("Sheet1").Range("A1:A8")
    If Not IsEmpty(cell.Value) Then
     With ActiveSheet.OLEObjects.Add(ClassType:="Forms.CheckBox.1", _
        Left:=51.75, Top:=183, Width:=120, Height:=19.5)
        .Object.Caption = cell.Value
    End With
    End If
rr = rr + 1
Next cell
End Sub
</code>```

How to check whether ActiveX checkbox already present in the sheet or not with Caption name

i tried this code for checking the checkboxes.. But its not working..

```<code>Function shapeExists(ByRef shapename As String) As Boolean

    shapeExists = False
    Dim sh As Shape
    For Each sh In ActiveSheet.Shapes
        If sh.name = shapename Then
            shapeExists = True
            Exit Function
        End If
    Next sh

End Function
</code>```

答:
ActiveX Checkboxes are OleObjects. Is this what you are trying?

Also you need to specify the correct .Top else they will be created at the same place. See how I used Top:=cell.Top

```<code>Sub Sample()
    Dim rng As Range, cell As Range
    Dim rr As Integer
    Dim tf As Boolean
    Dim shpTemp As Shape

    Set rng = Range("A1:A8")
    Set Destrng = Range("A2:A9")

    rr = 2

    For Each cell In Worksheets("Sheet1").Range("A1:A8")
        If Not IsEmpty(cell.Value) Then
            If Not CBExists(cell.Value) Then '<~~ Check if the checkbox exists
                With ActiveSheet.OLEObjects.Add(ClassType:="Forms.CheckBox.1", _
                        Left:=51.75, Top:=cell.Top, Width:=120, Height:=19.5)
                        .Object.Caption = cell.Value
                End With
            End If
        End If
        rr = rr + 1
    Next cell
End Sub

'~~> Function to check if the checkbox exists
Function CBExists(s As String) As Boolean
    Dim oleObj As OLEObject
    Dim i As Long

    For i = 1 To Worksheets("Sheet1").OLEObjects.Count
        If s = Worksheets("Sheet1").OLEObjects(i).Object.Caption Then
            CBExists = True
            Exit Function
        End If
    Next i
End Function
</code>```

Body:
In my Sheet 1, Column A has some values and I need to create a Active X checkbox for all the values in Sheet 2 in a specific cell. First I need to check whether Active X checkbox is there for the value or not, If its not there, I need to create. I already tried the below code, But its creating the duplicate checkboxes.

Sub Addcheckbox()
Dim rng As Range, cell As Range
Dim rr As Integer
Dim tf As Boolean
Dim shpTemp As Shape

Set rng = Range("A1:A8")
Set Destrng = Range("A2:A9")
rr = 2
For Each cell In Worksheets("Sheet1").Range("A1:A8")
    If Not IsEmpty(cell.Value) Then
     With ActiveSheet.OLEObjects.Add(ClassType:="Forms.CheckBox.1", _
        Left:=51.75, Top:=183, Width:=120, Height:=19.5)
        .Object.Caption = cell.Value
    End With
    End If
rr = rr + 1
Next cell
End Sub

How to check whether ActiveX checkbox already present in the sheet or not with Caption name

i tried this code for checking the checkboxes.. But its not working..

Function shapeExists(ByRef shapename As String) As Boolean

    shapeExists = False
    Dim sh As Shape
    For Each sh In ActiveSheet.Shapes
        If sh.name = shapename Then
            shapeExists = True
            Exit Function
        End If
    Next sh

End Function

Body:
ActiveX Checkboxes are OleObjects. Is this what you are trying?

Also you need to specify the correct .Top else they will be created at the same place. See how I used Top:=cell.Top

Sub Sample()
    Dim rng As Range, cell As Range
    Dim rr As Integer
    Dim tf As Boolean
    Dim shpTemp As Shape

    Set rng = Range("A1:A8")
    Set Destrng = Range("A2:A9")

    rr = 2

    For Each cell In Worksheets("Sheet1").Range("A1:A8")
        If Not IsEmpty(cell.Value) Then
            If Not CBExists(cell.Value) Then '<~~ Check if the checkbox exists
                With ActiveSheet.OLEObjects.Add(ClassType:="Forms.CheckBox.1", _
                        Left:=51.75, Top:=cell.Top, Width:=120, Height:=19.5)
                        .Object.Caption = cell.Value
                End With
            End If
        End If
        rr = rr + 1
    Next cell
End Sub

'~~> Function to check if the checkbox exists
Function CBExists(s As String) As Boolean
    Dim oleObj As OLEObject
    Dim i As Long

    For i = 1 To Worksheets("Sheet1").OLEObjects.Count
        If s = Worksheets("Sheet1").OLEObjects(i).Object.Caption Then
            CBExists = True
            Exit Function
        End If
    Next i
End Function


来源: stackexchange

问:
JavaScript and AJAX not working as expected
I'm using the JavaScript and AJAX for signup form.

I want to post all textboxes in signup form through AJAX but am failing to do so.

signup.php

$(document).ready(function() {
  $('submit').click(function() {
    var first = $('#firstname').val();
    var last = $('#lastname').val();
    var Email = $('#email').val();
    var pass = $('#password').val();
    var confirm = $('#confirmpassword').val();
    var phone = $('#phoneno').val();

    $.ajax({
      type: "POST",
      url: "register.php",
      data: {
        (

          firstname: first,
          lastname: last,
          email: Email,
          password: pass,
          confirmpassword: confirm,
          phoneno: phone,

        )
      },
      success: function(data) {
        alert('passed');
      },
      error: function() {
        alert("error");
      }

    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="jquery-3.2.0.min.js"></script>
<title>
</title>

<div align="right">
</div>
<div id="div">
  <center>
    <h3>REGISTER</h3>
  </center>
  <table>
    <thead>
    </thead>
    <tbody>
      <tr>
        <td>
          <label>Firstname</label>
          <td>
            <input type="text" name="firstname" id="firstname" required="">
          </td>
      </tr>
      <tr>
        <td>
          <label>Lastname</label>
        </td>
        <td>
          <input type="text" name="lastname" id="lastname" required="">
        </td>
      </tr>
      <tr>
        <td>
          <label>Email</label>
        </td>
        <td>
          <input type="text" name="email" id="email" required="">
        </td>
      </tr>
      <tr>
        <td>
          <label>Password</label>
        </td>
        <td>
          <input type="password" name="password" id="password" required="">
        </td>
      </tr>
      <tr>
        <td>
          <label>Confirm password</label>
        </td>
        <td>
          <input type="password" name="confirmpassword" id="confirmpassword" required="">
        </td>
      </tr>
      <tr>
        <td>
          <label>Phone no</label>
        </td>
        <td>
          <input type="text" name="phoneno" id="phoneno" required="">
        </td>
      </tr>
      <tr>
        <td>
        </td>
        <td>
          <input type="button" name="submit" value="submit" id="submit" />
        </td>
      </tr>
      <tr>
        <td>
        </td>
        <td>
        </td>
        <td>
          Login?
        </td>
      </tr>
    </tbody>
  </table>
</div></code>```

register.php

```<code><?php
include 'config.php';
 $firstname=$_POST['firstname'];
 $lastname= $_POST['lastname'];
 $email=$_POST['email'];
 $password=$_POST['password'];
 $confirmpassword=$_POST['confirmpassword'];
 $phoneno=$_POST['phoneno'];
if($password==$confirmpassword)
{
$insertuser=mysql_query("insert into register(firstname,lastname,email,password,confirmpassword,phoneno) values('$firstname','$lastname','$email','$password','$confirmpassword','$phoneno')",$conn)or die(mysql_error());
echo "success";

}
else
{
  echo "failure";

 }
?>
</code>```

答:
replace your data from jquery as follows

```<code>data: {( firstname: first,
          lastname: last,
          email: Email,
          password: pass,
          confirmpassword: confirm,
          phoneno: phone,
        )
      }
</code>```

remove the ()

```<code>data:{
   firstname: first,
   lastname: last,
   email: Email,
   password: pass,
   confirmpassword: confirm,
   phoneno: phone
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using the JavaScript and AJAX for signup form.

I want to post all textboxes in signup form through AJAX but am failing to do so.

signup.php

$(document).ready(function() {
  $('submit').click(function() {
    var first = $('#firstname').val();
    var last = $('#lastname').val();
    var Email = $('#email').val();
    var pass = $('#password').val();
    var confirm = $('#confirmpassword').val();
    var phone = $('#phoneno').val();

    $.ajax({
      type: "POST",
      url: "register.php",
      data: {
        (

          firstname: first,
          lastname: last,
          email: Email,
          password: pass,
          confirmpassword: confirm,
          phoneno: phone,

        )
      },
      success: function(data) {
        alert('passed');
      },
      error: function() {
        alert("error");
      }

    });
  });
});

<title>
</title>

REGISTER

          Firstname

            <input type="text" name="firstname" id="firstname" required="">

          Lastname

          <input type="text" name="lastname" id="lastname" required="">

          Email

          <input type="text" name="email" id="email" required="">

          Password

          <input type="password" name="password" id="password" required="">

          Confirm password

          <input type="password" name="confirmpassword" id="confirmpassword" required="">

          Phone no

          <input type="text" name="phoneno" id="phoneno" required="">

          <input type="button" name="submit" value="submit" id="submit" />

          Login?

register.php

<?php
include 'config.php';
 $firstname=$_POST['firstname'];
 $lastname= $_POST['lastname'];
 $email=$_POST['email'];
 $password=$_POST['password'];
 $confirmpassword=$_POST['confirmpassword'];
 $phoneno=$_POST['phoneno'];
if($password==$confirmpassword)
{
$insertuser=mysql_query("insert into register(firstname,lastname,email,password,confirmpassword,phoneno) values('$firstname','$lastname','$email','$password','$confirmpassword','$phoneno')",$conn)or die(mysql_error());
echo "success";

}
else
{
  echo "failure";

 }
?>

Body:
replace your data from jquery as follows

data: {( firstname: first,
          lastname: last,
          email: Email,
          password: pass,
          confirmpassword: confirm,
          phoneno: phone,
        )
      }

remove the ()

data:{
   firstname: first,
   lastname: last,
   email: Email,
   password: pass,
   confirmpassword: confirm,
   phoneno: phone
}


问:
How to use a non-git repository as a dependency for a git project?
I have a project on GitHub that uses ncurses. How would I add ncurses as a dependency, seeing as the ncurses source code doesn't have an official repository on GitHub? The source code is in the form of gzip tar of course.</p>

答:
If you really needed source dependencies to ncurses, you can find mirrors on GitHub.

For instance, https://github.com/mirror/ncurses.

The best practice would be to declare a binary dependency, or, as suggesting, simply checking if ncurses is installed:

at least a script, like ls -la /usr/include/ncurses.h

or a configure.ac, which is then used by automake to generate a Makefile.


问:
Sorting a pre-defined list of names
I'm working on Chapter 8 Challenge 3 from C Programming for the Absolute Beginner 2nd Edition. The program is supposed to sort an array of names alphabetically.

My program doesn't work. The main function without sort() works, but the sort function is messed up; also strcmp() seems to be used incorrectly, based on warning messages.

The compiler I'm using is gcc and I wrote the code with nano.

```<code>/* Uses strcmp() in a different function
   to sort a list of names in alphabetical order */

#include <stdio.h>
#include <string.h>

void sort(char*, int);

void main() {
    char strStates[4][11] = { "Florida", "Oregon", "California", "Georgia" };
    sort(*strStates, 4); // 4 is the number of string in the array

    printf("\nFour States Listed in Alphabetical Order\n");

    int x;
    for(x = 0; x < 4; x++)
        printf("\n%s", strStates[x]);
}

void sort(char* strNames, int iStrings) {
    char strPlaceholder[11] = { 0 };
    int x;
    int y;

    for(x = 0; x < iStrings; x++) {
        for(y = 0; y < iStrings - 1; y++) {
            if(strcmp(strNames[y], strNames[y + 1]) > 0) {
                strcpy(strPlaceholder, strNames[y + 1]);
                strcpy(strNames[y + 1], strNames[y]);
                strcpy(strNames[y], strPlaceholder);
            }
        }
    }
}
</code>```

答:
Not meant as an answer but as a hint to let you get forward. A two dimensional array like char[4][11] is something different than a pointer to a (sequences of) characters like char*.

Suppose the following code:

```<code>char *s = "Florida"; // lets pointer 's' point to a sequence of characters, i.e. { 'F', 'l', 'o', 'r', 'i', 'd', 'a', '\0' }
char arr[2][11] = { "Florida", "New York" };
</code>```

Then an expression like s[1] is equivalent to *(s + sizeof(char)), which is *(s+1), whereas an expression like arr[1] is equivalent to *(arr + sizeof(char[11])), which is *(arr + 11), not *(arr + 1). The "sizeof"-part is done by the compiler and is derived from the type of the variable. Hence an argument of type char* behaves different than an argument of type char[11].

The following code might help you forward:

```<code>void print (char array[][11], int n) {

    for(int i=0;i<n;i++)
        printf("%d:%s\n",i,array[i]);
}

int main() {

    char strStates[4][11] = { "aer", "adf", "awer", "aert" };
    print (strStates,4);

    return 0;
}
</code>```

Title: Sorting a pre-defined list of names

Body:
I'm working on Chapter 8 Challenge 3 from C Programming for the Absolute Beginner 2nd Edition. The program is supposed to sort an array of names alphabetically.

My program doesn't work. The main function without sort() works, but the sort function is messed up; also strcmp() seems to be used incorrectly, based on warning messages.

The compiler I'm using is gcc and I wrote the code with nano.

/* Uses strcmp() in a different function
   to sort a list of names in alphabetical order */

#include <stdio.h>
#include <string.h>

void sort(char*, int);

void main() {
    char strStates[4][11] = { "Florida", "Oregon", "California", "Georgia" };
    sort(*strStates, 4); // 4 is the number of string in the array

    printf("\nFour States Listed in Alphabetical Order\n");

    int x;
    for(x = 0; x < 4; x++)
        printf("\n%s", strStates[x]);
}

void sort(char* strNames, int iStrings) {
    char strPlaceholder[11] = { 0 };
    int x;
    int y;

    for(x = 0; x < iStrings; x++) {
        for(y = 0; y < iStrings - 1; y++) {
            if(strcmp(strNames[y], strNames[y + 1]) > 0) {
                strcpy(strPlaceholder, strNames[y + 1]);
                strcpy(strNames[y + 1], strNames[y]);
                strcpy(strNames[y], strPlaceholder);
            }
        }
    }
}

Body:
Not meant as an answer but as a hint to let you get forward. A two dimensional array like char[4][11] is something different than a pointer to a (sequences of) characters like char*.

Suppose the following code:

char *s = "Florida"; // lets pointer 's' point to a sequence of characters, i.e. { 'F', 'l', 'o', 'r', 'i', 'd', 'a', '\0' }
char arr[2][11] = { "Florida", "New York" };

Then an expression like s[1] is equivalent to *(s + sizeof(char)), which is *(s+1), whereas an expression like arr[1] is equivalent to *(arr + sizeof(char[11])), which is *(arr + 11), not *(arr + 1). The "sizeof"-part is done by the compiler and is derived from the type of the variable. Hence an argument of type char* behaves different than an argument of type char[11].

The following code might help you forward:

void print (char array[][11], int n) {

    for(int i=0;i<n;i++)
        printf("%d:%s\n",i,array[i]);
}

int main() {

    char strStates[4][11] = { "aer", "adf", "awer", "aert" };
    print (strStates,4);

    return 0;
}


问:
Move object forward in facing direction
basically I am trying to make my character dash forward a specific distance in the direction the camera is facing. This a fps and the best I have been able to do so face is dash forward in the global X axes, which obviously is wrong.

I have this function which is called from the update function:

```<code>Debug.Log("We are dashing.");

    if (!inputDash || !canControl)
        dashing.lastButtonDownTime = -100;

    if (inputDash && dashing.lastButtonDownTime < 0 && canControl)
        dashing.lastButtonDownTime = Time.time;

    if (dashing.enabled && canControl && (Time.time - dashing.lastButtonDownTime < 0.2))
    {
        dashing.dashing = true;
        dashing.lastButtonDownTime = -100;
        dashing.dashCounter ++;

        dashing.dashDir = Camera.mainCamera.transform.position;

        //velocity = Vector3.MoveTowards(dashing.dashDir, (dashing.dashDir + Vector3(dashing.dashDir.x + 2, 0, 0)), (2 * Time.deltaTime));

        Debug.Log("We just dashed.");
    }

    return velocity;
</code>```

I have tried a number of different things for the dashing.dashDir, but none have worked. I know I am bascially looking to dash in the local axes of the camera?

I have also tried this:

```<code>dashing.dashDir = Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
velocity += dashing.dashDir * dashing.baseDistance;
</code>```

Any help would be greatly appreciated as this is driving me insane.

Final point. I am looking to dash the player very quickly forward in the facing direction approximately 3m and then carry to velocity when the dash finishes. Sorry if that's unclear.

答:
Here is my answer and it works perfectly: Moves forward, Rotates and Collides with Other objects (Having RigidBody and Box/Capsule Collider). tThis is based from Burkhard's answer.

But befor all do this : Create an empty Object set it a child of your Player and drag your camera Object into your empty Object.

NB : You can place the camera behind your player to get a best view.

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

  public class CubeControl : MonoBehaviour {

    public float speed = 10.0f;
    Rigidbody rb;
    GameObject playerEmpty;
    // Use this for initialization
    void Start () {

        rb = GetComponent<Rigidbody> ();

    }

    // Update is called once per frame
    void Update () {

        float Haxis = Input.GetAxis ("Horizontal");
        float Vaxis = Input.GetAxis ("Vertical");

        //Go Forward
        if(Input.GetKeyDown(KeyCode.UpArrow))
            {

                //Works perfectly but does no longer collide
                //rb.transform.position += transform.forward * Time.deltaTime * 10.0f;
               //Not moving in the right direction
                //rb.velocity += Vector3.forward * 5.0f;

              rb.velocity += Camera.main.transform.forward * speed;

            //rb.rotation() += new Vector3 (0.0f, headingAngle, 0.0f) * 5.0f;
            //rb.velocity += gameObject.transform.localEulerAngles * Time.deltaTime * 10.0f ;
            }
        if(Input.GetKeyDown(KeyCode.DownArrow))
            {
                rb.velocity -= Camera.main.transform.forward * speed;
            }
            Vector3 rotationAmount = Vector3.Lerp(Vector3.zero, new Vector3(0f, 10.0f * (Haxis < 0f ? -1f : 1f), 0f), Mathf.Abs(Haxis));
            Quaternion deltaRotation = Quaternion.Euler(rotationAmount * Time.deltaTime);
            this.transform.rotation = (this.transform.rotation * deltaRotation);

    }
}
</code>```

Title: Move object forward in facing direction

Body:
basically I am trying to make my character dash forward a specific distance in the direction the camera is facing. This a fps and the best I have been able to do so face is dash forward in the global X axes, which obviously is wrong.

I have this function which is called from the update function:

Debug.Log("We are dashing.");

    if (!inputDash || !canControl)
        dashing.lastButtonDownTime = -100;

    if (inputDash && dashing.lastButtonDownTime < 0 && canControl)
        dashing.lastButtonDownTime = Time.time;

    if (dashing.enabled && canControl && (Time.time - dashing.lastButtonDownTime < 0.2))
    {
        dashing.dashing = true;
        dashing.lastButtonDownTime = -100;
        dashing.dashCounter ++;

        dashing.dashDir = Camera.mainCamera.transform.position;

        //velocity = Vector3.MoveTowards(dashing.dashDir, (dashing.dashDir + Vector3(dashing.dashDir.x + 2, 0, 0)), (2 * Time.deltaTime));

        Debug.Log("We just dashed.");
    }

    return velocity;

I have tried a number of different things for the dashing.dashDir, but none have worked. I know I am bascially looking to dash in the local axes of the camera?

I have also tried this:

dashing.dashDir = Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
velocity += dashing.dashDir * dashing.baseDistance;

Any help would be greatly appreciated as this is driving me insane.

Final point. I am looking to dash the player very quickly forward in the facing direction approximately 3m and then carry to velocity when the dash finishes. Sorry if that's unclear.

Body:
Here is my answer and it works perfectly: Moves forward, Rotates and Collides with Other objects (Having RigidBody and Box/Capsule Collider). tThis is based from Burkhard's answer.

But befor all do this : Create an empty Object set it a child of your Player and drag your camera Object into your empty Object.

NB : You can place the camera behind your player to get a best view.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

  public class CubeControl : MonoBehaviour {

    public float speed = 10.0f;
    Rigidbody rb;
    GameObject playerEmpty;
    // Use this for initialization
    void Start () {

        rb = GetComponent<Rigidbody> ();

    }

    // Update is called once per frame
    void Update () {

        float Haxis = Input.GetAxis ("Horizontal");
        float Vaxis = Input.GetAxis ("Vertical");

        //Go Forward
        if(Input.GetKeyDown(KeyCode.UpArrow))
            {

                //Works perfectly but does no longer collide
                //rb.transform.position += transform.forward * Time.deltaTime * 10.0f;
               //Not moving in the right direction
                //rb.velocity += Vector3.forward * 5.0f;

              rb.velocity += Camera.main.transform.forward * speed;

            //rb.rotation() += new Vector3 (0.0f, headingAngle, 0.0f) * 5.0f;
            //rb.velocity += gameObject.transform.localEulerAngles * Time.deltaTime * 10.0f ;
            }
        if(Input.GetKeyDown(KeyCode.DownArrow))
            {
                rb.velocity -= Camera.main.transform.forward * speed;
            }
            Vector3 rotationAmount = Vector3.Lerp(Vector3.zero, new Vector3(0f, 10.0f * (Haxis < 0f ? -1f : 1f), 0f), Mathf.Abs(Haxis));
            Quaternion deltaRotation = Quaternion.Euler(rotationAmount * Time.deltaTime);
            this.transform.rotation = (this.transform.rotation * deltaRotation);

    }
}


问:
Save audio file from app to iPad/iPhone library
I have been trying to figure out how to do this for most of the day, but I haven't been able to find much help. We have this multimedia app that allows users to view pictures, videos, and music/ringtones about the particular subject. I know you can save images using UIImageWriteToSavedPhotosAlbum and you can save a video file using UISaveVideoAtPathToSavedPhotosAlbum. But I can't figure out how to allow the user to save an audio file. All the files are stored within the app, so its not like I'm trying to stream or download them from the internet. Does anyone have any pointers on how to do this?

答: The official SDK only allows you to retrieve information with MPMediaLibrary, no write access.

ContentLicense: CC BY-SA 2.5


问:
How to Clear/Reset formData() using javascript?
I am using formData for Ajax Image Uploading, when I am submit first time it will successfully upload, and again click post button that image also posted to server, I think formData will not clear.

My Code

```<code>$("#postsubmitimage").click(function () {
                var formData = new FormData();
                for (var i = 0; i < files.length; i++) {
                    if (files[i].type.indexOf('image/') === 0) {
                        formData.append("files", files[i]);
                    }
                }
                    $.ajax({
                        type: "POST",
                        url: '/Ajax/Fileupload/',
                        data: formData,
                        dataType: 'json',
                        contentType: false,
                        processData: false,
                        success: function (json) {
                            $('#textpostimage').val('');
                        }
                    });
            })
</code>```

答:
Have you tried doing it this way?

var formData = new FormData($('<form></form>'));

Body:
I am using formData for Ajax Image Uploading, when I am submit first time it will successfully upload, and again click post button that image also posted to server, I think formData will not clear.

My Code

$("#postsubmitimage").click(function () {
                var formData = new FormData();
                for (var i = 0; i < files.length; i++) {
                    if (files[i].type.indexOf('image/') === 0) {
                        formData.append("files", files[i]);
                    }
                }
                    $.ajax({
                        type: "POST",
                        url: '/Ajax/Fileupload/',
                        data: formData,
                        dataType: 'json',
                        contentType: false,
                        processData: false,
                        success: function (json) {
                            $('#textpostimage').val('');
                        }
                    });
            })


问:
What is a docker-compose.yml file?
I can't find a real definition of what a docker-compose file is.

Is it correct to say this:

A docker-compose file is a YAML file that allows us to deploy multiples Docker containers at the same time.

I'd like to be able to explain a bit better what a docker-compose file is.

答:
Docker Compose is a tool that allows you to deploy and manage multiple containers at the same time.

A docker-compose.yml file contains instructions on how to do that.

In this file, you instruct Docker Compose for example to:

From where to take the Dockerfile to build a particular image

Which ports you want to expose

How to link containers

Which ports you want to bind to the host machine

Docker Compose reads that file and executes commands.

It is used instead of all optional parameters when building and running a single docker container.

Example:

```<code>version: '2'
services:
  nginx:
      build: ./nginx
      links:
          - django:django
          - angular:angular
      ports:
          - "80:80"
          - "8000:8000"
          - "443:443"
      networks:
       - my_net
  django:
      build: ./django
      expose:
          - "8000"
      networks:
       - my_net
  angular:
      build: ./angular2
      links:
          - django:django
      expose:
          - "80"
      networks:
        - my_net
networks:
  my_net:
    external:
      name: my_net
</code>```

This example instructs Docker Compose to:

Build nginx from path ./nginx

Links angular and django containers (so their IP in the Docker network is resolved by name)

Binds ports 80, 443, 8000 to the host machine

Add it to network my_net

(so all 3 containers are in the same network and therefore accessible from each other)

Then something similar is done for the django and angular containers.

If you would use just Docker commands, it would be something like:

```<code>docker build --name nginx .
docker run --link django:django angular:angular --expose 80 443 8000 --net my_net nginx
</code>```

So while you probably don't want to type all these options and commands for each image/container, you can write a docker-compose.yml file in which you write all these instructions in a human-readable format.

ContentLicense: CC BY-SA 4.0

Title: What is a docker-compose.yml file?

Body:
Docker Compose is a tool that allows you to deploy and manage multiple containers at the same time.

A docker-compose.yml file contains instructions on how to do that.

In this file, you instruct Docker Compose for example to:

From where to take the Dockerfile to build a particular image

Which ports you want to expose

How to link containers

Which ports you want to bind to the host machine

Docker Compose reads that file and executes commands.

It is used instead of all optional parameters when building and running a single docker container.

Example:

version: '2'
services:
  nginx:
      build: ./nginx
      links:
          - django:django
          - angular:angular
      ports:
          - "80:80"
          - "8000:8000"
          - "443:443"
      networks:
       - my_net
  django:
      build: ./django
      expose:
          - "8000"
      networks:
       - my_net
  angular:
      build: ./angular2
      links:
          - django:django
      expose:
          - "80"
      networks:
        - my_net
networks:
  my_net:
    external:
      name: my_net

This example instructs Docker Compose to:

Build nginx from path ./nginx

Links angular and django containers (so their IP in the Docker network is resolved by name)

Binds ports 80, 443, 8000 to the host machine

Add it to network my_net

(so all 3 containers are in the same network and therefore accessible from each other)

Then something similar is done for the django and angular containers.

If you would use just Docker commands, it would be something like:

docker build --name nginx .
docker run --link django:django angular:angular --expose 80 443 8000 --net my_net nginx

So while you probably don't want to type all these options and commands for each image/container, you can write a docker-compose.yml file in which you write all these instructions in a human-readable format.


问:
How to handle dependent class and avoid type checking when using common base class as function parameter?
We have a tree of objects of different types derive from a common tree node and We want to write a method to render complete tree. We are using different renderer based on UI selected Eg.. text Renderer, 2d renderer, 3d renderer. Our tree is our model and we don't want to put in rendering code inside it. so, we decided to create separate rendering code.
Our renderer have a method RenderNode(TreeNode node) that takes reference of base class TreeNode. Since, we need to work with various different kind of node, we are type checking for each tree node type and rendering it.

```<code>void RenderNode(TreeNode node) {
    if(node is NoEditNode){
        // call Derive class RenderEditNode
        RenderEditNode(node);
    }
    else if (node is PersonNode){
        // call Derive class RenderPersonNode
        RenderPersonNode(node);
    }
    else if (node is AssetNode){
        // call Derive class RenderAssetNode
        RenderAssetNode(node);
    }
    .
    .
    .
}
</code>```

Even though this is done in base class and derived Renderer will just implement specific rendering code, this is not a good OO design. In case I add a new Tree node I'll need to change all renderer and to avoid this situation we need to add render code to tree node itself which will again need to be sync when a new renderer is introduced.
So we have multiple kind of tree node and multiple kind of renderer. How can we design this to avoid type checking and avoid change one class if a new kind of another class.

答:
Take a look at the visitor pattern. The visitor design pattern is a way of separating an algorithm from an object structure on which it operates.

Bacisly you create a seperate class for each implentetion of a render alogritm and inject that class into the TreeNode derived classes.

Here is an example of an implementation:

```<code>public interface IRenderer
{
    void Render(TreeNode node);
}

class NoEditNode : TreeNode
{
    IRenderer renderer = new RenderEditNode();
    public void Render()
    {
        renderer.Render(this);
    }
}

class RenderEditNode :  IRenderer
{
    public void Render(TreeNode node)
    {
    /*
    ...
    */
    }
}

class PersonNode : TreeNode
{
    IRenderer renderer;

    public PersonNode(IRenderer renderer)
    {
        this.renderer = renderer;
    }

    public void Render()
    {
        renderer.Render(this);
    }
}

class RenderPersonNode :  IRenderer
{
    public void Render(TreeNode node)
    {
        /*
        ...
        */
    }
}
</code>```

Body:
We have a tree of objects of different types derive from a common tree node and We want to write a method to render complete tree. We are using different renderer based on UI selected Eg.. text Renderer, 2d renderer, 3d renderer. Our tree is our model and we don't want to put in rendering code inside it. so, we decided to create separate rendering code.
Our renderer have a method RenderNode(TreeNode node) that takes reference of base class TreeNode. Since, we need to work with various different kind of node, we are type checking for each tree node type and rendering it.

void RenderNode(TreeNode node) {
    if(node is NoEditNode){
        // call Derive class RenderEditNode
        RenderEditNode(node);
    }
    else if (node is PersonNode){
        // call Derive class RenderPersonNode
        RenderPersonNode(node);
    }
    else if (node is AssetNode){
        // call Derive class RenderAssetNode
        RenderAssetNode(node);
    }
    .
    .
    .
}

Even though this is done in base class and derived Renderer will just implement specific rendering code, this is not a good OO design. In case I add a new Tree node I'll need to change all renderer and to avoid this situation we need to add render code to tree node itself which will again need to be sync when a new renderer is introduced.
So we have multiple kind of tree node and multiple kind of renderer. How can we design this to avoid type checking and avoid change one class if a new kind of another class.

Body:
Take a look at the visitor pattern. The visitor design pattern is a way of separating an algorithm from an object structure on which it operates.

Bacisly you create a seperate class for each implentetion of a render alogritm and inject that class into the TreeNode derived classes.

Here is an example of an implementation:

public interface IRenderer
{
    void Render(TreeNode node);
}

class NoEditNode : TreeNode
{
    IRenderer renderer = new RenderEditNode();
    public void Render()
    {
        renderer.Render(this);
    }
}

class RenderEditNode :  IRenderer
{
    public void Render(TreeNode node)
    {
    /*
    ...
    */
    }
}

class PersonNode : TreeNode
{
    IRenderer renderer;

    public PersonNode(IRenderer renderer)
    {
        this.renderer = renderer;
    }

    public void Render()
    {
        renderer.Render(this);
    }
}

class RenderPersonNode :  IRenderer
{
    public void Render(TreeNode node)
    {
        /*
        ...
        */
    }
}


问:
Alert opens every time and not only the first time
I want my alert to only open the first time the app is launched on a new device but it currently opens every time the app is closed in multitasking and opened again. I have attached my code if anyone is able to help please?</p>

```<code>    override func viewDidAppear(_ animated: Bool) {
        // alert first time app is opened
        // making of alert

        let alert = UIAlertController(title: "Navigation", message: "Tap Right Hand Side of Screen For Next Quote, Left Hand Side To Go Back", preferredStyle: UIAlertControllerStyle.alert)

        //add ok button
        alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: nil))

        // detect if first launch
        let launchedBefore = UserDefaults.standard.bool(forKey: "launcedBefore")
        if launchedBefore {
        }
        else {
            self.present(alert, animated: true, completion: nil)
            UserDefaults.standard.set(true, forKey: "launchedBefore")
        }
    }
</code>```

答:
This is the reason why I hate using UserDefaults. Sometimes you make typos and you can't tell where it's happening.

The best way to use UserDefaults is to create all the keys into constants, so your two lines accessing UserDefaults would look something cleaner like this:

```<code>let launchedBefore = UserDefaults.standard.bool(forKey: kLaunchedBeforeKey)
</code>```

and

```<code>UserDefaults.standard.set(true, forKey: kLaunchedBeforeKey)
</code>```

This way the compiler will let you know in case you make a typo.

Body:
I want my alert to only open the first time the app is launched on a new device but it currently opens every time the app is closed in multitasking and opened again. I have attached my code if anyone is able to help please?

    override func viewDidAppear(_ animated: Bool) {
        // alert first time app is opened
        // making of alert

        let alert = UIAlertController(title: "Navigation", message: "Tap Right Hand Side of Screen For Next Quote, Left Hand Side To Go Back", preferredStyle: UIAlertControllerStyle.alert)

        //add ok button
        alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: nil))

        // detect if first launch
        let launchedBefore = UserDefaults.standard.bool(forKey: "launcedBefore")
        if launchedBefore {
        }
        else {
            self.present(alert, animated: true, completion: nil)
            UserDefaults.standard.set(true, forKey: "launchedBefore")
        }
    }

Body:
This is the reason why I hate using UserDefaults. Sometimes you make typos and you can't tell where it's happening.

The best way to use UserDefaults is to create all the keys into constants, so your two lines accessing UserDefaults would look something cleaner like this:

let launchedBefore = UserDefaults.standard.bool(forKey: kLaunchedBeforeKey)

and

UserDefaults.standard.set(true, forKey: kLaunchedBeforeKey)

This way the compiler will let you know in case you make a typo.


问:
issue with angular2 routing
i have an issue using Angular2 routings , i build an application with three buttons , each button takes me to a specific route.
This is my app-routing.module page :

/***** importation Components****/
import {NgModule} from '@angular/core';

import {DashboardComponent} from './dashboard/dashboard.component';
import {PlayersComponent} from './players/players.component';
import {PlayerDetailsComponent} from './player-details/player-details.component';
import {RouterModule,Routes} from '@angular/router';

const routes : Routes=[
{ path : '',redirectTo:'dashboard',pathMatch: 'full'},
{ path: 'dashboard',component:DashboardComponent},
{ path: 'players',component:PlayersComponent},
{ path: 'detail/:id',component:PlayerDetailsComponent}

] ;

@NgModule({
   imports: [ RouterModule.forRoot(routes) ],
     exports: [ RouterModule ]

})
export class AppRoutingModule {}```
</div>
</div>
</p>

<p>This is my app.component.html page that containes the buttons :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="nav nav-pills nav-justified" >
   <li class="element" role="presentation"  >Dashboard</li>
  <li class="element" role="presentation" >Players</li>
  <li class="element" role="presentation" >Statistics</li>
</ul>
<router-outlet></router-outlet></code>```

My app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
/***********Importation Components********************/
import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { PlayersComponent } from './players/players.component';
import { PlayerDetailsComponent } from './player-details/player-details.component';

/*****Importaion Service*******************************/
import {PlayerService} from './player.service';
/**** Importation fichier routing**************/
import {AppRoutingModule} from './app-routing.module';

@NgModule({
  declarations: [
    AppComponent,
    DashboardComponent,
    PlayersComponent,
    PlayerDetailsComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [PlayerService],
  bootstrap: [AppComponent]
})
export class AppModule { }```
</div>
</div>
</p>

<p>and when i click a button it dosen't take me to component i want , On the other hand if i type the path in adress bar it take me to the component adequate .
i guess my routing version is this : </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>"scripts": {},
  "typings": "./router.d.ts",
  "version": "4.1.3"
}</code>```

EDIT :
i found out that after removing recent updates i have done the routing starts working again.
Those are my 2 pages i have updated.
dashboard.component.html

import { Component, OnInit } from '@angular/core';
import {Player} from '../player';
import {PlayerService} from '../player.service';
import {Router} from '@angular/router';
@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
  players : Player[] = [];
 bestPlayer:Player;
 data:Player[];

max:number =0;
  constructor(private playerService : PlayerService ,private router: Router) { }

  ngOnInit() {

   this.playerService.getPlayers()
   .then(players=> this.players = players);
    this.data=this.playerService.getDatas();
  for (var i = 0; i <= this.data.length; i++) {
    if (this.data[i].likes>this.max) {
      this.max=this.data[i].likes;
      this.bestPlayer=this.data[i];

     }
  }

    }
    viewDetails(bestPlayer: Player):void{
      this.router.navigate(['/detail',this.bestPlayer.id]);

    }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container well-sm bloc" >
 <div class="row"><h1 style="font-family: 'Lobster', cursive;color: white"><span class="glyphicon glyphicon-star" style="color: #FFC153"></span> Player of the week is </h1> </div>
 <div >
 <h2>{{bestPlayer.name}} <span class="badge badge1">{{bestPlayer.number}}</span></h2>
 <h2>with : {{max}} Likes <span class="glyphicon glyphicon-heart " style="color: red"></span></h2>
 <br><button class="btn btn-success" (click)="viewDetails(bestPlayer)">View player details</button>
 </div>

</div></code>```

答:
I found out that an issue in my dashboard.component.ts is causing the problem.
i wrote a function that get and show the "best player" in my array of objects (the player who has more likes).
this is what the function looks like

 ngOnInit() {

   this.playerService.getPlayers()
   .then(players=> this.players = players);
    this.data=this.playerService.getDatas();
  for (var i = 0; i <= this.data.length; i++) {
    if (this.data[i].likes>this.max) {
      this.max=this.data[i].likes;
      this.bestPlayer=this.data[i];

     }
  }

    }
    viewDetails(bestPlayer: Player):void{
      this.router.navigate(['/detail',this.bestPlayer.id]);

    }```

when i run the app the browser show me an error function in the console "this.data[i] is undefined" but the app runs anyway.
when i delete this the router starts working again

Title: issue with angular2 routing

Body:
i have an issue using Angular2 routings , i build an application with three buttons , each button takes me to a specific route.
This is my app-routing.module page :

/***** importation Components****/
import {NgModule} from '@angular/core';

import {DashboardComponent} from './dashboard/dashboard.component';
import {PlayersComponent} from './players/players.component';
import {PlayerDetailsComponent} from './player-details/player-details.component';
import {RouterModule,Routes} from '@angular/router';

const routes : Routes=[
{ path : '',redirectTo:'dashboard',pathMatch: 'full'},
{ path: 'dashboard',component:DashboardComponent},
{ path: 'players',component:PlayersComponent},
{ path: 'detail/:id',component:PlayerDetailsComponent}

] ;

@NgModule({
   imports: [ RouterModule.forRoot(routes) ],
     exports: [ RouterModule ]

})
export class AppRoutingModule {}

This is my app.component.html page that containes the buttons :

Dashboard

Players

Statistics

<router-outlet></router-outlet>

My app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
/***********Importation Components********************/
import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { PlayersComponent } from './players/players.component';
import { PlayerDetailsComponent } from './player-details/player-details.component';

/*****Importaion Service*******************************/
import {PlayerService} from './player.service';
/**** Importation fichier routing**************/
import {AppRoutingModule} from './app-routing.module';

@NgModule({
  declarations: [
    AppComponent,
    DashboardComponent,
    PlayersComponent,
    PlayerDetailsComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [PlayerService],
  bootstrap: [AppComponent]
})
export class AppModule { }

and when i click a button it dosen't take me to component i want , On the other hand if i type the path in adress bar it take me to the component adequate .
i guess my routing version is this :

"scripts": {},
  "typings": "./router.d.ts",
  "version": "4.1.3"
}

EDIT :
i found out that after removing recent updates i have done the routing starts working again.
Those are my 2 pages i have updated.
dashboard.component.html

import { Component, OnInit } from '@angular/core';
import {Player} from '../player';
import {PlayerService} from '../player.service';
import {Router} from '@angular/router';
@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
  players : Player[] = [];
 bestPlayer:Player;
 data:Player[];

max:number =0;
  constructor(private playerService : PlayerService ,private router: Router) { }

  ngOnInit() {

   this.playerService.getPlayers()
   .then(players=> this.players = players);
    this.data=this.playerService.getDatas();
  for (var i = 0; i <= this.data.length; i++) {
    if (this.data[i].likes>this.max) {
      this.max=this.data[i].likes;
      this.bestPlayer=this.data[i];

     }
  }

    }
    viewDetails(bestPlayer: Player):void{
      this.router.navigate(['/detail',this.bestPlayer.id]);

    }

}

 Player of the week is

{{bestPlayer.name}} {{bestPlayer.number}}

with : {{max}} Likes

<button class="btn btn-success" (click)="viewDetails(bestPlayer)">View player details</button>

Body:
I found out that an issue in my dashboard.component.ts is causing the problem.
i wrote a function that get and show the "best player" in my array of objects (the player who has more likes).
this is what the function looks like

 ngOnInit() {

   this.playerService.getPlayers()
   .then(players=> this.players = players);
    this.data=this.playerService.getDatas();
  for (var i = 0; i <= this.data.length; i++) {
    if (this.data[i].likes>this.max) {
      this.max=this.data[i].likes;
      this.bestPlayer=this.data[i];

     }
  }

    }
    viewDetails(bestPlayer: Player):void{
      this.router.navigate(['/detail',this.bestPlayer.id]);

    }

when i run the app the browser show me an error function in the console "this.data[i] is undefined" but the app runs anyway.
when i delete this the router starts working again


问:
error while building the apk in android
This is the my build.gradle and when I build the apk by clicking on the build apk this error shown.I have seen the some of the queries before but not able to figure out the problem solution

Error:Execution failed for task ':app:transformClassesWithDexForDebug'.

com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.example.ranjeet.location"
        minSdkVersion 14
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.google.code.gson:gson:2.8.0'
    compile 'com.google.android.gms:play-services:10.2.6'
    compile 'com.google.android.gms:play-services-maps:10.2.6'
}
</code>```

答:
You have too many methods. There can only be 65536 methods for dex.

So, enable multidex as following:

```<code>android {

    defaultConfig {
        ...

        // Enabling multidex support.
        multiDexEnabled true
    }
    ...
}
</code>```

And paste this code as well,

```<code>dexOptions {
    javaMaxHeapSize "4g"
    preDexLibraries = false
}
</code>```

Title: error while building the apk in android

Body:
This is the my build.gradle and when I build the apk by clicking on the build apk this error shown.I have seen the some of the queries before but not able to figure out the problem solution

Error:Execution failed for task ':app:transformClassesWithDexForDebug'.

com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.example.ranjeet.location"
        minSdkVersion 14
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.google.code.gson:gson:2.8.0'
    compile 'com.google.android.gms:play-services:10.2.6'
    compile 'com.google.android.gms:play-services-maps:10.2.6'
}

Body:
You have too many methods. There can only be 65536 methods for dex.

So, enable multidex as following:

android {

    defaultConfig {
        ...

        // Enabling multidex support.
        multiDexEnabled true
    }
    ...
}

And paste this code as well,

dexOptions {
    javaMaxHeapSize "4g"
    preDexLibraries = false
}


问:
How do you do post request to Flask backend api using vue js?
I am trying to do simple signup process using vue js and flask back end.
But I get this error message.

XMLHttpRequest cannot load http://localhost:5000/users. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

Why is this happening?

My vue js code is following

```<code>methods: {

    signup() {

        this.$http.post("http://localhost:5000/users", this.user)
            .then(function(data) {
                alert(data)
            })
    }

}
</code>```

my flask back end code is following

```<code>@app.route('/users', methods=['POST'])
    def users():
    username = request.form.get('username')
    password1 = request.form.get('password1')
    password2 = request.form.get('password2')
    first_name = request.form.get('first_name')
    last_name = request.form.get('last_name')
    email = request.form.get('email')

    file = request.files['avatar']

    if file.filename:
        if allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'],
    filename))
        else:
            error = "Your avatar has be to an image file"
            redirect(url_for('signup'))
    else:
        filename = ""

    if password1 == password2:
        user = User(username = username, password = password1, first_name = first_name, last_name = last_name,  email = email)
        user.save_to_db()
</code>```

答:
You are serving your app over http://localhost:8080/ while your API is at http://localhost:5000 and these two are different origins for the browser!

From MDN

A resource makes a cross-origin HTTP request when it requests a resource from a different domain, protocol, or port to its own. For example, an HTML page served from http://domain-a.com makes an  src request for http://domain-b.com/image.jpg

For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example, XMLHttpRequest and Fetch follow the same-origin policy. So, a web application using XMLHttpRequest or Fetch could only make HTTP requests to its own domain.

The Cross-Origin Resource Sharing (CORS) mechanism gives web servers cross-domain access controls, which enable secure cross-domain data transfers. Modern browsers use CORS in an API container - such as XMLHttpRequest or Fetch - to mitigate risks of cross-origin HTTP requests.

In your case either use flask-cors or host your API on the same domain as your app.

Body:
I am trying to do simple signup process using vue js and flask back end.
But I get this error message.

XMLHttpRequest cannot load http://localhost:5000/users. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

Why is this happening?

My vue js code is following

methods: {

    signup() {

        this.$http.post("http://localhost:5000/users", this.user)
            .then(function(data) {
                alert(data)
            })
    }

}

my flask back end code is following

@app.route('/users', methods=['POST'])
    def users():
    username = request.form.get('username')
    password1 = request.form.get('password1')
    password2 = request.form.get('password2')
    first_name = request.form.get('first_name')
    last_name = request.form.get('last_name')
    email = request.form.get('email')

    file = request.files['avatar']

    if file.filename:
        if allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'],
    filename))
        else:
            error = "Your avatar has be to an image file"
            redirect(url_for('signup'))
    else:
        filename = ""

    if password1 == password2:
        user = User(username = username, password = password1, first_name = first_name, last_name = last_name,  email = email)
        user.save_to_db()


问:
how to remove clippings in konva?
There's a lot of docs on how to set clipX, clipY, clipFunc, etc.

But there's no doc on how to remove clippings.

Is there any standard way of removing a clippings?

答:
Just set undefined or null properties:

```<code>layer.clipX(undefined);
layer.clipY(undefined);
layer.clipWidth(undefined);
layer.clipHeight(undefined);
layer.draw();
</code>```

Demo: https://jsfiddle.net/sz0dm02b/

Title: how to remove clippings in konva?

Body:
Just set undefined or null properties:

layer.clipX(undefined);
layer.clipY(undefined);
layer.clipWidth(undefined);
layer.clipHeight(undefined);
layer.draw();

Demo: https://jsfiddle.net/sz0dm02b/


问:
How to know if Spork is running
I'm trying to speed up "rspecing" in a rails 2.3.8 app with spork. When I run spork in the root of the project I get:

```<code>(...stuff...)
No server is running
Running specs locally:
Spork is ready and listening on 8989!
</code>```

And then, if I run specs, the message

```<code> No server is running
 Running specs locally
</code>```

which appears if I run them without Spork doesn't appear, however spec startup is as slow as without Spork. Also in Spork's terminal no further output appears.

My question is, is spork actually running? If so, are the specs running there?, and finally, if the answer to both is true, how can I speed up my tests?

Here are the config files involved:

spec/spec.opts

```<code>  --colour
  --format progress
  --loadby mtime
  --reverse
  --drb
</code>```

spec/spec.helper

```<code>require 'rubygems'
require 'bundler/setup'
require 'spork'

Spork.prefork do

   ENV["RAILS_ENV"] ||= 'test'
   require File.expand_path(File.join(File.dirname(__FILE__),'..','config','environment'))
   require 'spec/autorun'
   require 'spec/rails'

   Dir[File.expand_path(File.join(File.dirname(__FILE__),'support','**','*.rb'))].each {|f| require f}

   Spec::Runner.configure do |config|
  end

 end

 Spork.each_run do

end
</code>```

And, to have a full question, here are the times measured with 'time':

With Spork:

```<code>real    0m39.524s
user    0m5.012s
sys  0m0.912s
</code>```

Without Spork:

```<code>real    0m39.576s
user    0m18.537s
sys  0m2.400s
</code>```

When running sport --diagnose I get

```<code> - Spork Diagnosis -
 -- Summary --
 config/boot.rb
 config/initializers/inflections.rb
 config/initializers/mime_types.rb
 config/initializers/new_rails_defaults.rb
 config/initializers/site_keys.rb
 config/preinitializer.rb
 spec/spec_helper.rb
</code>```

And then, for

```<code> --- config/initializers/inflections.rb ---
 --- config/initializers/mime_types.rb ---
 --- config/initializers/new_rails_defaults.rb ---
 --- config/initializers/site_keys.rb ---
</code>```

The following stacktrace

```<code> /var/lib/gems/1.8/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:147:in `load'
 /var/lib/gems/1.8/gems/rails-2.3.8/lib/initializer.rb:622:in `load_application_initializers'
 /var/lib/gems/1.8/gems/rails-2.3.8/lib/initializer.rb:621:in `each'
 /var/lib/gems/1.8/gems/rails-2.3.8/lib/initializer.rb:621:in `load_application_initializers'
 /var/lib/gems/1.8/gems/rails-2.3.8/lib/initializer.rb:176:in `process'
 /var/lib/gems/1.8/gems/rails-2.3.8/lib/initializer.rb:113:in `send'
 /var/lib/gems/1.8/gems/rails-2.3.8/lib/initializer.rb:113:in `run_without_spork'
 /var/lib/gems/1.8/gems/spork-0.8.4/lib/spork/app_framework/rails.rb:18:in `run'
 config/environment.rb:15
 spec/spec_helper.rb:14:in `require'
 spec/spec_helper.rb:14
 /var/lib/gems/1.8/gems/spork-0.8.4/bin/../lib/spork.rb:23:in `prefork'
</code>```

spec/spec_helper.rb:6

答:
I ran into the same problem, and this is what I was able to figure out.

Around line 50 of lib/tasks/rspec.rake you will find the following line.

```<code>spec_prereq = File.exist?(File.join(RAILS_ROOT, 'config', 'database.yml')) ? "db:test:prepare" : :noop
</code>```

This is causing db:test:prepare to get run before your specs, which in turn loads the environment, defeating the whole purpose of spork. I commented out this line and added the following below it.

```<code>spec_prereq = :noop
</code>```

This change should result in quite a bit of improvement. You will have to run db:test:prepare manually after you run db:migrate. I have a command that does both.

I don't know whether you're using Bundler, but I saw additional speed gains by upgrading to the latest (1.0.7). (Bundler sets up load paths when Rake is loaded in 2.3.x)

I still have a ~2.5s delay resulting from the overhead of spork, rake, and bundler, which I hope can be improved in the future, perhaps when spork supports rails 3.

Title: How to know if Spork is running

Body:
I'm trying to speed up "rspecing" in a rails 2.3.8 app with spork. When I run spork in the root of the project I get:

(...stuff...)
No server is running
Running specs locally:
Spork is ready and listening on 8989!

And then, if I run specs, the message

 No server is running
 Running specs locally

which appears if I run them without Spork doesn't appear, however spec startup is as slow as without Spork. Also in Spork's terminal no further output appears.

My question is, is spork actually running? If so, are the specs running there?, and finally, if the answer to both is true, how can I speed up my tests?

Here are the config files involved:

spec/spec.opts

  --colour
  --format progress
  --loadby mtime
  --reverse
  --drb

spec/spec.helper

require 'rubygems'
require 'bundler/setup'
require 'spork'

Spork.prefork do

   ENV["RAILS_ENV"] ||= 'test'
   require File.expand_path(File.join(File.dirname(__FILE__),'..','config','environment'))
   require 'spec/autorun'
   require 'spec/rails'

   Dir[File.expand_path(File.join(File.dirname(__FILE__),'support','**','*.rb'))].each {|f| require f}

   Spec::Runner.configure do |config|
  end

 end

 Spork.each_run do

end

And, to have a full question, here are the times measured with 'time':

With Spork:

real    0m39.524s
user    0m5.012s
sys  0m0.912s

Without Spork:

real    0m39.576s
user    0m18.537s
sys  0m2.400s

When running sport --diagnose I get

 - Spork Diagnosis -
 -- Summary --
 config/boot.rb
 config/initializers/inflections.rb
 config/initializers/mime_types.rb
 config/initializers/new_rails_defaults.rb
 config/initializers/site_keys.rb
 config/preinitializer.rb
 spec/spec_helper.rb

And then, for

 --- config/initializers/inflections.rb ---
 --- config/initializers/mime_types.rb ---
 --- config/initializers/new_rails_defaults.rb ---
 --- config/initializers/site_keys.rb ---

The following stacktrace

 /var/lib/gems/1.8/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:147:in `load'
 /var/lib/gems/1.8/gems/rails-2.3.8/lib/initializer.rb:622:in `load_application_initializers'
 /var/lib/gems/1.8/gems/rails-2.3.8/lib/initializer.rb:621:in `each'
 /var/lib/gems/1.8/gems/rails-2.3.8/lib/initializer.rb:621:in `load_application_initializers'
 /var/lib/gems/1.8/gems/rails-2.3.8/lib/initializer.rb:176:in `process'
 /var/lib/gems/1.8/gems/rails-2.3.8/lib/initializer.rb:113:in `send'
 /var/lib/gems/1.8/gems/rails-2.3.8/lib/initializer.rb:113:in `run_without_spork'
 /var/lib/gems/1.8/gems/spork-0.8.4/lib/spork/app_framework/rails.rb:18:in `run'
 config/environment.rb:15
 spec/spec_helper.rb:14:in `require'
 spec/spec_helper.rb:14
 /var/lib/gems/1.8/gems/spork-0.8.4/bin/../lib/spork.rb:23:in `prefork'

spec/spec_helper.rb:6

Body:
I ran into the same problem, and this is what I was able to figure out.

Around line 50 of lib/tasks/rspec.rake you will find the following line.

spec_prereq = File.exist?(File.join(RAILS_ROOT, 'config', 'database.yml')) ? "db:test:prepare" : :noop

This is causing db:test:prepare to get run before your specs, which in turn loads the environment, defeating the whole purpose of spork. I commented out this line and added the following below it.

spec_prereq = :noop

This change should result in quite a bit of improvement. You will have to run db:test:prepare manually after you run db:migrate. I have a command that does both.

I don't know whether you're using Bundler, but I saw additional speed gains by upgrading to the latest (1.0.7). (Bundler sets up load paths when Rake is loaded in 2.3.x)

I still have a ~2.5s delay resulting from the overhead of spork, rake, and bundler, which I hope can be improved in the future, perhaps when spork supports rails 3.


问:
Calculating categorical average with filtered data
I have following dataset:

```<code>A -1
A 10
B  8
D -1
A  0
A  4
B  2
C  6
</code>```

And I want to add column to it like this:

```<code>A -1 4,6
A 10 4,6
B  8 5,0
D -1 5,0
A  0 4,6
A  4 4,6
B  2 5,0
C  6 6,0
</code>```

What have happened here?

Well I have calculated average of each categorical letter variable but ignoring negative numbers and given this as new columns value.

If there is only negative values for category I have given value of total average (ignoring negative values).

In SQL this would have been done with filtered group funcion followed with join. In excel this would be conditional vlookup. How I do this in R?

Edit:

```<code># Create dataset
category <- c("A","A","B","D","A","A","B","C")
value <- c(-1,10,8,-1,0,4,2,6)
dataset <- data.frame(category, value)

# Calculated means

fdata <- dataset[dataset[,'value']>-1,]
aggregate(fdata[,2], list(fdata$category), mean)
</code>```

答:
We can use ave from base R grouped by each category, we check if all the value in a particular group is less than 0, if it is then we select the mean of the entire dataset and if it is not then we take only the mean of the group.

```<code>dataset$mean_column <- with(dataset, ave(value, category, FUN = function(x)
         ifelse(all(x < 0), mean(value[value >= 0]), mean(x[x >= 0]))))

dataset

#  category value  mean_column
#1        A    -1    4.666667
#2        A    10    4.666667
#3        B     8    5.000000
#4        D    -1    5.000000
#5        A     0    4.666667
#6        A     4    4.666667
#7        B     2    5.000000
#8        C     6    6.000000
</code>```

Body:
I have following dataset:

A -1
A 10
B  8
D -1
A  0
A  4
B  2
C  6

And I want to add column to it like this:

A -1 4,6
A 10 4,6
B  8 5,0
D -1 5,0
A  0 4,6
A  4 4,6
B  2 5,0
C  6 6,0

What have happened here?

Well I have calculated average of each categorical letter variable but ignoring negative numbers and given this as new columns value.

If there is only negative values for category I have given value of total average (ignoring negative values).

In SQL this would have been done with filtered group funcion followed with join. In excel this would be conditional vlookup. How I do this in R?

Edit:

# Create dataset
category <- c("A","A","B","D","A","A","B","C")
value <- c(-1,10,8,-1,0,4,2,6)
dataset <- data.frame(category, value)

# Calculated means

fdata <- dataset[dataset[,'value']>-1,]
aggregate(fdata[,2], list(fdata$category), mean)

Body:
We can use ave from base R grouped by each category, we check if all the value in a particular group is less than 0, if it is then we select the mean of the entire dataset and if it is not then we take only the mean of the group.

dataset$mean_column <- with(dataset, ave(value, category, FUN = function(x)
         ifelse(all(x < 0), mean(value[value >= 0]), mean(x[x >= 0]))))

dataset

#  category value  mean_column
#1        A    -1    4.666667
#2        A    10    4.666667
#3        B     8    5.000000
#4        D    -1    5.000000
#5        A     0    4.666667
#6        A     4    4.666667
#7        B     2    5.000000
#8        C     6    6.000000


问:
How to delete many to many DB in realm
This is I tried

```<code>public class AppInfo extends RealmObject {
    public String packageName;

    public RealmList<CategoryInfo> categoryList;
}

public class CategoryInfo extends RealmObject {
    public String categoryName;
}
</code>```

This is my DB Table.

I wanna delete categoryName.

```<code> AppInfo result = realm.where(AppInfo.class).equalTo("packageName",info.getPackageName()).findFirst();

result.categoryList.remove(category);
</code>```

but the code can't delete categoryName.

答:
Instead of

```<code>result.categoryList.remove(category);
</code>```

You should do

```<code>result.categoryList.where().equalTo("categoryName", category).findAll().deleteAllFromRealm();
</code>```

With Realm 3.4.0, you can also do

```<code>public class AppInfo extends RealmObject {
    public String packageName;

    public RealmList<CategoryInfo> categoryList;
}

public class CategoryInfo extends RealmObject {
    public String categoryName;

    @LinkingObjects("categoryList")
    public final RealmResults<AppInfo> appInfos = null;
}
</code>```

and

```<code>realm.where(CategoryInfo.class)
         .equalTo("appInfos.packageName", packageName)
         .equalTo("categoryName", category)
         .findAll()
         .deleteFromRealm();
</code>```

Title: How to delete many to many DB in realm

Body:
This is I tried

public class AppInfo extends RealmObject {
    public String packageName;

    public RealmList<CategoryInfo> categoryList;
}

public class CategoryInfo extends RealmObject {
    public String categoryName;
}

This is my DB Table.

I wanna delete categoryName.

 AppInfo result = realm.where(AppInfo.class).equalTo("packageName",info.getPackageName()).findFirst();

result.categoryList.remove(category);

but the code can't delete categoryName.

Body:
Instead of

result.categoryList.remove(category);

You should do

result.categoryList.where().equalTo("categoryName", category).findAll().deleteAllFromRealm();

With Realm 3.4.0, you can also do

public class AppInfo extends RealmObject {
    public String packageName;

    public RealmList<CategoryInfo> categoryList;
}

public class CategoryInfo extends RealmObject {
    public String categoryName;

    @LinkingObjects("categoryList")
    public final RealmResults<AppInfo> appInfos = null;
}

and

realm.where(CategoryInfo.class)
         .equalTo("appInfos.packageName", packageName)
         .equalTo("categoryName", category)
         .findAll()
         .deleteFromRealm();


问:
[ERROR]Native table performance schema has the wrong structure
```<code>150814  9:09:14 [ERROR] Native table 'performance_schema'.'events_waits_current' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'events_waits_history' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'events_waits_history_long' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'setup_consumers' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'setup_instruments' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'setup_timers' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'performance_timers' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'threads' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'events_waits_summary_by_thread_by_event_name' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'events_waits_summary_by_instance' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'events_waits_summary_global_by_event_name' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'file_summary_by_event_name' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'file_summary_by_instance' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'mutex_instances' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'rwlock_instances' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'cond_instances' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'file_instances' has the wrong structure
150814  9:09:14 [Note] /usr/libexec/mysqld: ready for connections.
Version: '5.5.44-cll-lve'  socket: '/var/lib/mysql/mysql.sock'  port: 3306  MySQL Community Server (GPL) by Atomicorp
</code>```

Then I run

```<code>mysql_upgrade
</code>```

It shows:

Looking for 'mysql' as: mysql

Looking for 'mysqlcheck' as: mysqlcheck

FATAL ERROR: Upgrade failed

答:
If you're running MySQL on your local device, you need to upgrade your mysql and then restart:

Upgrade:

```<code>$ mysql_upgrade -u root
</code>```

Restart:

```<code>$ mysql.server restart
</code>```

Body:
150814  9:09:14 [ERROR] Native table 'performance_schema'.'events_waits_current' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'events_waits_history' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'events_waits_history_long' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'setup_consumers' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'setup_instruments' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'setup_timers' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'performance_timers' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'threads' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'events_waits_summary_by_thread_by_event_name' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'events_waits_summary_by_instance' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'events_waits_summary_global_by_event_name' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'file_summary_by_event_name' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'file_summary_by_instance' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'mutex_instances' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'rwlock_instances' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'cond_instances' has the wrong structure
150814  9:09:14 [ERROR] Native table 'performance_schema'.'file_instances' has the wrong structure
150814  9:09:14 [Note] /usr/libexec/mysqld: ready for connections.
Version: '5.5.44-cll-lve'  socket: '/var/lib/mysql/mysql.sock'  port: 3306  MySQL Community Server (GPL) by Atomicorp

Then I run

mysql_upgrade

It shows:

Looking for 'mysql' as: mysql

Looking for 'mysqlcheck' as: mysqlcheck

FATAL ERROR: Upgrade failed

Body:
If you're running MySQL on your local device, you need to upgrade your mysql and then restart:

Upgrade:

$ mysql_upgrade -u root

Restart:

$ mysql.server restart


问:
JavaScript and AJAX not working as expected
I'm using the JavaScript and AJAX for signup form.

I want to post all textboxes in signup form through AJAX but am failing to do so.

signup.php

$(document).ready(function() {
  $('submit').click(function() {
    var first = $('#firstname').val();
    var last = $('#lastname').val();
    var Email = $('#email').val();
    var pass = $('#password').val();
    var confirm = $('#confirmpassword').val();
    var phone = $('#phoneno').val();

    $.ajax({
      type: "POST",
      url: "register.php",
      data: {
        (

          firstname: first,
          lastname: last,
          email: Email,
          password: pass,
          confirmpassword: confirm,
          phoneno: phone,

        )
      },
      success: function(data) {
        alert('passed');
      },
      error: function() {
        alert("error");
      }

    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="jquery-3.2.0.min.js"></script>
<title>
</title>

<div align="right">
</div>
<div id="div">
  <center>
    <h3>REGISTER</h3>
  </center>
  <table>
    <thead>
    </thead>
    <tbody>
      <tr>
        <td>
          <label>Firstname</label>
          <td>
            <input type="text" name="firstname" id="firstname" required="">
          </td>
      </tr>
      <tr>
        <td>
          <label>Lastname</label>
        </td>
        <td>
          <input type="text" name="lastname" id="lastname" required="">
        </td>
      </tr>
      <tr>
        <td>
          <label>Email</label>
        </td>
        <td>
          <input type="text" name="email" id="email" required="">
        </td>
      </tr>
      <tr>
        <td>
          <label>Password</label>
        </td>
        <td>
          <input type="password" name="password" id="password" required="">
        </td>
      </tr>
      <tr>
        <td>
          <label>Confirm password</label>
        </td>
        <td>
          <input type="password" name="confirmpassword" id="confirmpassword" required="">
        </td>
      </tr>
      <tr>
        <td>
          <label>Phone no</label>
        </td>
        <td>
          <input type="text" name="phoneno" id="phoneno" required="">
        </td>
      </tr>
      <tr>
        <td>
        </td>
        <td>
          <input type="button" name="submit" value="submit" id="submit" />
        </td>
      </tr>
      <tr>
        <td>
        </td>
        <td>
        </td>
        <td>
          Login?
        </td>
      </tr>
    </tbody>
  </table>
</div></code>```

register.php

```<code><?php
include 'config.php';
 $firstname=$_POST['firstname'];
 $lastname= $_POST['lastname'];
 $email=$_POST['email'];
 $password=$_POST['password'];
 $confirmpassword=$_POST['confirmpassword'];
 $phoneno=$_POST['phoneno'];
if($password==$confirmpassword)
{
$insertuser=mysql_query("insert into register(firstname,lastname,email,password,confirmpassword,phoneno) values('$firstname','$lastname','$email','$password','$confirmpassword','$phoneno')",$conn)or die(mysql_error());
echo "success";

}
else
{
  echo "failure";

 }
?>
</code>```

答:
Input type should be submit like:

```<code><input type="submit" name="submit" value="submit" id="submit" />
</code>```

if you want to use $('submit') else you need to change it to $('#submit').

Body:
I'm using the JavaScript and AJAX for signup form.

I want to post all textboxes in signup form through AJAX but am failing to do so.

signup.php

$(document).ready(function() {
  $('submit').click(function() {
    var first = $('#firstname').val();
    var last = $('#lastname').val();
    var Email = $('#email').val();
    var pass = $('#password').val();
    var confirm = $('#confirmpassword').val();
    var phone = $('#phoneno').val();

    $.ajax({
      type: "POST",
      url: "register.php",
      data: {
        (

          firstname: first,
          lastname: last,
          email: Email,
          password: pass,
          confirmpassword: confirm,
          phoneno: phone,

        )
      },
      success: function(data) {
        alert('passed');
      },
      error: function() {
        alert("error");
      }

    });
  });
});

<title>
</title>

REGISTER

          Firstname

            <input type="text" name="firstname" id="firstname" required="">

          Lastname

          <input type="text" name="lastname" id="lastname" required="">

          Email

          <input type="text" name="email" id="email" required="">

          Password

          <input type="password" name="password" id="password" required="">

          Confirm password

          <input type="password" name="confirmpassword" id="confirmpassword" required="">

          Phone no

          <input type="text" name="phoneno" id="phoneno" required="">

          <input type="button" name="submit" value="submit" id="submit" />

          Login?

register.php

<?php
include 'config.php';
 $firstname=$_POST['firstname'];
 $lastname= $_POST['lastname'];
 $email=$_POST['email'];
 $password=$_POST['password'];
 $confirmpassword=$_POST['confirmpassword'];
 $phoneno=$_POST['phoneno'];
if($password==$confirmpassword)
{
$insertuser=mysql_query("insert into register(firstname,lastname,email,password,confirmpassword,phoneno) values('$firstname','$lastname','$email','$password','$confirmpassword','$phoneno')",$conn)or die(mysql_error());
echo "success";

}
else
{
  echo "failure";

 }
?>

Body:
Input type should be submit like:

<input type="submit" name="submit" value="submit" id="submit" />

if you want to use $('submit') else you need to change it to $('#submit').


问:
Hide a button in onload using angularjs
I have one form with three buttons edit update and cancel.Onload of the page I need to hide the update button.

When I click edit button edit should be hide and update should be displayed.
when I click on update I need to redirect some other page.

Hoe to do this?

```<code>                <form id="show_details">

                        <label>Project Name</label>
                        <label><input type="text"></label>

                        <label>Client </label>
                        <label><input type="text"></label>

                        <label>Project Co-ordinator</label>
                        <label><input type="text" disabled="true" ></label>

                        <label>Client Co-ordinator</label>
                        <label><input type="text"></label>

                        <label>Resource</label>
                        <label><input type="text" disabled="true"></label>
                    </div>
                </form>
                <div class="row">
                    <span class="pull-right btnMarginTop">
                        <button class="btn btn-primary" id="projectDetailsEdit"  ng-click="goEvent()">Edit</button>
                        <button class="btn btn-primary" id="projectDetailsUpdate" ng-hide="editMode=true" ng-click="goEvent()">Update</button>
                        <button class="btn btn-default" onclick="window.location.href = '/Project/ProjectList'">Cancel</button>
                    </span>
                </div>

<script>
    var app = angular
                    .module("intranet_App", [])
                    .controller(function ($scope, $http) {
                       $scope.editMode = false;
                       $scope.goEvent = function(){
                       $scope.editMode = !$scope.editMode;
                       if($scope.editMode){
                          $scope.editMode = false;
                       }else{
                           $scope.editMode = true;
                       }
                    }
                    })
</script>
</code>```

答:
You have problem in html code and changing editMode in goEvent function twice. Here is working code

var app = angular.module("intranetApp", [])
                    .controller('ctrl',function ($scope, $http) {
                       $scope.editMode = false;
                       $scope.goEvent = function(){
                       $scope.editMode = !$scope.editMode;

                    }
                    })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="intranetApp" ng-controller="ctrl">
<form id="show_details" >

                        <label>Project Name</label>
                        <label><input type="text"></label>

                        <label>Client </label>
                        <label><input type="text"></label>

                        <label>Project Co-ordinator</label>
                        <label><input type="text" disabled="true" ></label>

                        <label>Client Co-ordinator</label>
                        <label><input type="text"></label>

                        <label>Resource</label>
                        <label><input type="text" disabled="true"></label>

                <div class="row">
                    <span class="pull-right btnMarginTop">
                        <button class="btn btn-primary" id="projectDetailsEdit"  ng-show="editMode == false" ng-click="goEvent()">Edit</button>
                        <button class="btn btn-primary" id="projectDetailsUpdate" ng-show="editMode" ng-click="goEvent()">Update</button>
                        <button class="btn btn-default" onclick="window.location.href = '/Project/ProjectList'">Cancel</button>
                    </span>
                </div>
                </form>
                </div></code>```

Title: Hide a button in onload using angularjs

Body:
I have one form with three buttons edit update and cancel.Onload of the page I need to hide the update button.

When I click edit button edit should be hide and update should be displayed.
when I click on update I need to redirect some other page.

Hoe to do this?

                <form id="show_details">

                        Project Name
                        <input type="text">

                        Client
                        <input type="text">

                        Project Co-ordinator
                        <input type="text" disabled="true" >

                        Client Co-ordinator
                        <input type="text">

                        Resource
                        <input type="text" disabled="true">

                </form>

                        <button class="btn btn-primary" id="projectDetailsEdit"  ng-click="goEvent()">Edit</button>
                        <button class="btn btn-primary" id="projectDetailsUpdate" ng-hide="editMode=true" ng-click="goEvent()">Update</button>
                        <button class="btn btn-default" onclick="window.location.href = '/Project/ProjectList'">Cancel</button>

Body:
You have problem in html code and changing editMode in goEvent function twice. Here is working code

var app = angular.module("intranetApp", [])
                    .controller('ctrl',function ($scope, $http) {
                       $scope.editMode = false;
                       $scope.goEvent = function(){
                       $scope.editMode = !$scope.editMode;

                    }
                    })

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="intranetApp" ng-controller="ctrl">
<form id="show_details" >

                        <label>Project Name</label>
                        <label><input type="text"></label>

                        <label>Client </label>
                        <label><input type="text"></label>

                        <label>Project Co-ordinator</label>
                        <label><input type="text" disabled="true" ></label>

                        <label>Client Co-ordinator</label>
                        <label><input type="text"></label>

                        <label>Resource</label>
                        <label><input type="text" disabled="true"></label>

                <div class="row">
                    <span class="pull-right btnMarginTop">
                        <button class="btn btn-primary" id="projectDetailsEdit"  ng-show="editMode == false" ng-click="goEvent()">Edit</button>
                        <button class="btn btn-primary" id="projectDetailsUpdate" ng-show="editMode" ng-click="goEvent()">Update</button>
                        <button class="btn btn-default" onclick="window.location.href = '/Project/ProjectList'">Cancel</button>
                    </span>
                </div>
                </form>
                </div>


问:
MVVM binding many properties
Is there a simpeler way to bind many properties?

So if you have a Person class with properties: lastname, firstname, birthday, gender, title, ...

Now I do this for every property on the ViewModel:

```<code> public string _LastName;
 public string LastName
 {
    get { return _LastName; }
    set { _LastName = value;
          RaisePropertyChanged("LastName"); }
 }
</code>```

And on the XAML page this binding:

```<code> <TextBlock Text="{Binding FirstName}" />
</code>```

Now image if Person object has like 20 properties..
So my question is can I do this in a simpeler way?

答:
The simplest solution is to use the POCO mechanism provided by a free DevExpress MVVM Framework.
POCO will automatically implement INotifyPropertyChanged and raise the PropertyChanged event for all public virtual properties in your view model.

All magic happens when you use the ViewModelSource class to create your view model. You can create your view model in XAML:

```<code><UserControl ...
    DataContext="{dxmvvm:ViewModelSource Type=local:MyViewModel}">
</code>```

Or in code-behind:

```<code>this.DataContext = ViewModelSource.Create(() => new MyViewModel());
</code>```

Title: MVVM binding many properties

Body:
Is there a simpeler way to bind many properties?

So if you have a Person class with properties: lastname, firstname, birthday, gender, title, ...

Now I do this for every property on the ViewModel:

 public string _LastName;
 public string LastName
 {
    get { return _LastName; }
    set { _LastName = value;
          RaisePropertyChanged("LastName"); }
 }

And on the XAML page this binding:

 <TextBlock Text="{Binding FirstName}" />

Now image if Person object has like 20 properties..
So my question is can I do this in a simpeler way?

Body:
The simplest solution is to use the POCO mechanism provided by a free DevExpress MVVM Framework.
POCO will automatically implement INotifyPropertyChanged and raise the PropertyChanged event for all public virtual properties in your view model.

All magic happens when you use the ViewModelSource class to create your view model. You can create your view model in XAML:

<UserControl ...
    DataContext="{dxmvvm:ViewModelSource Type=local:MyViewModel}">

Or in code-behind:

this.DataContext = ViewModelSource.Create(() => new MyViewModel());


问:
Android floating button not coming proper
I am using a floating button. The image source I am using is also proper but not sure while setting it is showing it as dot in the center. Screenshot and Code below :

```<code><android.support.design.widget.FloatingActionButton
        android:id="@+id/fab_add_cg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:elevation="10dp"
        app:borderWidth="0dp"
        app:backgroundTint="@color/blue_4a90e2"
        android:src="@drawable/addbutton"/>
</code>```

答:
Try using

```<code> android:scaleType="center"
</code>```

make sure your icon size is 24 X24 dp icon

see this   for reference

Body:
I am using a floating button. The image source I am using is also proper but not sure while setting it is showing it as dot in the center. Screenshot and Code below :

<android.support.design.widget.FloatingActionButton
        android:id="@+id/fab_add_cg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:elevation="10dp"
        app:borderWidth="0dp"
        app:backgroundTint="@color/blue_4a90e2"
        android:src="@drawable/addbutton"/>

Body:
Try using

 android:scaleType="center"

make sure your icon size is 24 X24 dp icon

see this   for reference


问:
Node.js: How to use kafka-node for fetching messages from beginning from a topic?
I followed this tutorial for installing Kafka on Ubuntu 14.04 server. The examples provided for producer and consumer are working fine.

Here is the producer command:

```<code>echo "Hello, World" | ~/kafka/bin/kafka-console-producer.sh --broker-list localhost:9092 --topic TutorialTopic > /dev/null
</code>```

And here is the consumer command:

```<code>~/kafka/bin/kafka-console-consumer.sh --zookeeper localhost:2181 --topic TutorialTopic --from-beginning
</code>```

However, I am trying to write a similar consumer in Node.js and it does not display the messages that existed in the topic before the consumer was created. Here is my code. What additional config is required to accomplish what I am trying ?

```<code>var kafka = require('kafka-node')
var Consumer = kafka.Consumer
var client = new kafka.Client("localhost:2181/")
var consumer = new Consumer(
    client,
    [
      { topic: 'TutorialTopic', partition: 0, offset: 0}
    ],
    {
      fromOffset: true
    }
  );

consumer.on('message', function (message) {
  console.log("received message", message);
});
</code>```

答:
```<code>Add fromOffset to earliest in consumer config

var consumer = new Consumer(
client,
[
  { topic: 'TutorialTopic', partition: 0, offset: 0}
],
{
  fromOffset: 'earliest',
});
</code>```

Body:
I followed this tutorial for installing Kafka on Ubuntu 14.04 server. The examples provided for producer and consumer are working fine.

Here is the producer command:

echo "Hello, World" | ~/kafka/bin/kafka-console-producer.sh --broker-list localhost:9092 --topic TutorialTopic > /dev/null

And here is the consumer command:

~/kafka/bin/kafka-console-consumer.sh --zookeeper localhost:2181 --topic TutorialTopic --from-beginning

However, I am trying to write a similar consumer in Node.js and it does not display the messages that existed in the topic before the consumer was created. Here is my code. What additional config is required to accomplish what I am trying ?

var kafka = require('kafka-node')
var Consumer = kafka.Consumer
var client = new kafka.Client("localhost:2181/")
var consumer = new Consumer(
    client,
    [
      { topic: 'TutorialTopic', partition: 0, offset: 0}
    ],
    {
      fromOffset: true
    }
  );

consumer.on('message', function (message) {
  console.log("received message", message);
});


问:
Liferay: How to configure Service Builder to use MySQL generated Primary Key
I have a liferay entity (log table) that has a primary key auto generated by Liferay Service Builder (service.xml).
However now an external application need to add entries to this same database table.

Looking at this requirement I see only two options to achieve this:

If I can specify within service.xml that can allow this database entity to use MySQL generated primary key (rather than Liferay counter services), then Liferay or External application both can add entries without any worries.

If #1 is not possible due to Service Builder limitations, then only option is to expose this entity using a liferay web service for the external application to add entries to this db table.

答:
DTD Service Builder 6.2.0

The answer to your question is directly in the xml document description.

First Example

The second implementation generates identifiers that are unique only when no
  other process is inserting data into the same table. This implementation should
  NOT be used in a clustered environment, but it does work for all supported
  databases.

Example

```<code><column
    name="id"
    type="Integer"
    primary="true"
    id-type="increment"
/>
</code>```

Second Example

The third implementation uses an identity column to generate a primary key. In this implementation, the create table SQL generated for this entity will
  create an identity column that natively auto-generates a primary key whenever
  an insert occurs. This implementation is only supported by DB2, MySQL, and
  MS SQL Server.

Example

```<code><column
    name="id"
    type="Integer"
    primary="true"
    id-type="identity"
/>
</code>```

A hard to come by piece of information is how to override the create method in your generated persistenceImpl class.  When you create a surrogate key in Liferay you generally use the CounterLocalService to increment.  However, when your key is handled by the database you need to send in 0 as the argument.

```<code>public SoftwareKey createSoftwareKey() {
    return softwareKeyPersistence.create(0);
}
</code>```

Body:
DTD Service Builder 6.2.0

The answer to your question is directly in the xml document description.

First Example

The second implementation generates identifiers that are unique only when no
  other process is inserting data into the same table. This implementation should
  NOT be used in a clustered environment, but it does work for all supported
  databases.

Example

<column
    name="id"
    type="Integer"
    primary="true"
    id-type="increment"
/>

Second Example

The third implementation uses an identity column to generate a primary key. In this implementation, the create table SQL generated for this entity will
  create an identity column that natively auto-generates a primary key whenever
  an insert occurs. This implementation is only supported by DB2, MySQL, and
  MS SQL Server.

Example

<column
    name="id"
    type="Integer"
    primary="true"
    id-type="identity"
/>

A hard to come by piece of information is how to override the create method in your generated persistenceImpl class.  When you create a surrogate key in Liferay you generally use the CounterLocalService to increment.  However, when your key is handled by the database you need to send in 0 as the argument.

public SoftwareKey createSoftwareKey() {
    return softwareKeyPersistence.create(0);
}