问:
How do i run the same function which involves row and column indices over multiple data frames that are in a list?
Game1 is just one dataframe and I applied these functions to it but now I want to be able to do this to each dataframe in a list which I imported using a DataLoader package.

```<code>Game1$Goal=Goal <- 0

for(i in 1:nrow(Game1))
ifelse(Game1$EventName[i] == "Shot" && Game1$EventName[i+1] == "Goal" |     Game1$EventName[i] == "Header Shot" && Game1$EventName[i+1] == "Goal",   Game1$Goal[i] <- 1, Game1$Goal[i] <- 0)

Game1shot <- subset(Game1, EventName == "Shot" | EventName == "Header Shot")

nRowsz <- nrow(Game1shot)
for (i in 1:nrow(Game1){
  Zone1 <- as.integer(Game1$Zone == "Zone 1")
  Zone2 <- as.integer(Game1$Zone == "Zone 2")
  Zone3 <- as.integer(Game1$Zone == "Zone 3")
  ........
  Zone100 <- as.integer(Game1$Zone == "Zone 100")
  Goal <- Game1$Goal

  Gamefinal1 <- data.frame(Zone1,......,Zone100,Goal)
  }
</code>```

and this counties until Zone100 and all these Zone"" vectors are made into a new data frame named "Gamefinal1" for Game1 but i want this for all Games.

After importing all the csv files as dataframes which are elements in a list.
I tried writing code with these 2 methods so i can apply the functions above to each element in this list but it doesn't working.

Method 1

```<code>Games <- importCsv(path = "")
Games <- lapply(Games, function(x) {
  for(j in 1:nrow(x))
    ifelse(x$EventName[j] == "Shot" && x$EventName[j+1] == "Goal",   x$Goal[j] <- 1, x$Goal[j] <- 0)
  })
</code>```

Method 2

```<code>for(i in Games){
      for(j in 1:nrow(i))
      ifelse(i$EventName[j] == "Shot" && i$EventName[j+1] == "Goal" |  i$EventName[j] == "Header Shot" && i$EventName[j+1] == "Goal", i$Goal[j] <-  1, i$Goal[j] <- 0)
      }
</code>```

After running Method 2, it say there are 50 or more warnings.. and they are
Warnings from Method 2

Thanks in advance!!

[Snippet of how the data looks][2]

Simplied version of how the data looks

```<code>Half        Time     EventName      Rotation   Zone
First Half  0        Start Of Half  180        Zone 46
First Half  0.5      Touch          180        Zone 46
First Half  1.5      Shot           180        Zone 46
First Half  13.1     Throw In       0          Zone 99
First Half  14.8     Header         0          Zone 57
First Half  22.6     Shot           180        Zone 44
First Half  23.6     Goal           180        Zone 44
First Half  25       Touch          0          Zone 99
First Half  26       Shot           0          Zone 97
First Half  27       Pass           0          Zone 90
First Half  27.9     Header Shot    0          Zone 91
First Half  29.3     Goal           0          Zone 54
First Half  30.6     Pass           0          Zone 54
First Half  33       Touch          0          Zone 59
</code>```

答:
Consider adjusting your ifelse to avoid assignment calls within it. Also, consider an sapply on a character vector of zones ("Zone 1", "Zone 2", "Zone 3", ...):

```<code>Zones <- paste("Zone", seq(100))
Games <- importCsv(path = "")

NewGames <- lapply(Games, function(x) {
  for(i in seq(nrow(x)-1)) {
    x$Goal[i] <- ifelse((x$EventName[i] == "Shot" & x$EventName[i+1] == "Goal") |
                        (x$EventName[i] == "Header Shot" & x$EventName[i+1] == "Goal"), 1, 0)
  }

  subGame <- subset(x, EventName == "Shot" | EventName == "Header Shot")
  Zones_mat <- sapply(Zones, function(z){
    as.integer(subGame$Zone == z)
  })

  Zones_mat <- cbind(Zones_mat, subGame$Goal)
  colnames(Zones_mat) <- append(gsub(" ", "", Zones), "Goal")
})
</code>```

R Fiddle Demo

Body:
Game1 is just one dataframe and I applied these functions to it but now I want to be able to do this to each dataframe in a list which I imported using a DataLoader package.

Game1$Goal=Goal <- 0

for(i in 1:nrow(Game1))
ifelse(Game1$EventName[i] == "Shot" && Game1$EventName[i+1] == "Goal" |     Game1$EventName[i] == "Header Shot" && Game1$EventName[i+1] == "Goal",   Game1$Goal[i] <- 1, Game1$Goal[i] <- 0)

Game1shot <- subset(Game1, EventName == "Shot" | EventName == "Header Shot")

nRowsz <- nrow(Game1shot)
for (i in 1:nrow(Game1){
  Zone1 <- as.integer(Game1$Zone == "Zone 1")
  Zone2 <- as.integer(Game1$Zone == "Zone 2")
  Zone3 <- as.integer(Game1$Zone == "Zone 3")
  ........
  Zone100 <- as.integer(Game1$Zone == "Zone 100")
  Goal <- Game1$Goal

  Gamefinal1 <- data.frame(Zone1,......,Zone100,Goal)
  }

and this counties until Zone100 and all these Zone"" vectors are made into a new data frame named "Gamefinal1" for Game1 but i want this for all Games.

After importing all the csv files as dataframes which are elements in a list.
I tried writing code with these 2 methods so i can apply the functions above to each element in this list but it doesn't working.

Method 1

Games <- importCsv(path = "")
Games <- lapply(Games, function(x) {
  for(j in 1:nrow(x))
    ifelse(x$EventName[j] == "Shot" && x$EventName[j+1] == "Goal",   x$Goal[j] <- 1, x$Goal[j] <- 0)
  })

Method 2

for(i in Games){
      for(j in 1:nrow(i))
      ifelse(i$EventName[j] == "Shot" && i$EventName[j+1] == "Goal" |  i$EventName[j] == "Header Shot" && i$EventName[j+1] == "Goal", i$Goal[j] <-  1, i$Goal[j] <- 0)
      }

After running Method 2, it say there are 50 or more warnings.. and they are
Warnings from Method 2

Thanks in advance!!

[Snippet of how the data looks][2]

Simplied version of how the data looks

Half        Time     EventName      Rotation   Zone
First Half  0        Start Of Half  180        Zone 46
First Half  0.5      Touch          180        Zone 46
First Half  1.5      Shot           180        Zone 46
First Half  13.1     Throw In       0          Zone 99
First Half  14.8     Header         0          Zone 57
First Half  22.6     Shot           180        Zone 44
First Half  23.6     Goal           180        Zone 44
First Half  25       Touch          0          Zone 99
First Half  26       Shot           0          Zone 97
First Half  27       Pass           0          Zone 90
First Half  27.9     Header Shot    0          Zone 91
First Half  29.3     Goal           0          Zone 54
First Half  30.6     Pass           0          Zone 54
First Half  33       Touch          0          Zone 59

Body:
Consider adjusting your ifelse to avoid assignment calls within it. Also, consider an sapply on a character vector of zones ("Zone 1", "Zone 2", "Zone 3", ...):

Zones <- paste("Zone", seq(100))
Games <- importCsv(path = "")

NewGames <- lapply(Games, function(x) {
  for(i in seq(nrow(x)-1)) {
    x$Goal[i] <- ifelse((x$EventName[i] == "Shot" & x$EventName[i+1] == "Goal") |
                        (x$EventName[i] == "Header Shot" & x$EventName[i+1] == "Goal"), 1, 0)
  }

  subGame <- subset(x, EventName == "Shot" | EventName == "Header Shot")
  Zones_mat <- sapply(Zones, function(z){
    as.integer(subGame$Zone == z)
  })

  Zones_mat <- cbind(Zones_mat, subGame$Goal)
  colnames(Zones_mat) <- append(gsub(" ", "", Zones), "Goal")
})

R Fiddle Demo


来源: stackexchange

问:
Select first and second half of list items
I'm trying to change the color of list items based on a gradient with a defined starting color and ending color. I'm trying to use two different color stops for the 1st and 2nd half of my list items. The problem is that only the first half is working and I get a JS error

https://jsfiddle.net/qrzms3s9/1/

```<code>jQuery(document).ready(function($) {
  if($('.test')[0]){

    var circles = $('.testcircle').length,
            halfcircles = circles / 2;

    function colorStrToIntArray(color) {
        if (color.length == 4 || color.length == 7) {
                color = color.substr(1);
        }
        if (color.length == 3) {
            var r = parseInt(color.substr(0, 1) + color.substr(0, 1), 16),
                    g = parseInt(color.substr(1, 1) + color.substr(1, 1), 16),
                    b = parseInt(color.substr(2, 1) + color.substr(2, 1), 16);

            return [r, g, b];
        }
        else if (color.length == 6) {
            return [
                parseInt(color.substr(0, 2), 16),
                parseInt(color.substr(2, 2), 16),
                parseInt(color.substr(4, 2), 16)
            ];
        }
        return false;
    }

    function calculateSteps(color1, color2, steps) {
        var output = [],
                start = colorStrToIntArray(color1),
                end = colorStrToIntArray(color2);
        var calculate = function(start, end, step) {
            return start + Math.round((end - start) * (step / (steps / 2)));
        };
        for ( var i = 0; i < steps; i++ ) {
            var color = [0, 0, 0];
            color[0] = calculate(start[0], end[0], i);
            color[1] = calculate(start[1], end[1], i);
            color[2] = calculate(start[2], end[2], i);
            output.push(color);
        }
        return output;
    }

    var colors = calculateSteps("#f29111", "#e60000", halfcircles),
            colors2 = calculateSteps("#d20911", "#22637e", halfcircles),
            cars = $('.testcircle');
            index = 0;

    $('.testcircle').each(function() {
        var $carrot = $("<div>", {"class": "testw6"});
        $(this).closest('li').find('.testw5').prepend($carrot);
        if (index < halfcircles) {
            $(this).css('background-color', 'rgb(' + colors[index][0] + ', ' + colors[index][1] + ', ' + colors[index][2] + ')');
            $(this).closest('li').find('.testw5').css('background-color', 'rgb(' + colors[index][0] + ', ' + colors[index][1] + ', ' + colors[index][2] + ')');
            $(this).closest('li').find('.testw6').css('background-color', 'rgb(' + colors[index][0] + ', ' + colors[index][1] + ', ' + colors[index][2] + ')');
            index++;
        }
        else {
            $(this).css('background-color', 'rgb(' + colors2[index][0] + ', ' + colors2[index][1] + ', ' + colors2[index][2] + ')');
            $(this).closest('li').find('.testw5').css('background-color', 'rgb(' + colors2[index][0] + ', ' + colors2[index][1] + ', ' + colors2[index][2] + ')');
            $(this).closest('li').find('.testw6').css('background-color', 'rgb(' + colors2[index][0] + ', ' + colors2[index][1] + ', ' + colors2[index][2] + ')');
            index++;
        }
    });

  }
});
</code>```

答:
Problem is with your index count. For the second half of iteration you need to reset the index. I have a better approach for the code - instead of resetting the index, we can have a single array of colors and point the element index from each.

jQuery(document).ready(function($) {

  var circles = $('.testcircle').length,
    halfcircles = circles / 2;

  function colorStrToIntArray(color) {
    if (color.length == 4 || color.length == 7) {
      color = color.substr(1);
    }
    if (color.length == 3) {
      var r = parseInt(color.substr(0, 1) + color.substr(0, 1), 16),
        g = parseInt(color.substr(1, 1) + color.substr(1, 1), 16),
        b = parseInt(color.substr(2, 1) + color.substr(2, 1), 16);

      return [r, g, b];
    } else if (color.length == 6) {
      return [
        parseInt(color.substr(0, 2), 16),
        parseInt(color.substr(2, 2), 16),
        parseInt(color.substr(4, 2), 16)
      ];
    }
    return false;
  }

  function calculateSteps(color1, color2, steps) {
    var output = [],
      start = colorStrToIntArray(color1),
      end = colorStrToIntArray(color2);
    var calculate = function(start, end, step) {
      return start + Math.round((end - start) * (step / (steps / 2)));
    };
    for (var i = 0; i < steps; i++) {
      var color = [0, 0, 0];
      color[0] = calculate(start[0], end[0], i);
      color[1] = calculate(start[1], end[1], i);
      color[2] = calculate(start[2], end[2], i);
      output.push(color);
    }
    return output;
  }

  var colors = calculateSteps("#f29111", "#e60000", halfcircles),
    cars = $('.testcircle');
  colors = colors.concat(calculateSteps("#d20911", "#22637e", halfcircles));

  $('.testcircle').each(function(i) {
    var $carrot = $("
", {
      "class": "testw6"
    });
    var rgb = 'rgb(' + colors[i][0] + ', ' + colors[i][1] + ', ' + colors[i][2] + ')';
    $(this).closest('li').find('.testw5').prepend($carrot);
    $(this).css('background-color', rgb);
    $(this).closest('li').find('.testw5').css('background-color', rgb);
    $(this).closest('li').find('.testw6').css('background-color', rgb);
  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="testw3">
  <ul class="testw4">
    <li>

        <span class="testcircle"><span class="testnumber">10</span></span>
        <div class="testtext">Title</div>
        <div class="testw5">
          <p>Lorem ipsum dolor sit amet.</p>
          Lorem Ipsum Link
        </div>

    </li>
    <li>

        <span class="testcircle"><span class="testnumber">10</span></span>
        <div class="testtext">Title</div>
        <div class="testw5">
          <p>Lorem ipsum dolor sit amet.</p>
          Lorem Ipsum Link
        </div>

    </li>
    <li>

        <span class="testcircle"><span class="testnumber">10</span></span>
        <div class="testtext">Title</div>
        <div class="testw5">
          <p>Lorem ipsum dolor sit amet.</p>
          Lorem Ipsum Link
        </div>

    </li>
    <li>

        <span class="testcircle"><span class="testnumber">10</span></span>
        <div class="testtext">Title</div>
        <div class="testw5">
          <p>Lorem ipsum dolor sit amet.</p>
          Lorem Ipsum Link
        </div>

    </li>
    <li>

        <span class="testcircle"><span class="testnumber">10</span></span>
        <div class="testtext">Title</div>
        <div class="testw5">
          <p>Lorem ipsum dolor sit amet.</p>
          Lorem Ipsum Link
        </div>

    </li>
    <li>

        <span class="testcircle"><span class="testnumber">10</span></span>
        <div class="testtext">Title</div>
        <div class="testw5">
          <p>Lorem ipsum dolor sit amet.</p>
          Lorem Ipsum Link
        </div>

    </li>
    <li>

        <span class="testcircle"><span class="testnumber">10</span></span>
        <div class="testtext">Title</div>
        <div class="testw5">
          <p>Lorem ipsum dolor sit amet.</p>
          Lorem Ipsum Link
        </div>

    </li>
    <li>

        <span class="testcircle"><span class="testnumber">10</span></span>
        <div class="testtext">Title</div>
        <div class="testw5">
          <p>Lorem ipsum dolor sit amet.</p>
          Lorem Ipsum Link
        </div>

    </li>
    <li>

        <span class="testcircle"><span class="testnumber">10</span></span>
        <div class="testtext">Title</div>
        <div class="testw5">
          <p>Lorem ipsum dolor sit amet.</p>
          Lorem Ipsum Link
        </div>

    </li>
    <li>

        <span class="testcircle"><span class="testnumber">10</span></span>
        <div class="testtext">Title</div>
        <div class="testw5">
          <p>Lorem ipsum dolor sit amet.</p>
          Lorem Ipsum Link
        </div>

    </li>
  </ul>
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to change the color of list items based on a gradient with a defined starting color and ending color. I'm trying to use two different color stops for the 1st and 2nd half of my list items. The problem is that only the first half is working and I get a JS error

https://jsfiddle.net/qrzms3s9/1/

jQuery(document).ready(function($) {
  if($('.test')[0]){

    var circles = $('.testcircle').length,
            halfcircles = circles / 2;

    function colorStrToIntArray(color) {
        if (color.length == 4 || color.length == 7) {
                color = color.substr(1);
        }
        if (color.length == 3) {
            var r = parseInt(color.substr(0, 1) + color.substr(0, 1), 16),
                    g = parseInt(color.substr(1, 1) + color.substr(1, 1), 16),
                    b = parseInt(color.substr(2, 1) + color.substr(2, 1), 16);

            return [r, g, b];
        }
        else if (color.length == 6) {
            return [
                parseInt(color.substr(0, 2), 16),
                parseInt(color.substr(2, 2), 16),
                parseInt(color.substr(4, 2), 16)
            ];
        }
        return false;
    }

    function calculateSteps(color1, color2, steps) {
        var output = [],
                start = colorStrToIntArray(color1),
                end = colorStrToIntArray(color2);
        var calculate = function(start, end, step) {
            return start + Math.round((end - start) * (step / (steps / 2)));
        };
        for ( var i = 0; i < steps; i++ ) {
            var color = [0, 0, 0];
            color[0] = calculate(start[0], end[0], i);
            color[1] = calculate(start[1], end[1], i);
            color[2] = calculate(start[2], end[2], i);
            output.push(color);
        }
        return output;
    }

    var colors = calculateSteps("#f29111", "#e60000", halfcircles),
            colors2 = calculateSteps("#d20911", "#22637e", halfcircles),
            cars = $('.testcircle');
            index = 0;

    $('.testcircle').each(function() {
        var $carrot = $("
", {"class": "testw6"});
        $(this).closest('li').find('.testw5').prepend($carrot);
        if (index < halfcircles) {
            $(this).css('background-color', 'rgb(' + colors[index][0] + ', ' + colors[index][1] + ', ' + colors[index][2] + ')');
            $(this).closest('li').find('.testw5').css('background-color', 'rgb(' + colors[index][0] + ', ' + colors[index][1] + ', ' + colors[index][2] + ')');
            $(this).closest('li').find('.testw6').css('background-color', 'rgb(' + colors[index][0] + ', ' + colors[index][1] + ', ' + colors[index][2] + ')');
            index++;
        }
        else {
            $(this).css('background-color', 'rgb(' + colors2[index][0] + ', ' + colors2[index][1] + ', ' + colors2[index][2] + ')');
            $(this).closest('li').find('.testw5').css('background-color', 'rgb(' + colors2[index][0] + ', ' + colors2[index][1] + ', ' + colors2[index][2] + ')');
            $(this).closest('li').find('.testw6').css('background-color', 'rgb(' + colors2[index][0] + ', ' + colors2[index][1] + ', ' + colors2[index][2] + ')');
            index++;
        }
    });

  }
});

Body:
Problem is with your index count. For the second half of iteration you need to reset the index. I have a better approach for the code - instead of resetting the index, we can have a single array of colors and point the element index from each.

jQuery(document).ready(function($) {

  var circles = $('.testcircle').length,
    halfcircles = circles / 2;

  function colorStrToIntArray(color) {
    if (color.length == 4 || color.length == 7) {
      color = color.substr(1);
    }
    if (color.length == 3) {
      var r = parseInt(color.substr(0, 1) + color.substr(0, 1), 16),
        g = parseInt(color.substr(1, 1) + color.substr(1, 1), 16),
        b = parseInt(color.substr(2, 1) + color.substr(2, 1), 16);

      return [r, g, b];
    } else if (color.length == 6) {
      return [
        parseInt(color.substr(0, 2), 16),
        parseInt(color.substr(2, 2), 16),
        parseInt(color.substr(4, 2), 16)
      ];
    }
    return false;
  }

  function calculateSteps(color1, color2, steps) {
    var output = [],
      start = colorStrToIntArray(color1),
      end = colorStrToIntArray(color2);
    var calculate = function(start, end, step) {
      return start + Math.round((end - start) * (step / (steps / 2)));
    };
    for (var i = 0; i < steps; i++) {
      var color = [0, 0, 0];
      color[0] = calculate(start[0], end[0], i);
      color[1] = calculate(start[1], end[1], i);
      color[2] = calculate(start[2], end[2], i);
      output.push(color);
    }
    return output;
  }

  var colors = calculateSteps("#f29111", "#e60000", halfcircles),
    cars = $('.testcircle');
  colors = colors.concat(calculateSteps("#d20911", "#22637e", halfcircles));

  $('.testcircle').each(function(i) {
    var $carrot = $("<div>", {
      "class": "testw6"
    });
    var rgb = 'rgb(' + colors[i][0] + ', ' + colors[i][1] + ', ' + colors[i][2] + ')';
    $(this).closest('li').find('.testw5').prepend($carrot);
    $(this).css('background-color', rgb);
    $(this).closest('li').find('.testw5').css('background-color', rgb);
    $(this).closest('li').find('.testw6').css('background-color', rgb);
  });

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="testw3">
  <ul class="testw4">
    <li>
      <a href="placeholder.html">
        <span class="testcircle"><span class="testnumber">10</span></span>
        <div class="testtext">Title</div>
        <div class="testw5">
          <p>Lorem ipsum dolor sit amet.</p>
          <a href="placeholder.html">Lorem Ipsum Link</a>
        </div>
      </a>
    </li>
    <li>
      <a href="placeholder.html">
        <span class="testcircle"><span class="testnumber">10</span></span>
        <div class="testtext">Title</div>
        <div class="testw5">
          <p>Lorem ipsum dolor sit amet.</p>
          <a href="placeholder.html">Lorem Ipsum Link</a>
        </div>
      </a>
    </li>
    <li>
      <a href="placeholder.html">
        <span class="testcircle"><span class="testnumber">10</span></span>
        <div class="testtext">Title</div>
        <div class="testw5">
          <p>Lorem ipsum dolor sit amet.</p>
          <a href="placeholder.html">Lorem Ipsum Link</a>
        </div>
      </a>
    </li>
    <li>
      <a href="placeholder.html">
        <span class="testcircle"><span class="testnumber">10</span></span>
        <div class="testtext">Title</div>
        <div class="testw5">
          <p>Lorem ipsum dolor sit amet.</p>
          <a href="placeholder.html">Lorem Ipsum Link</a>
        </div>
      </a>
    </li>
    <li>
      <a href="placeholder.html">
        <span class="testcircle"><span class="testnumber">10</span></span>
        <div class="testtext">Title</div>
        <div class="testw5">
          <p>Lorem ipsum dolor sit amet.</p>
          <a href="placeholder.html">Lorem Ipsum Link</a>
        </div>
      </a>
    </li>
    <li>
      <a href="placeholder.html">
        <span class="testcircle"><span class="testnumber">10</span></span>
        <div class="testtext">Title</div>
        <div class="testw5">
          <p>Lorem ipsum dolor sit amet.</p>
          <a href="placeholder.html">Lorem Ipsum Link</a>
        </div>
      </a>
    </li>
    <li>
      <a href="placeholder.html">
        <span class="testcircle"><span class="testnumber">10</span></span>
        <div class="testtext">Title</div>
        <div class="testw5">
          <p>Lorem ipsum dolor sit amet.</p>
          <a href="placeholder.html">Lorem Ipsum Link</a>
        </div>
      </a>
    </li>
    <li>
      <a href="placeholder.html">
        <span class="testcircle"><span class="testnumber">10</span></span>
        <div class="testtext">Title</div>
        <div class="testw5">
          <p>Lorem ipsum dolor sit amet.</p>
          <a href="placeholder.html">Lorem Ipsum Link</a>
        </div>
      </a>
    </li>
    <li>
      <a href="placeholder.html">
        <span class="testcircle"><span class="testnumber">10</span></span>
        <div class="testtext">Title</div>
        <div class="testw5">
          <p>Lorem ipsum dolor sit amet.</p>
          <a href="placeholder.html">Lorem Ipsum Link</a>
        </div>
      </a>
    </li>
    <li>
      <a href="placeholder.html">
        <span class="testcircle"><span class="testnumber">10</span></span>
        <div class="testtext">Title</div>
        <div class="testw5">
          <p>Lorem ipsum dolor sit amet.</p>
          <a href="placeholder.html">Lorem Ipsum Link</a>
        </div>
      </a>
    </li>
  </ul>
</div>


问:
Android SQLiteException during creating Table
I am getting this error again and again.Can't figure it out how to solve.I am sharing the codes.Please help!

Codes:
addnewcontact.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.sambal.contactmanager.AddNewContact">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Name:"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="79dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Mobile Number:"
        android:id="@+id/textView2"
        android:layout_below="@+id/textView"
        android:layout_alignParentStart="true"
        android:layout_marginTop="25dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Email Id:"
        android:id="@+id/textView3"
        android:layout_marginTop="26dp"
        android:layout_below="@+id/textView2"
        android:layout_alignParentStart="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/etName"
        android:layout_above="@+id/textView2"
        android:layout_alignParentEnd="true"
        android:layout_toEndOf="@+id/textView2" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/etMobileNumber"
        android:layout_above="@+id/textView3"
        android:layout_alignEnd="@+id/etName"
        android:layout_toEndOf="@+id/textView2" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:id="@+id/etEmail"
        android:layout_alignBottom="@+id/textView3"
        android:layout_alignParentEnd="true"
        android:layout_toEndOf="@+id/textView2" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="SAVE"
        android:id="@+id/btnSave"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>
</code>```

here is DataBaseHelper.java

```<code>package com.example.sambal.contactmanager;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME="contacts.db";
    private static final String TABLE_NAME="contacts";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE" + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,MOBILE_NUMBER INTEGER,E-MAIL TEXT)");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
            onCreate(db);

    }
    public boolean insertData(String name,int mobile_number,String email){
        SQLiteDatabase db = this.getWritableDatabase();

            ContentValues contentValues = new ContentValues();
            contentValues.put("NAME", name);
            contentValues.put("MOBILE_NUMBER", mobile_number);
            contentValues.put("E-MAIL", email);

            long result = db.insert(TABLE_NAME, null, contentValues);
            if (result == -1)
                return false;
            else
                return true;

        }

    }
</code>```

AddNewContact.java

```<code>package com.example.sambal.contactmanager;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AddNewContact extends AppCompatActivity {
    EditText name,mobile_number,email;
    Button save;

    private DatabaseHelper databaseHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_new_contact);

        databaseHelper=new DatabaseHelper(this);

        name= (EditText) findViewById(R.id.etName);
        mobile_number= (EditText) findViewById(R.id.etMobileNumber);
        email= (EditText) findViewById(R.id.etEmail);
        save= (Button) findViewById(R.id.btnSave);

        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                    boolean result = databaseHelper.insertData(name.getText().toString(),
                            Integer.parseInt(mobile_number.getText().toString()), email.getText().toString());
                    if (result)
                        Toast.makeText(AddNewContact.this, "Data Inserted", Toast.LENGTH_SHORT).show();
                    else
                        Toast.makeText(AddNewContact.this, "Data Not Inserted", Toast.LENGTH_SHORT).show();

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

Here is MainActivity.java

```<code>package com.example.sambal.contactmanager;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    DatabaseHelper databaseHelper;
    Button addcontact;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        databaseHelper=new DatabaseHelper(this);
        addcontact= (Button) findViewById(R.id.btnAdd);
         addcontact.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 Intent intent=new Intent(MainActivity.this,AddNewContact.class);
                 startActivity(intent);
             }
         });
    }
}
</code>```

The logcat

```<code> 03-30 23:11:27.650 28750-28750/com.example.sambal.contactmanager E/SQLiteLog: (1) near "TABLEcontacts": syntax error
03-30 23:11:27.673 28750-28750/com.example.sambal.contactmanager E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.sambal.contactmanager, PID: 28750
                                                                                android.database.sqlite.SQLiteException: near "TABLEcontacts": syntax error (code 1): , while compiling: CREATE TABLEcontacts (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,MOBILE_NUMBER INTEGER,E-MAIL TEXT)
                                                                                at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                                at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
                                                                                at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
                                                                                at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                                at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                                                at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                                                                                at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
                                                                                at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
                                                                                at com.example.sambal.contactmanager.DatabaseHelper.onCreate(DatabaseHelper.java:25)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
                                                                                at com.example.sambal.contactmanager.DatabaseHelper.insertData(DatabaseHelper.java:40)
                                                                                at com.example.sambal.contactmanager.AddNewContact$1.onClick(AddNewContact.java:33)
                                                                                at android.view.View.performClick(View.java:4790)
                                                                                at android.view.View$PerformClick.run(View.java:19883)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5268)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
03-30 23:11:54.392 29707-29707/com.example.sambal.contactmanager E/SQLiteLog: (1) near "TABLEcontacts": syntax error
03-30 23:11:54.397 29707-29707/com.example.sambal.contactmanager E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.sambal.contactmanager, PID: 29707
                                                                                android.database.sqlite.SQLiteException: near "TABLEcontacts": syntax error (code 1): , while compiling: CREATE TABLEcontacts (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,MOBILE_NUMBER INTEGER,E-MAIL TEXT)
                                                                                at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                                at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
                                                                                at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
                                                                                at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                                at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                                                at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                                                                                at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
                                                                                at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
                                                                                at com.example.sambal.contactmanager.DatabaseHelper.onCreate(DatabaseHelper.java:25)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
                                                                                at com.example.sambal.contactmanager.DatabaseHelper.insertData(DatabaseHelper.java:40)
                                                                                at com.example.sambal.contactmanager.AddNewContact$1.onClick(AddNewContact.java:33)
                                                                                at android.view.View.performClick(View.java:4790)
                                                                                at android.view.View$PerformClick.run(View.java:19883)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5268)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
03-30 23:12:08.363 30145-30145/com.example.sambal.contactmanager E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.sambal.contactmanager, PID: 30145
                                                                                java.lang.NumberFormatException: Invalid int: "fhh"
                                                                                at java.lang.Integer.invalidInt(Integer.java:138)
                                                                                at java.lang.Integer.parse(Integer.java:410)
                                                                                at java.lang.Integer.parseInt(Integer.java:367)
                                                                                at java.lang.Integer.parseInt(Integer.java:334)
                                                                                at com.example.sambal.contactmanager.AddNewContact$1.onClick(AddNewContact.java:34)
                                                                                at android.view.View.performClick(View.java:4790)
                                                                                at android.view.View$PerformClick.run(View.java:19883)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5268)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
</code>```

答:
The syntax is
"Create table(space here)table name..."
While see your logcat, see the query, you are missing space between TABLE and CONTACTS.

It's better to use " create table if not exists"

Body:
I am getting this error again and again.Can't figure it out how to solve.I am sharing the codes.Please help!

Codes:
addnewcontact.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.sambal.contactmanager.AddNewContact">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Name:"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="79dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Mobile Number:"
        android:id="@+id/textView2"
        android:layout_below="@+id/textView"
        android:layout_alignParentStart="true"
        android:layout_marginTop="25dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Email Id:"
        android:id="@+id/textView3"
        android:layout_marginTop="26dp"
        android:layout_below="@+id/textView2"
        android:layout_alignParentStart="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/etName"
        android:layout_above="@+id/textView2"
        android:layout_alignParentEnd="true"
        android:layout_toEndOf="@+id/textView2" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/etMobileNumber"
        android:layout_above="@+id/textView3"
        android:layout_alignEnd="@+id/etName"
        android:layout_toEndOf="@+id/textView2" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:id="@+id/etEmail"
        android:layout_alignBottom="@+id/textView3"
        android:layout_alignParentEnd="true"
        android:layout_toEndOf="@+id/textView2" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="SAVE"
        android:id="@+id/btnSave"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

here is DataBaseHelper.java

package com.example.sambal.contactmanager;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME="contacts.db";
    private static final String TABLE_NAME="contacts";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE" + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,MOBILE_NUMBER INTEGER,E-MAIL TEXT)");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
            onCreate(db);

    }
    public boolean insertData(String name,int mobile_number,String email){
        SQLiteDatabase db = this.getWritableDatabase();

            ContentValues contentValues = new ContentValues();
            contentValues.put("NAME", name);
            contentValues.put("MOBILE_NUMBER", mobile_number);
            contentValues.put("E-MAIL", email);

            long result = db.insert(TABLE_NAME, null, contentValues);
            if (result == -1)
                return false;
            else
                return true;

        }

    }

AddNewContact.java

package com.example.sambal.contactmanager;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AddNewContact extends AppCompatActivity {
    EditText name,mobile_number,email;
    Button save;

    private DatabaseHelper databaseHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_new_contact);

        databaseHelper=new DatabaseHelper(this);

        name= (EditText) findViewById(R.id.etName);
        mobile_number= (EditText) findViewById(R.id.etMobileNumber);
        email= (EditText) findViewById(R.id.etEmail);
        save= (Button) findViewById(R.id.btnSave);

        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                    boolean result = databaseHelper.insertData(name.getText().toString(),
                            Integer.parseInt(mobile_number.getText().toString()), email.getText().toString());
                    if (result)
                        Toast.makeText(AddNewContact.this, "Data Inserted", Toast.LENGTH_SHORT).show();
                    else
                        Toast.makeText(AddNewContact.this, "Data Not Inserted", Toast.LENGTH_SHORT).show();

            }
        });
    }
}

Here is MainActivity.java

package com.example.sambal.contactmanager;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    DatabaseHelper databaseHelper;
    Button addcontact;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        databaseHelper=new DatabaseHelper(this);
        addcontact= (Button) findViewById(R.id.btnAdd);
         addcontact.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 Intent intent=new Intent(MainActivity.this,AddNewContact.class);
                 startActivity(intent);
             }
         });
    }
}

The logcat

 03-30 23:11:27.650 28750-28750/com.example.sambal.contactmanager E/SQLiteLog: (1) near "TABLEcontacts": syntax error
03-30 23:11:27.673 28750-28750/com.example.sambal.contactmanager E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.sambal.contactmanager, PID: 28750
                                                                                android.database.sqlite.SQLiteException: near "TABLEcontacts": syntax error (code 1): , while compiling: CREATE TABLEcontacts (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,MOBILE_NUMBER INTEGER,E-MAIL TEXT)
                                                                                at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                                at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
                                                                                at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
                                                                                at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                                at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                                                at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                                                                                at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
                                                                                at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
                                                                                at com.example.sambal.contactmanager.DatabaseHelper.onCreate(DatabaseHelper.java:25)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
                                                                                at com.example.sambal.contactmanager.DatabaseHelper.insertData(DatabaseHelper.java:40)
                                                                                at com.example.sambal.contactmanager.AddNewContact$1.onClick(AddNewContact.java:33)
                                                                                at android.view.View.performClick(View.java:4790)
                                                                                at android.view.View$PerformClick.run(View.java:19883)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5268)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
03-30 23:11:54.392 29707-29707/com.example.sambal.contactmanager E/SQLiteLog: (1) near "TABLEcontacts": syntax error
03-30 23:11:54.397 29707-29707/com.example.sambal.contactmanager E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.sambal.contactmanager, PID: 29707
                                                                                android.database.sqlite.SQLiteException: near "TABLEcontacts": syntax error (code 1): , while compiling: CREATE TABLEcontacts (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,MOBILE_NUMBER INTEGER,E-MAIL TEXT)
                                                                                at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                                at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
                                                                                at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
                                                                                at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                                at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                                                at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                                                                                at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
                                                                                at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
                                                                                at com.example.sambal.contactmanager.DatabaseHelper.onCreate(DatabaseHelper.java:25)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
                                                                                at com.example.sambal.contactmanager.DatabaseHelper.insertData(DatabaseHelper.java:40)
                                                                                at com.example.sambal.contactmanager.AddNewContact$1.onClick(AddNewContact.java:33)
                                                                                at android.view.View.performClick(View.java:4790)
                                                                                at android.view.View$PerformClick.run(View.java:19883)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5268)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
03-30 23:12:08.363 30145-30145/com.example.sambal.contactmanager E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.sambal.contactmanager, PID: 30145
                                                                                java.lang.NumberFormatException: Invalid int: "fhh"
                                                                                at java.lang.Integer.invalidInt(Integer.java:138)
                                                                                at java.lang.Integer.parse(Integer.java:410)
                                                                                at java.lang.Integer.parseInt(Integer.java:367)
                                                                                at java.lang.Integer.parseInt(Integer.java:334)
                                                                                at com.example.sambal.contactmanager.AddNewContact$1.onClick(AddNewContact.java:34)
                                                                                at android.view.View.performClick(View.java:4790)
                                                                                at android.view.View$PerformClick.run(View.java:19883)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5268)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)


问:
XmlReader.Read() getting name and value
I've been at this for a few hours now and was hoping someone could point me in the right direction.
my psuedo xml file:

```<code><Parent>
    <child Seq="1">
        <Num1>1137555</Num1>
    </Child>
    <Child2>
        <Text1>random text</Text1>
    </Child2>
</Parent>
</code>```

I'm trying to get a reference to the Elements Name(in this case "Num1") and it's value("1137555"). I understand that the reader will read Num1 first, and then the content but my code seems to be skipping over a large chunk of my xml. I have about 16 different child elements nested in the parent element but i'm only getting back perhaps the last half of them.
My Code:

```<code>while (xmlReader.Read())
{
    if (xmlReader.NodeType == XmlNodeType.Element)
    {
        Console.WriteLine(xmlReader.Name);
    }
    if (xmlReader.HasValue)
    {
        Console.WriteLine(xmlReader.Value);
    }
}
</code>```

答:
1) I would suggest to take a look at XDocument.

2) There is an error in your XML structure your first Child node is invalid.

<child></Child>  (the first c is not in capital case)

Here is my code using XDocument:

```<code>var xml = "<Parent><Child Seq='1'><Num1>1137555</Num1></Child><Child2><Text1>random text</Text1></Child2></Parent>";
var document = XDocument.Parse(xml);

foreach (var child in document.Root.Elements("Child"))
{
    child.Element("Num1").Value.Dump();
}
</code>```

Output:

Title: XmlReader.Read() getting name and value

Body:
I've been at this for a few hours now and was hoping someone could point me in the right direction.
my psuedo xml file:

<Parent>
    <child Seq="1">
        <Num1>1137555</Num1>
    </Child>
    <Child2>
        <Text1>random text</Text1>
    </Child2>
</Parent>

I'm trying to get a reference to the Elements Name(in this case "Num1") and it's value("1137555"). I understand that the reader will read Num1 first, and then the content but my code seems to be skipping over a large chunk of my xml. I have about 16 different child elements nested in the parent element but i'm only getting back perhaps the last half of them.
My Code:

while (xmlReader.Read())
{
    if (xmlReader.NodeType == XmlNodeType.Element)
    {
        Console.WriteLine(xmlReader.Name);
    }
    if (xmlReader.HasValue)
    {
        Console.WriteLine(xmlReader.Value);
    }
}

Body:
1) I would suggest to take a look at XDocument.

2) There is an error in your XML structure your first Child node is invalid.

<child></Child>  (the first c is not in capital case)

Here is my code using XDocument:

var xml = "<Parent><Child Seq='1'><Num1>1137555</Num1></Child><Child2><Text1>random text</Text1></Child2></Parent>";
var document = XDocument.Parse(xml);

foreach (var child in document.Root.Elements("Child"))
{
    child.Element("Num1").Value.Dump();
}

Output:


问:
check if two integers sum to a third
Ok I'm doing this programming assignment and need a little help.

Here is the problem:

Given three ints, a b c, return true if it is possible to add two of the ints to get the third.

```<code>twoAsOne(1, 2, 3) → true
twoAsOne(3, 1, 2) → true
twoAsOne(3, 2, 2) → false
</code>```

Here's the what I have gotten so far:

```<code>public boolean twoAsOne(int a, int b, int c) {
  return a + b != c;
}
</code>```

It keeps saying it is not fully correct and I do not know where I am going wrong.

答:
I might be very late yet I have minimized it. twoAsOne</p>

```<code>public boolean twoAsOne(integer a, integer b, integer c){
    return ((a+b) == c ? true : (a+c) == b ? true : (b+c == a)? true : false);
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: check if two integers sum to a third

Body:
Ok I'm doing this programming assignment and need a little help.

Here is the problem:

Given three ints, a b c, return true if it is possible to add two of the ints to get the third.

twoAsOne(1, 2, 3) → true
twoAsOne(3, 1, 2) → true
twoAsOne(3, 2, 2) → false

Here's the what I have gotten so far:

public boolean twoAsOne(int a, int b, int c) {
  return a + b != c;
}

It keeps saying it is not fully correct and I do not know where I am going wrong.

Body:
I might be very late yet I have minimized it. twoAsOne

public boolean twoAsOne(integer a, integer b, integer c){
    return ((a+b) == c ? true : (a+c) == b ? true : (b+c == a)? true : false);
}


问:
Why do we take the derivative of the transfer function in calculating back propagation algorithm?
What is the concept behind taking the derivative? It's interesting that for somehow teaching a system, we have to adjust its weights. But why are we doing this using a derivation of the transfer function. What is in derivation that helps us. I know derivation is the slope of a continuous function at a given point, but what does it have to do with the problem.</p>

答:
You must already know that the cost function is a function with the weights as the variables.
For now consider it as f(W).

Our main motive here is to find a W for which we get the minimum value for f(W).

One of the ways for doing this is to plot function f in one axis and W in another....... but remember that here W is not just a single variable but a collection of variables.

So what can be the other way?
It can be as simple as changing values of W and see if we get a lower value or not than the previous value of W.

But taking random values for all the variables in W can be a tedious task.

So what we do is, we first take random values for W and see the output of f(W) and the slope at all the values of each variable(we get this by partially differentiating the function with the i'th variable and putting the value of the i'th variable).

now once we know the slope at that point in space we move a little further towards the lower side in the slope (this little factor is termed alpha in gradient descent) and this goes on until the slope gives a opposite value stating we already reached the lowest point in the graph(graph with n dimensions, function vs W, W being a collection of n variables).


问:
Slice implementation with negative step
What is the start and stop value when we are doing [::-1] for any sequence?
I know it will reverse the string. But want to understand how it is implemented.
s[:] - for this start is 0 and stop is len(s).

So how is it working for s[::-1]

Can somebody please explain how it is implemented?

答:
In terms of "where does it start" and "where does it stop", it starts at the last element and stops at the first. I think you knew that already, though.

In terms of "what actual start and stop values does the sequence receive", the start and stop are actually None. Any omitted slice argument is implicitly None, so

```<code>s[::-1]
</code>```

is equivalent to

```<code>s[None:None:-1]
</code>```

The sequence will interpret None appropriately depending on the slice direction.

Title: Slice implementation with negative step

Body:
In terms of "where does it start" and "where does it stop", it starts at the last element and stops at the first. I think you knew that already, though.

In terms of "what actual start and stop values does the sequence receive", the start and stop are actually None. Any omitted slice argument is implicitly None, so

s[::-1]

is equivalent to

s[None:None:-1]

The sequence will interpret None appropriately depending on the slice direction.


问:
Registration from using PHP, SQL and Javascript
I am currently making a registration form using PHP, SQL and Javascript. I have a problem that is in the PHP script. If the code is without the PHP part, everything works perfectly, but if the PHP is a part of the code, it gives me a blank page when loaded. Please give me suggestions how to figure the problem out. Thank you in advance.</p>

```<code><!DOCTYPE html>
<html lang="en-US" class="Html" id="Main" dir="auto">
<head class="Head" id="Main">
<link rel="stylesheet" type="text/css" href="style.css">
<meta name="description" content="123">
<meta name="author" content="123">
<title class="Title" id="Title">Registration</title>
</head>
<body class="Body" id="Main">
<nav>
    <ul>
        <li><a href="home.php">Home</a></li>
        <li><a href="about.php">About</a></li>
        <li><a href="albums.php">The Albums</a></li>
        <li><a href="shoppingcart.php">Shopping Cart</a></li>
    </ul>
</nav>
<div class="a00">Registration</div>

<script type="text/javascript">

function FormValidation(theForm) {
var errors = "";
var email = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
var username = /^[a-zA-Z0-9]{3,15}$/;
var password = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*][a-zA-Z0-9!@#\$%\^&\*]{8,16}$/;

if (theForm.one.value == "") {
    errors += "Please enter your username name! \n";
}

else if (!username.test(theForm.one.value)) {
    errors += "Username is wrong! \n";
    errors += "Username includes wrong characters! \n";
    errors += "Username must include only alphabetical and numeric characters! \n";
    errors += "Username must be between 3 and 15 characters! \n";
}

if (theForm.two.value == "") {
    errors += "Please enter your password! \n";
}

else if (!password.test(theForm.two.value)) {
    errors += "Password is wrong! \n";
    errors += "Password includes wrong characters! \n";
    errors += "Password must include at least one uppercase alphabetical character! \n";
    errors += "Password must include at least one lowercase alphabetical character! \n";
    errors += "Password must include at least one numerical character! \n";
    errors += "Password must include at least one special character! \n";
    errors += "Username must be between 8 and 16 characters! \n";
}

if (theForm.three.value == "") {
    errors += "Please enter your e-mail address! \n";
}

else if (!email.test(theForm.three.value)) {
    errors += "E-mail address is wrong \n";
    errors += "E-mail address must be in the right format! \n";
}

if (!errors == "") {
    alert("LIST OF ERRORS: \n" + errors);
    return false;
} else {
    return true;
}
}

function ShowHelpUsername() {
document.getElementById("demo1").innerHTML = "Help: Fill in your username. It must be unique and easy to remmeber.";
}

function ShowHelpPassword() {
document.getElementById("demo1").innerHTML = "Help: Fill in your password. It must include 1 uppercase alphabetical character, 1 lowercase alphabetical character, 1 numeric character, and 1 special character.";
}

function ShowHelpEmail() {
document.getElementById("demo1").innerHTML = "Help: Fill in your personal electronic mail.";
}

</script>

<?php
$con = mysqli_connect("", "","", "");
if (!$con) {
die("Error: " . mysqli_connect_error());
}

if (isset($_POST['register'])) {

$username=mysql_real_escape_string($_POST['one']);
$email=mysql_real_escape_string($_POST['three']);
$password=mysql_real_escape_string($_POST['two']);
$mysqlget="INSERT INTO users (username,email,password) VALUES ('$username','$email','$password')";

mysqli_query($con, $mysqlget) or die ("Error: " . mysql_error($con));

}
?>

<form method="POST" action="registration.php" class="myForm" name="myForm" onSubmit="javascript:return FormValidation(this)">
<div class="form-group-username">
<label for="username">Username</label><br>
<input type="text" placeholder="Between 3 and 15 characters" class="form-control-1" id="one" name="one" onfocus="ShowHelpUsername()">
</div>
<div class="form-group-password">
<label for="password">Password</label><br>
<input type="password" placeholder="Between 8 and 16 characters" class="form-control-2" id="two" name="two" onfocus="ShowHelpPassword()">
</div>
<div class="form-group-email">
<label for="e-mail">E-mail</label><br>
<input type="text" placeholder="For safety purposes" class="form-control-3" id="three" name="three" onfocus="ShowHelpEmail()">
</div>
<div class="form-group-submit">
<input type="submit" name="register" class="submit_form_55" value="Create Account">
</div>
<div class="form-group-help">
<p id="demo1"></p>
</div>

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

答:
If you can't see an error message [only blank pages meaning you had errors] you should check PHP log files. Some errors are not displayed on the browser for security reasons.

Log locations might differ from versions, on linux systems you might check /var/logs/httpd or something like that.

Check this thread: How to get useful error messages in PHP?

Body:
I am currently making a registration form using PHP, SQL and Javascript. I have a problem that is in the PHP script. If the code is without the PHP part, everything works perfectly, but if the PHP is a part of the code, it gives me a blank page when loaded. Please give me suggestions how to figure the problem out. Thank you in advance.

<!DOCTYPE html>

<link rel="stylesheet" type="text/css" href="style.css">
<meta name="description" content="123">
<meta name="author" content="123">
<title class="Title" id="Title">Registration</title>

Home

About

The Albums

Shopping Cart

Registration

<?php
$con = mysqli_connect("", "","", "");
if (!$con) {
die("Error: " . mysqli_connect_error());
}

if (isset($_POST['register'])) {

$username=mysql_real_escape_string($_POST['one']);
$email=mysql_real_escape_string($_POST['three']);
$password=mysql_real_escape_string($_POST['two']);
$mysqlget="INSERT INTO users (username,email,password) VALUES ('$username','$email','$password')";

mysqli_query($con, $mysqlget) or die ("Error: " . mysql_error($con));

}
?>

<form method="POST" action="registration.php" class="myForm" name="myForm" onSubmit="javascript:return FormValidation(this)">

Username

<input type="text" placeholder="Between 3 and 15 characters" class="form-control-1" id="one" name="one" onfocus="ShowHelpUsername()">

Password

<input type="password" placeholder="Between 8 and 16 characters" class="form-control-2" id="two" name="two" onfocus="ShowHelpPassword()">

E-mail

<input type="text" placeholder="For safety purposes" class="form-control-3" id="three" name="three" onfocus="ShowHelpEmail()">

<input type="submit" name="register" class="submit_form_55" value="Create Account">

</form>


问:
HTML - relationship between  vs
My goal is to come up with a dropdown menu:

$(document).on('click', '.dropdown', function() {
  var is_visible = $(this).find('.dropdown-content').is(":visible");
  $('.dropdown-content').toggle(false);

  if (is_visible == false){
    $(this).find('.dropdown-content').toggle(true);
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dropdown {
  position: relative;
  display: inline-block;
  cursor: pointer;
}

div.dropdown-content {
  display: none;
  white-space: nowrap;
  position: absolute;
  padding: 12px 16px;
  z-index: 1;
  margin-top: 15px;
  background: white;
}</code>```

<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"/>

 Share

 Delete

```

The question is, what is the semantic role of  tag in the dropdown-content item definition (provided I don't use its href attribute and use JavaScript to handle the click event)?

In other words: if I want to have a clickable icon, in which cases should I surround it with an  tag?

答:
if I want to have a clickable icon, in which cases should I surround it with  tag?

The only case where you should wrap anything with an  tag is if it's a link, or a placeholder for where a link could be.

Otherwise, if you want to make something clickable, the appropriate element is <button type="button">.

The one exception to that is if you need to wrap anything that's not phrasing content, in which case I recommend using
 with a keydown handler to trigger click events on Enter, and Space.

Additional notes about accessibility for icons, and icon fonts in general: If a network request fails and the icon font fails to load, your sighted users will find themselves in the same situation as your non-sighted users, where it's unclear as to what the button should do.

Generally speaking it's better to pair icons with textual labels, but if that's not possible, consider using an  element with [alt] text instead of the icon.

If that's not possible, at least add an [aria-label] attribute.

Title: HTML - relationship between <a> vs <i>

Body:
My goal is to come up with a dropdown menu:

$(document).on('click', '.dropdown', function() {
  var is_visible = $(this).find('.dropdown-content').is(":visible");
  $('.dropdown-content').toggle(false);

  if (is_visible == false){
    $(this).find('.dropdown-content').toggle(true);
  }
});

.dropdown {
  position: relative;
  display: inline-block;
  cursor: pointer;
}

div.dropdown-content {
  display: none;
  white-space: nowrap;
  position: absolute;
  padding: 12px 16px;
  z-index: 1;
  margin-top: 15px;
  background: white;
}

<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"/>

 Share

 Delete

The question is, what is the semantic role of  tag in the dropdown-content item definition (provided I don't use its href attribute and use JavaScript to handle the click event)?

In other words: if I want to have a clickable icon, in which cases should I surround it with an  tag?

Body:
if I want to have a clickable icon, in which cases should I surround it with <a> tag?

The only case where you should wrap anything with an <a> tag is if it's a link, or a placeholder for where a link could be.

Otherwise, if you want to make something clickable, the appropriate element is <button type="button">.

The one exception to that is if you need to wrap anything that's not phrasing content, in which case I recommend using <div role="button" tabindex="0> with a keydown handler to trigger click events on Enter, and Space.

Additional notes about accessibility for icons, and icon fonts in general: If a network request fails and the icon font fails to load, your sighted users will find themselves in the same situation as your non-sighted users, where it's unclear as to what the button should do.

Generally speaking it's better to pair icons with textual labels, but if that's not possible, consider using an <img> element with [alt] text instead of the icon.

If that's not possible, at least add an [aria-label] attribute.


问:
Functional dependencies in database
I have the following set of functional dependencies on the relation
schema r(A, B, C, D, E, F ) :

```<code>A -> BCD
BC -> DE
B -> D
D -> A
</code>```

Can anyone show with explanation how to find the candidate keys for this relation ?

答:
Short answer: The candidate keys are (A,F), (B,F) and (D,F).

Like this Wikipedia article says:

The set of all candidate keys can be computed e.g. from the set of
  functional dependencies. To this end we need to define the attribute
  closure α+ for an attribute set α. The set
  α+ contains all attributes that are functionally
  implied by α.

It is quite simple to find a single candidate key. We start with a
  set α of attributes and try to remove successively each
  attribute. If after removing an attribute the attribute closure
  stays the same, then this attribute is not necessary and we can
  remove it permanently. We call the result minimize(α). If α is the set of all attributes, then minimize(α) is a candidate key.

So now we only need to put this into practice. Let's start with all attributes α0=(A,B,C,D,E,F). Now we can look whether removing A generates a problem. With α'0=(B,C,D,E,F), α'0+ is (B,C,D,E,F,A) (since D→ A holds). Now by kicking out A permanently and trying to remove B, we will end up with a candidate key.

α1=(B,C,D,E,F). Can we throw out B? Yes because α'1=(C,D,E,F) will result in α'1+=(A,B,C,D,E,F) (since D→A and A→BCD).

α2=(C,D,E,F). Can we throw out C? Yes because α'2=(D,E,F) will result in α'2+=(A,B,C,D,E,F) (since D→A and A→BCD).

α3=(D,E,F). Can we throw out D? No because α'3=(E,F) will result in α'3+=(E,F).

α3=(D,E,F). Can we throw out E? Yes because α'3=(D,F) will result in α'3+=(A,B,C,D,E,F) (since D→A; A→BCD; and BC→DE).

α4=(D,F). Can we throw out F? No because α'4=(D) will result in α'4+=(A,B,C,D,E) (since D→A; A→BCD; and BC→DE).

So now we generated minimize(α0)=α4=(D,F). We could use a brute force approach where in each iteration we iterate over all possible keys we can remove. But this will cost exponential time to generate.

The Wikipedia article however includes a way to generate all candidate keys polynomial in the number of keys and the functional dependencies. The algorithm is defined as:

```<code>function find_candidate_keys(A, F)
/* A is the set of all attributes and F is the set of functional dependencies */
K[0] := minimize(A);
n := 1; /* Number of Keys known so far */
i := 0; /* Currently processed key */
while i < n do
  foreach α → β ∈ F do
    /* Build a new potential key from the previous known key and the current FD */
    S := α ∪ (K[i] − β);
    /* Search whether the new potential key is part of the already known keys */
    found := false;
    for j := 0 to n-1 do
      if K[j] ⊆ S then found := true;
    /* If not, add if
    if not found then
      K[n] := minimize(S);
      n := n + 1;
  i := i + 1
return K
</code>```

So if we run the algorithm, we first have to calculate minimize(A), but the nice thing is: we already did that above. So K[0] = (D,F), n=1 and i=0.

Now we take the while loop and start iterating over all functional dependencies.

for A→ BCD. So now we construct a key (A,F). We check if there is already a subset defined as key (which is not the case). Now we minimize it, like: (A,F)→(A,F). So we add a new key (A,F).

for BC→DE. So now we construct a key (B,C,F). We check if there is already a subset defined as key (which is not the case). Now we minimize it, like (B,C,F)→(B,F)→(B,F). So we add (B,F).

for B→D. So now we construct a key (B,F). We check if there is already a subset defined as key (this is the case). We don't add this one.

for D→A. So now we construct a key (D,F). We check if there is already a subset defined as key (this is the case). We don't add this one.

This is the end of the first iteration. So K is now K=[(D,F),(A,F),(B,F)]. n=3 and now i=1. So for K[i]=(A,F) we now iterate:

for A→ BCD. So now we construct a key (A,F). We check if there is already a subset defined as key (this is the case). We don't add this one.

for BC→DE. So now we construct a key (B,C,F). We check if there is already a subset defined as key (this is the case). We don't add this one.

for B→D. So now we construct a key (A,B,F). We check if there is already a subset defined as key (this is the case). We don't add this one.

for D→A. So now we construct a key (D,F). We check if there is already a subset defined as key (this is the case). We don't add this one.

This is the end of the second iteration. So K is now K=[(D,F),(A,F),(B,F)]. n=3 and now i=2. So for K[i]=(B,F) we now iterate:

for A→ BCD. So now we construct a key (A,F). We check if there is already a subset defined as key (this is the case). We don't add this one.

for BC→DE. So now we construct a key (B,C,F). We check if there is already a subset defined as key (this is the case). We don't add this one.

for B→D. So now we construct a key (B,F). We check if there is already a subset defined as key (this is the case). We don't add this one.

for D→A. So now we construct a key (B,D,F). We check if there is already a subset defined as key (this is the case). We don't add this one.

So at the end K=[(D,F),(A,F),(B,F)]. These are all candidate keys.

Title: Functional dependencies in database

Body:
I have the following set of functional dependencies on the relation
schema r(A, B, C, D, E, F ) :

A -> BCD
BC -> DE
B -> D
D -> A

Can anyone show with explanation how to find the candidate keys for this relation ?

Body:
Short answer: The candidate keys are (A,F), (B,F) and (D,F).

Like this Wikipedia article says:

The set of all candidate keys can be computed e.g. from the set of
  functional dependencies. To this end we need to define the attribute
  closure α+ for an attribute set α. The set
  α+ contains all attributes that are functionally
  implied by α.

It is quite simple to find a single candidate key. We start with a
  set α of attributes and try to remove successively each
  attribute. If after removing an attribute the attribute closure
  stays the same, then this attribute is not necessary and we can
  remove it permanently. We call the result minimize(α). If α is the set of all attributes, then minimize(α) is a candidate key.

So now we only need to put this into practice. Let's start with all attributes α0=(A,B,C,D,E,F). Now we can look whether removing A generates a problem. With α'0=(B,C,D,E,F), α'0+ is (B,C,D,E,F,A) (since D→ A holds). Now by kicking out A permanently and trying to remove B, we will end up with a candidate key.

α1=(B,C,D,E,F). Can we throw out B? Yes because α'1=(C,D,E,F) will result in α'1+=(A,B,C,D,E,F) (since D→A and A→BCD).

α2=(C,D,E,F). Can we throw out C? Yes because α'2=(D,E,F) will result in α'2+=(A,B,C,D,E,F) (since D→A and A→BCD).

α3=(D,E,F). Can we throw out D? No because α'3=(E,F) will result in α'3+=(E,F).

α3=(D,E,F). Can we throw out E? Yes because α'3=(D,F) will result in α'3+=(A,B,C,D,E,F) (since D→A; A→BCD; and BC→DE).

α4=(D,F). Can we throw out F? No because α'4=(D) will result in α'4+=(A,B,C,D,E) (since D→A; A→BCD; and BC→DE).

So now we generated minimize(α0)=α4=(D,F). We could use a brute force approach where in each iteration we iterate over all possible keys we can remove. But this will cost exponential time to generate.

The Wikipedia article however includes a way to generate all candidate keys polynomial in the number of keys and the functional dependencies. The algorithm is defined as:

function find_candidate_keys(A, F)
/* A is the set of all attributes and F is the set of functional dependencies */
K[0] := minimize(A);
n := 1; /* Number of Keys known so far */
i := 0; /* Currently processed key */
while i < n do
  foreach α → β ∈ F do
    /* Build a new potential key from the previous known key and the current FD */
    S := α ∪ (K[i] − β);
    /* Search whether the new potential key is part of the already known keys */
    found := false;
    for j := 0 to n-1 do
      if K[j] ⊆ S then found := true;
    /* If not, add if
    if not found then
      K[n] := minimize(S);
      n := n + 1;
  i := i + 1
return K

So if we run the algorithm, we first have to calculate minimize(A), but the nice thing is: we already did that above. So K[0] = (D,F), n=1 and i=0.

Now we take the while loop and start iterating over all functional dependencies.

for A→ BCD. So now we construct a key (A,F). We check if there is already a subset defined as key (which is not the case). Now we minimize it, like: (A,F)→(A,F). So we add a new key (A,F).

for BC→DE. So now we construct a key (B,C,F). We check if there is already a subset defined as key (which is not the case). Now we minimize it, like (B,C,F)→(B,F)→(B,F). So we add (B,F).

for B→D. So now we construct a key (B,F). We check if there is already a subset defined as key (this is the case). We don't add this one.

for D→A. So now we construct a key (D,F). We check if there is already a subset defined as key (this is the case). We don't add this one.

This is the end of the first iteration. So K is now K=[(D,F),(A,F),(B,F)]. n=3 and now i=1. So for K[i]=(A,F) we now iterate:

for A→ BCD. So now we construct a key (A,F). We check if there is already a subset defined as key (this is the case). We don't add this one.

for BC→DE. So now we construct a key (B,C,F). We check if there is already a subset defined as key (this is the case). We don't add this one.

for B→D. So now we construct a key (A,B,F). We check if there is already a subset defined as key (this is the case). We don't add this one.

for D→A. So now we construct a key (D,F). We check if there is already a subset defined as key (this is the case). We don't add this one.

This is the end of the second iteration. So K is now K=[(D,F),(A,F),(B,F)]. n=3 and now i=2. So for K[i]=(B,F) we now iterate:

for A→ BCD. So now we construct a key (A,F). We check if there is already a subset defined as key (this is the case). We don't add this one.

for BC→DE. So now we construct a key (B,C,F). We check if there is already a subset defined as key (this is the case). We don't add this one.

for B→D. So now we construct a key (B,F). We check if there is already a subset defined as key (this is the case). We don't add this one.

for D→A. So now we construct a key (B,D,F). We check if there is already a subset defined as key (this is the case). We don't add this one.

So at the end K=[(D,F),(A,F),(B,F)]. These are all candidate keys.


问:
Change setMyLocationEnabled button location on screen
When using Google Maps V2 on Android, when I call function:

```<code>googleMap.setMyLocationEnabled(true);
</code>```

It gives the button for the current location on TOP-RIGHT of map. I want to change that button location to left-bottom with my custom theme.

What should I do?

答:
add this in your onMapReady() method</p>

```<code>if (mapView != null &&
            mapView.findViewById(Integer.parseInt("1")) != null) {
        // Get the button view
        View locationButton = ((View) mapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
        // and next place it, on bottom right (as Google Maps app)
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)
                locationButton.getLayoutParams();
        // position on right bottom above zoomLayout
        View zoom_in_button = mapView.findViewWithTag("GoogleMapZoomInButton");
        View zoom_layout = (View) zoom_in_button.getParent();
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
        layoutParams.addRule(RelativeLayout.ABOVE, zoom_layout.getId());
        layoutParams.setMargins(0, 0, 30, 30);
    }
</code>```

Body:
When using Google Maps V2 on Android, when I call function:

googleMap.setMyLocationEnabled(true);

It gives the button for the current location on TOP-RIGHT of map. I want to change that button location to left-bottom with my custom theme.

What should I do?

Body:
add this in your onMapReady() method

if (mapView != null &&
            mapView.findViewById(Integer.parseInt("1")) != null) {
        // Get the button view
        View locationButton = ((View) mapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
        // and next place it, on bottom right (as Google Maps app)
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)
                locationButton.getLayoutParams();
        // position on right bottom above zoomLayout
        View zoom_in_button = mapView.findViewWithTag("GoogleMapZoomInButton");
        View zoom_layout = (View) zoom_in_button.getParent();
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
        layoutParams.addRule(RelativeLayout.ABOVE, zoom_layout.getId());
        layoutParams.setMargins(0, 0, 30, 30);
    }


问:
Git - show file diff between HEAD and initial (first) version
Suppose some repository at some point has created a file test.txt and committed it to the repository with some data. The file might not be present in the repository's initial commit.

Next, a lot of commits make changes to this file.
Now, I want to produce diff output that shows the difference between the initial (first) version of the file test.txt and the current (HEAD).
How do I do this?

EDIT: Question changed to note that the file might not be present in initial commit.

答:
Based on soundslikeodd's answer. Not actually an answer.

This is the script I wrote for myself to use and why not share it here... It takes any file under git version control and git diffs it do the file's earliest version. I think this will not work reliably if the same file was added multiple times (and removed in between) and I haven't thoroughly tested this. The thing I did though, is to make sure that I can use this script from anywhere (I set it as an alias).

```<code>#!/bin/bash
#takes a file under git version control as the first argument. diffs with the files original version.
cd $(dirname "$1")
git diff $(git log --oneline --diff-filter=A -- $1 | awk '{print $1}') HEAD $1
</code>```

The reason I add this as an answer is just that it wouldn't be nicely formatted as a comment. Please tell me if this kind of answer is not appreciated here.

Body:
Based on soundslikeodd's answer. Not actually an answer.

This is the script I wrote for myself to use and why not share it here... It takes any file under git version control and git diffs it do the file's earliest version. I think this will not work reliably if the same file was added multiple times (and removed in between) and I haven't thoroughly tested this. The thing I did though, is to make sure that I can use this script from anywhere (I set it as an alias).

#!/bin/bash
#takes a file under git version control as the first argument. diffs with the files original version.
cd $(dirname "$1")
git diff $(git log --oneline --diff-filter=A -- $1 | awk '{print $1}') HEAD $1

The reason I add this as an answer is just that it wouldn't be nicely formatted as a comment. Please tell me if this kind of answer is not appreciated here.


问:
Is Spring bean thread safe for Jedis?
We are not too sure if we apply Jedis pool correctly in order to achieve a Jedis thread-safe using Spring beans

```<code><bean id="redisOnlineManager" class="com.app.online.RedisOnlineManager>
<property name="pool">
    <bean class="redis.clients.jedis.JedisPool">
        <constructor-arg value="redis://localhost:1234/1" />
    </bean>
</property>
</code>```

```<code>private JedisPool pool;

public void setPool(JedisPool pool) {
    this.pool = pool;
}

private boolean exists(String key) {
    Jedis jedis = pool.getResource();
    try {
        return jedis.exists(key);
    } finally {
        jedis.close();
    }
}
</code>```

Did we implement Jedis pool correctly? does this code perform a thread-safe Jedis? If not, how should we use spring beans to make jedis threadsafe?

Please advise.. Thanks

答:
What he is trying to say is that create the pool in a spring singleton bean Or class with static method for accessing pool. If you do either of it, you should be fine. What you have done in the code is that You are creating a pool for each instance of the ResourceManager and it can be improved like the following.

```<code>@Scope("singleton")
public class ResourceManager {

    private JedisPool pool ;

    public ResourceManager(){
        pool = new JedisPool(new JedisPoolConfig(), "localhost");
    }

    private boolean exists(String key) {
        Jedis jedis = pool.getResource();
        try {
            return jedis.exists(key);
        } finally {
            jedis.close();
        }
    }

}
</code>```

Your application context will not have the inner bean.

```<code><bean id="redisOnlineManager" class="com.app.online.RedisOnlineManager/><!-- you dont need this in the application context if you are using annotations -->
</code>```

Title: Is Spring bean thread safe for Jedis?

Body:
We are not too sure if we apply Jedis pool correctly in order to achieve a Jedis thread-safe using Spring beans

<bean id="redisOnlineManager" class="com.app.online.RedisOnlineManager>
<property name="pool">
    <bean class="redis.clients.jedis.JedisPool">
        <constructor-arg value="redis://localhost:1234/1" />
    </bean>
</property>

private JedisPool pool;

public void setPool(JedisPool pool) {
    this.pool = pool;
}

private boolean exists(String key) {
    Jedis jedis = pool.getResource();
    try {
        return jedis.exists(key);
    } finally {
        jedis.close();
    }
}

Did we implement Jedis pool correctly? does this code perform a thread-safe Jedis? If not, how should we use spring beans to make jedis threadsafe?

Please advise.. Thanks

Body:
What he is trying to say is that create the pool in a spring singleton bean Or class with static method for accessing pool. If you do either of it, you should be fine. What you have done in the code is that You are creating a pool for each instance of the ResourceManager and it can be improved like the following.

@Scope("singleton")
public class ResourceManager {

    private JedisPool pool ;

    public ResourceManager(){
        pool = new JedisPool(new JedisPoolConfig(), "localhost");
    }

    private boolean exists(String key) {
        Jedis jedis = pool.getResource();
        try {
            return jedis.exists(key);
        } finally {
            jedis.close();
        }
    }

}

Your application context will not have the inner bean.

<bean id="redisOnlineManager" class="com.app.online.RedisOnlineManager/><!-- you dont need this in the application context if you are using annotations -->


问:
New to NLP, Question about annotation
I am new to NLP and I am looking for a starting point, in terms of some tutorials, documentation or example code.
I have been told to research the possibilities of processing natural text to extract some structured data from it.
For example I want to extract(annotate) height and weight from following statements.
"He is 6 feet tall and weighs 200 pounds" or
"His height is 6 feet and weight is 200" etc.
I have looked into UIMA but it seems like a  self created REGEX dictionary with no training capabilities.
So in a nutshell, what Java framework can I use to create an annotation engine that can be trained as well!
Any help(pointers) on this will be heavily appreciated.
Thanks</p>

答: If you really want to want to use machine learning to train your annotator, then GATE is probably your best bet. Take a look at the chapter on machine learning in their guide.</p>

Title: New to NLP, Question about annotation


问:
Is it legal to use youtube-api to download videos and convert to mp3
(site issue with youtube api)

Is it legal to use youtube-api to download videos and convert to mp3,include youtube icon refrenece that video belong to them,
Listen and when finish delete the converted mp3 include the video?

The idea is to pick 20 songs from youtube api search download and convert to mp3 and listen to music and when done listen delete all files.

Thanks.

答:
I think it would be legal as if it is illegal it would be dumb for those web writers
PS YOU CANNOT SELL THEM</p>