问:
How to get rid of underlined links
I learn via Freecodecamp, one of our tasks was to create a Portfolio, but I cannot get rid of the underline links inside my navbar and footnote.

Text-decoration: none; does not help, any other ideas?

body {
  max-width: 100%;
  position: relative;
  overflow-x: hidden;
}

.container {
  z-index: 5;
  background-color: #8f8a01;
  position: fixed;
  top: 0;
  margin: auto;
  width: 100%;
  box-shadow: 2px 2px 2px #888;
  padding-bottom: 5px;
  text-decoration: none;
}

button {
  margin: 15px 0px 0px 15px;
  box-shadow: 2px 2px 2px #888;
  background-color: #ece2b4;
  font-family: 'Rajdhani', sans-serif;
  font-size: 17px;
  font-weight: 800;
  color: #8f8a01;
}

button:hover {
  background-color: #edce00;
}

a {
  text-decoration: none;
}

.about {
  min-height: 380px;
  margin: auto;
  width: 100%;
  padding: 50px 220px 70px 200px;
  background-color: #ece2b4;
  line-height: 50px;
  text-align: left;
  overflow: auto;
}

p {
  padding-left: 150px;
}

.photo {
  width: 200px;
  heihgt: 200px;
  float: right;
  margin-right: 0px;
  margin-left: 0px;
  border-radius: 120px;
  box-shadow: 2px 2px 2px #888;
}

#port {
  background-color: #bdb817;
  padding: 10px 10px 19px 10px;
  margin: auto;
  width: 100%;
}

.left-link {
  margin: 25px;
  padding: 5px 30px 15px 5px;
}

.right-link {
  margin: 25px;
  padding: 5px 30px 15px 5px;
}

#port {
  align: center;
}

img:hover {
  background-color: #edce00;
}

.small-img {
  padding: 5px;
  border: 1px solid gray;
  height: 250px;
  width: 300px;
  max-height: 350px;
  max-width: 400px;
  border-radius: 15px;
  box-shadow: 2px 2px 2px #888;
}

input {
  text-align: center;
}

.send-btn {
  margin: 10px 10px 50px 10px;
}

.ctcMe {
  z-index: 1;
  background-color: #ece2b4;
  line-height: 30px;
  margin: auto;
  width: 100%;
  padding-top: 2px;
}

input {
  border-radius: 0px;
  border-top: none;
  border-left: none;
  width: 200px;
}

textarea {
  border-radius: 0px;
  border-top: none;
  border-left: none;
  width: 200px;
}

.contact {
  text-align: center;
}

.send-btn {
  margin-left: 0%;
}

.web {
  background-color: #bdb817;
  padding-top: 15px;
  padding-bottom: 5px;
  margin: auto;
  width: 100%;
}

.fc {
  width: 30px;
  height: 30px;
}

.coded {
  background-color: #edce00;
  padding-top: 15px;
  padding-bottom: 5px;
  margin: auto;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <div class="container">
    <div class="row">
      <div class="col-xs-2">

          <button class="btn btn-block">
          About</button>
      </div>
      <div class="col-xs-2">

          <button class="btn btn-block">Portfolio</button>
      </div>

      <div class="col-xs-2">

          <button class="btn btn-block">Contact</button>
      </div>
    </div>
    <!-- close ROW -->
  </div>
  <!-- close HEAD -->

  <div class="about">
    <h2 style="text-align: center">

      ABOUT </h2>

      <img src="https://media.licdn.com/mpr/mpr/shrinknp_200_200/AAEAAQAAAAAAAAzEAAAAJDkwZTM5NmY4LWYwMzQtNDhmOS1hYzExLTM4YWI5NTZmMGI5ZA.jpg" alt="picture of me" class="img-responsive photo">
      <center>
        <p> I am a book-lover translator, and an excellent-organised personal assistant.
          <br> I help my team daily to get through the week from chaos to clarity,
          <br> and I provide my colleagues with comprehensive translations and proofreading.
          <br> Recently I am also a coding hobbyist and a Front-End Developer wannabe.
        </p>
      </center>
  </div>

  <div id="port">
    <h2 style="text-align: center"> PORTFOLIO</h2>
    <br>
    <div class="row img-center">
      <div class="col-xs-offset-2">
        <img class="small-img" src="http://www.drodd.com/images15/1-12.jpg">
        <img class="small-img" src="http://www.edu.xunta.gal/centros/ceipramoncajal/?q=system/files/u2/globo2fantasia.jpg">
        <img class="small-img" src="https://rfclipart.com/image/big/67-84-40/strawberry-style-font-number-3-Download-Royalty-free-Vector-File-EPS-71206.jpg">
      </div>
      <!-- close COL -->
    </div>
    <!--- close ROW -->
    <br>
    <div class="row img-center">
      <div class="col-xs-offset-2">

        <img class="small-img" src="http://3.bp.blogspot.com/-9cSZuRMO65M/UOYn20oxGUI/AAAAAAAALgg/zTyw-uLPkO8/s1600/number4.jpg">
        <img class="small-img" src="https://thebitterlemon.files.wordpress.com/2016/09/5.jpg?w=400">
        <img class="small-img" src="https://thumbs.dreamstime.com/z/liczby-kresk%C3%B3wki-%C5%9Bmieszny-r%C3%B3%C5%BCowy-flaming-31350873.jpg">
      </div>
      <!--close COL -->
    </div>
    <!--close ROW -->
  </div>
  <!-- close PORT -->
  <div class="ctcMe">
    <h2 style="text-align: center">

    CONTACT ME</h2>
      <br>
      <div class="row" style="margin-top: 10px;">
        <div class="col-xs-7">
          <p class="contact">If you have any requests or questions<br>I am very eager to answer them :) </p>
        </div>
        <!-- close COL -->

        <div class="col-xs-2">
          <form><input type="text" placeholder="name">
            <input type="text" placeholder="e-mail addres">
            <input type="text" placeholder="phone number">
            <textarea style="text-align: center" type="text" placeholder="message">
         </textarea>
          </form>
          <form><button class="btn send-btn" type="mailo">SEND</button></form>
          </form>
        </div>
        <!-- close COL -->
      </div>
      <!-- close ROW -->

  </div>
  <!-- close CtcMe -->

  <div class="web">
    <center>
      <p class="footnote">
        Around the web:
        <br>
        <img class="fc" src="https://yt3.ggpht.com/-bWUaHwGz7To/AAAAAAAAAAI/AAAAAAAAAAA/xEUD6X5iT2Y/s900-c-k-no-mo-rj-c0xffffff/photo.jpg">
        <img class="fc" src="http://www.blitzcleaned.com/wp-content/uploads/2014/07/LI-Logo-1.png">
        <img class="fc" src="http://www.freeiconspng.com/uploads/github-logo-icon-0.png">
        href="https://codepen.io/Broccolina/"><img class="fc" src="https://blog.codepen.io/wp-content/uploads/2012/06/Button-Black-Large.png">
      </p>
    </center>
  </div>

  <div class="coded">
    <center>
      <p class="footnote">
        Written and coded by
        href="https://www.facebook.com/broccolina19"> Agnieszka Kozub
      </p>
    </center>
  </div>
</body></code>```

答:
Add the following to your CSS:

```<code>a:link, a:hover { text-decoration: none; }
</code>```

You can remove it from class .container

Title: How to get rid of underlined links

Body:
I learn via Freecodecamp, one of our tasks was to create a Portfolio, but I cannot get rid of the underline links inside my navbar and footnote.

Text-decoration: none; does not help, any other ideas?

body {
  max-width: 100%;
  position: relative;
  overflow-x: hidden;
}

.container {
  z-index: 5;
  background-color: #8f8a01;
  position: fixed;
  top: 0;
  margin: auto;
  width: 100%;
  box-shadow: 2px 2px 2px #888;
  padding-bottom: 5px;
  text-decoration: none;
}

button {
  margin: 15px 0px 0px 15px;
  box-shadow: 2px 2px 2px #888;
  background-color: #ece2b4;
  font-family: 'Rajdhani', sans-serif;
  font-size: 17px;
  font-weight: 800;
  color: #8f8a01;
}

button:hover {
  background-color: #edce00;
}

a {
  text-decoration: none;
}

.about {
  min-height: 380px;
  margin: auto;
  width: 100%;
  padding: 50px 220px 70px 200px;
  background-color: #ece2b4;
  line-height: 50px;
  text-align: left;
  overflow: auto;
}

p {
  padding-left: 150px;
}

.photo {
  width: 200px;
  heihgt: 200px;
  float: right;
  margin-right: 0px;
  margin-left: 0px;
  border-radius: 120px;
  box-shadow: 2px 2px 2px #888;
}

#port {
  background-color: #bdb817;
  padding: 10px 10px 19px 10px;
  margin: auto;
  width: 100%;
}

.left-link {
  margin: 25px;
  padding: 5px 30px 15px 5px;
}

.right-link {
  margin: 25px;
  padding: 5px 30px 15px 5px;
}

#port {
  align: center;
}

img:hover {
  background-color: #edce00;
}

.small-img {
  padding: 5px;
  border: 1px solid gray;
  height: 250px;
  width: 300px;
  max-height: 350px;
  max-width: 400px;
  border-radius: 15px;
  box-shadow: 2px 2px 2px #888;
}

input {
  text-align: center;
}

.send-btn {
  margin: 10px 10px 50px 10px;
}

.ctcMe {
  z-index: 1;
  background-color: #ece2b4;
  line-height: 30px;
  margin: auto;
  width: 100%;
  padding-top: 2px;
}

input {
  border-radius: 0px;
  border-top: none;
  border-left: none;
  width: 200px;
}

textarea {
  border-radius: 0px;
  border-top: none;
  border-left: none;
  width: 200px;
}

.contact {
  text-align: center;
}

.send-btn {
  margin-left: 0%;
}

.web {
  background-color: #bdb817;
  padding-top: 15px;
  padding-bottom: 5px;
  margin: auto;
  width: 100%;
}

.fc {
  width: 30px;
  height: 30px;
}

.coded {
  background-color: #edce00;
  padding-top: 15px;
  padding-bottom: 5px;
  margin: auto;
  width: 100%;
}

  <meta name="viewport" content="width=device-width, initial-scale=1">

          <button class="btn btn-block">
          About</button>

          <button class="btn btn-block">Portfolio</button>

          <button class="btn btn-block">Contact</button>

      ABOUT

 I am a book-lover translator, and an excellent-organised personal assistant.

 I help my team daily to get through the week from chaos to clarity,

 and I provide my colleagues with comprehensive translations and proofreading.

 Recently I am also a coding hobbyist and a Front-End Developer wannabe.

 PORTFOLIO

    CONTACT ME

If you have any requests or questions
I am very eager to answer them :)

          <form><input type="text" placeholder="name">
            <input type="text" placeholder="e-mail addres">
            <input type="text" placeholder="phone number">
            <textarea style="text-align: center" type="text" placeholder="message">
         </textarea>
          </form>
          <form><button class="btn send-btn" type="mailo">SEND</button></form>
          </form>

        Around the web:

        Written and coded by
         Agnieszka Kozub

Body:
Add the following to your CSS:

a:link, a:hover { text-decoration: none; }

You can remove it from class .container


来源: stackexchange

问:
C++ Using for loops when you don't know when the iteration would end
So I have this code for c++ (not c++11)

```<code>#include <iostream>

using namespace std;

int calcTrip (string s) {
    int ans = 1;
    for (int i = 0; i < sizeof(s); i++) {
        char c = s[i];
        ans = ((ans*(c - 'A' + 1)) );
    }
    return ans;

}
int main() {

    string a1, a2;
    cin >> a1 >> a2;
    cout << calcTrip(a1) << endl;
    if (calcTrip(a1) != calcTrip(a2)) {
        cout << "STAY" << endl;
    }
    else {
        cout << "GO" << endl;
    }

}
</code>```

For my for loop in the variable i in calctrip, if I do i<sizeof(s) I get i is less than 32 because a string has a size of 32. Since string s is a user input, how do I make i less than the number of characters in a user input, s.

P.S And I know how to do this in c++ 11, but for class, I need to know how to do it in c++ 98

答:
sizeof operator returns the sizeof datatype not variable.Using sizeof(s) will return the size of string rather than size of a1...So can use ,

a1.size()
    or
  a1.length()

to get the length of string variable.

ContentLicense: CC BY-SA 3.0

Body:
So I have this code for c++ (not c++11)

#include <iostream>

using namespace std;

int calcTrip (string s) {
    int ans = 1;
    for (int i = 0; i < sizeof(s); i++) {
        char c = s[i];
        ans = ((ans*(c - 'A' + 1)) );
    }
    return ans;

}
int main() {

    string a1, a2;
    cin >> a1 >> a2;
    cout << calcTrip(a1) << endl;
    if (calcTrip(a1) != calcTrip(a2)) {
        cout << "STAY" << endl;
    }
    else {
        cout << "GO" << endl;
    }

}

For my for loop in the variable i in calctrip, if I do i<sizeof(s) I get i is less than 32 because a string has a size of 32. Since string s is a user input, how do I make i less than the number of characters in a user input, s.

P.S And I know how to do this in c++ 11, but for class, I need to know how to do it in c++ 98


问:
Passing Controller a FormCollection and an IList<T>
I have a form which contains a whole heap of data entry fields that will be completed by the user including some elements where the user can dictate how many of the same items they will enter. This is as is being used in Phil Haack's blog entry Model Binding To A List.

I am successfully using JQuery to create the extra form elements, correctly indexed, etc. My issue is the best way to actually read these within my Controller. The Controller in the article only expects one object, IList<Product> whereas my Controller already expects a FormCollection form and now I am trying to also send it an IList<Itmes> as well.

Should I be adding this to the parameters expected by the Controller or accessing via form["items"] or something else?

View

```<code><form action="/MyItems/Add" method="post">
   <input type="text" name="Title" value="" />

   <input type="hidden" name="myItem.Index" value="0" />
   <input id="item[0].Amount" name="item[0].Amount" type="text" value="" />
   <input id="item[0].Name" name="item[0].Name" type="text" value="" />

   <input type="hidden" name="myItem.Index" value="1" />
   <input id="item[1].Amount" name="item[1].Amount" type="text" value="" />
   <input id="item[1].Name" name="item[1].Name" type="text" value="" />
</form>
</code>```

Controller

```<code>public ActionResult Add(FormCollection form)
{
    string Title = form["Title"];
    List<Item> Items = form["items"].ToList();
}
</code>```

DTO

```<code>public class Item()
{
    int Amount {get; set; };
    string Name {get; set; };
}
</code>```

答:
You could just add the myItem as a parameter like so:

```<code>public ActionResult Add(FormCollection form, List<Item> myItem)
{
}
</code>```

It will then bind automatically from the form data and populate the myItem parameter.

OwnerDisplayName: dave

ContentLicense: CC BY-SA 2.5

Body:
I have a form which contains a whole heap of data entry fields that will be completed by the user including some elements where the user can dictate how many of the same items they will enter. This is as is being used in Phil Haack's blog entry Model Binding To A List.

I am successfully using JQuery to create the extra form elements, correctly indexed, etc. My issue is the best way to actually read these within my Controller. The Controller in the article only expects one object, IList<Product> whereas my Controller already expects a FormCollection form and now I am trying to also send it an IList<Itmes> as well.

Should I be adding this to the parameters expected by the Controller or accessing via form["items"] or something else?

View

<form action="/MyItems/Add" method="post">
   <input type="text" name="Title" value="" />

   <input type="hidden" name="myItem.Index" value="0" />
   <input id="item[0].Amount" name="item[0].Amount" type="text" value="" />
   <input id="item[0].Name" name="item[0].Name" type="text" value="" />

   <input type="hidden" name="myItem.Index" value="1" />
   <input id="item[1].Amount" name="item[1].Amount" type="text" value="" />
   <input id="item[1].Name" name="item[1].Name" type="text" value="" />
</form>

Controller

public ActionResult Add(FormCollection form)
{
    string Title = form["Title"];
    List<Item> Items = form["items"].ToList();
}

DTO

public class Item()
{
    int Amount {get; set; };
    string Name {get; set; };
}

LastEditorDisplayName: dave

Body:
You could just add the myItem as a parameter like so:

public ActionResult Add(FormCollection form, List<Item> myItem)
{
}

It will then bind automatically from the form data and populate the myItem parameter.

OwnerDisplayName: Schotime


问:
Images showing in simulator but not on the iPhone device
So when I run the application from the device the pictures show up and everything works great. However, when I move to the device I run in about 10 out of 38 pictures that don't show up.  I am pulling the names for the images from an sqlite database and I already checked and the names are correct, case and everything.  I checked the bundle and the images are correctly in there.

Does memory play into effect in this?  I am not really sure what else could cause this to happen??

Thanks!

Solution:
The files somehow were not saved properly and were unable to be opened by say photoshop or paint even.  So with the files not being able to be open they weren't showing up... Thanks for the help everyone!

答:
Generally, if in-memory size was the culprit, your application would crash with a low memory error on the device.  However, it seems like the images just don't display.

One other thing that can be going wrong is the size of the images.  UIViews on the iPhone can only have dimensions smaller than the maximum texture size supported by the GPU.  Apple states that this is 1024 x 1024, but I've found it to be more like 2048 x 2048 on even the original model iPhone.  You may be creating a view for some of these images that exceeds this size in one dimension, but your Mac has a larger maximum texture size on its GPU and so it displays fine in the Simulator.


问:
Convert .dll format to .exe format?
I have c++ project developed in Visual studio, when i was build my project got .dll file and some other files are existed in some directory. So my question is, Any ways are there for convert my existed .dll file to .exe file ???

Thanks in Advance..

答: You cannot just simply convert any .dll file to program executable .exe. This is more a work for a programmer, not a simple conversion any user can make with some kind of utility.</p>

Title: Convert .dll format to .exe format?


问:
how to numeric sort in datagridview
I am using a DataGridView.

ValueType is Object. So, it orders it starting from the first number.

But i want to sort by numeric.

Next is my Code.

```<code>public event DataGridViewSortCompareEventHandler OnSortCompare;
DataGridView Grid;
Grid.ColumnHeaderMouseClick += Grid_ColumnHeaderMouseClick;
Grid.OnSortCompare += new DataGridViewSortCompareEventHandler(Grid_SortCompare);

void Grid_ColumnHeaderMouseClick(object sender,    DataGridViewCellMouseEventArgs e)
{
    OnSortCompare(sender, ***?***);
}

void Grid_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
{
   int a = int.Parse(e.CellValue1.ToString());
   int b = int.Parse(e.CellValue2.ToString());
   e.SortResult = a.CompareTo(b);
   e.Handled = true;
}
</code>```

But I don't know how i can pass 'e'(DataGridViewSortCompareEventArgs e).

it is  '* ? *' in my code.

Any help would be much appreciated.

答:
You can sort your grid like the following.

```<code>Grid.Sort(Grid.Columns[0], ListSortDirection.Descending);
</code>```

Just be aware the ValueType of the column must be set to the correct type or the sorting won't work correctly.

```<code>Grid.Columns[0].ValueType = typeof(int);
</code>```

Title: how to numeric sort in datagridview

Body:
I am using a DataGridView.

ValueType is Object. So, it orders it starting from the first number.

But i want to sort by numeric.

Next is my Code.

public event DataGridViewSortCompareEventHandler OnSortCompare;
DataGridView Grid;
Grid.ColumnHeaderMouseClick += Grid_ColumnHeaderMouseClick;
Grid.OnSortCompare += new DataGridViewSortCompareEventHandler(Grid_SortCompare);

void Grid_ColumnHeaderMouseClick(object sender,    DataGridViewCellMouseEventArgs e)
{
    OnSortCompare(sender, ***?***);
}

void Grid_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
{
   int a = int.Parse(e.CellValue1.ToString());
   int b = int.Parse(e.CellValue2.ToString());
   e.SortResult = a.CompareTo(b);
   e.Handled = true;
}

But I don't know how i can pass 'e'(DataGridViewSortCompareEventArgs e).

it is  '* ? *' in my code.

Any help would be much appreciated.

Body:
You can sort your grid like the following.

Grid.Sort(Grid.Columns[0], ListSortDirection.Descending);

Just be aware the ValueType of the column must be set to the correct type or the sorting won't work correctly.

Grid.Columns[0].ValueType = typeof(int);


问:
How to perform clustering/grouping on categorical variables based on frequencies?
I have a sample set of observations as follows

```<code>var1 var2 var3 var4
 1    2    1     1
 3    2    1     3
 1    2    0     1
 3    2    2     3
</code>```

All the values are categorical in nature. I want to group 1st and 3rd row to one cluster and 2nd and 4th to another cluster.I believe One-hot encoding is not effective in this case because categorical variables does not posses any rank and they are purely nominal in nature .

(The rows need not have to be absolutely same as well). Is there a pre-built mathematical algorithm to group these rows based on similarities/frequencies? Can anyone suggest a good way to do it? Or should I go with one-hot coding?

答:
You can use the gower distance to calculate the distance between categorical variables.

Below an example:

```<code># Import data
dta <- read.table(header = TRUE, textConnection("Var1 var2 var3 var4
 1    2    1     1
 3    2    1     3
 1    2    0     1
 3    2    2     3"))
dta <- as.data.frame(lapply(dta, as.factor))

# Create distance matrix using gower distance using gower package (fast)
# The code below computes the complete distance matrix, while only the upper
# or lower half is needed; so this could be improved.
library(gower)
pairs <- expand.grid(x = seq_len(nrow(dta)), y = seq_len(nrow(dta)))
dist <- gower_dist(dta[pairs$x,], dta[pairs$y, ])
dist <- array(dist, dim = c(nrow(dta), nrow(dta)))

# Convert matrix to distance object
dist <- as.dist(dist)

# Cluster using distance matrix; for this there are numerous options
# Use hierarchical clustering in this case
cl <- hclust(dist)
plot(cl)
</code>```

Another solution using the cluster package (als contains a large number of
clustering methods)

```<code>library(cluster)
dist <- daisy(dta, metric = "gower")

cl <- hclust(dist)
plot(cl)
</code>```

In order to derive the clustering from the hierarchical clustering, the tree needs to be 'cut'  into the clusters. This can be done by specifying the height at which the tree needs to be cut, or by specifying the number of clusters. Below I specify the number of clusters:

```<code>dta$cluster <- cutree(cl, k = 2)
</code>```

Body:
I have a sample set of observations as follows

var1 var2 var3 var4
 1    2    1     1
 3    2    1     3
 1    2    0     1
 3    2    2     3

All the values are categorical in nature. I want to group 1st and 3rd row to one cluster and 2nd and 4th to another cluster.I believe One-hot encoding is not effective in this case because categorical variables does not posses any rank and they are purely nominal in nature .

(The rows need not have to be absolutely same as well). Is there a pre-built mathematical algorithm to group these rows based on similarities/frequencies? Can anyone suggest a good way to do it? Or should I go with one-hot coding?

Body:
You can use the gower distance to calculate the distance between categorical variables.

Below an example:

# Import data
dta <- read.table(header = TRUE, textConnection("Var1 var2 var3 var4
 1    2    1     1
 3    2    1     3
 1    2    0     1
 3    2    2     3"))
dta <- as.data.frame(lapply(dta, as.factor))

# Create distance matrix using gower distance using gower package (fast)
# The code below computes the complete distance matrix, while only the upper
# or lower half is needed; so this could be improved.
library(gower)
pairs <- expand.grid(x = seq_len(nrow(dta)), y = seq_len(nrow(dta)))
dist <- gower_dist(dta[pairs$x,], dta[pairs$y, ])
dist <- array(dist, dim = c(nrow(dta), nrow(dta)))

# Convert matrix to distance object
dist <- as.dist(dist)

# Cluster using distance matrix; for this there are numerous options
# Use hierarchical clustering in this case
cl <- hclust(dist)
plot(cl)

Another solution using the cluster package (als contains a large number of
clustering methods)

library(cluster)
dist <- daisy(dta, metric = "gower")

cl <- hclust(dist)
plot(cl)

In order to derive the clustering from the hierarchical clustering, the tree needs to be 'cut'  into the clusters. This can be done by specifying the height at which the tree needs to be cut, or by specifying the number of clusters. Below I specify the number of clusters:

dta$cluster <- cutree(cl, k = 2)


问:
How to solve "Error: MySQL shutdown unexpectedly"?
When I open XAMPP and click start MySQL button and it gives me an error.
I had  started it just before, but now it isn't working.

12:19:12 PM [mysql] Attempting to start MySQL app...

  12:19:12 PM [mysql] Status change detected: running

  12:19:13 PM [mysql] Status change detected: stopped

  12:19:13 PM [mysql] Error: MySQL shutdown unexpectedly.

  12:19:13 PM [mysql] This may be due to a blocked port, missing dependencies,

  12:19:13 PM [mysql] improper privileges, a crash, or a shutdown by another method

  12:19:13 PM [mysql] Press the Logs button to view error logs and check

  12:19:13 PM [mysql] the Windows Event Viewer for more clues

  12:19:13 PM [mysql] If you need more help, copy and post this

  12:19:13 PM [mysql] entire log window on the forums

Here is the contents of the error log:

2013-08-02 12:19:12 4536 [Note] Plugin 'FEDERATED' is disabled.

  2013-08-02 12:19:12 f64 InnoDB: Warning: Using innodb_additional_mem_pool_size is DEPRECATED. This option may be removed in future releases, together with the option innodb_use_sys_malloc and with the InnoDB's internal memory allocator.

  2013-08-02 12:19:12 4536 [Note] InnoDB: The InnoDB memory heap is disabled

  2013-08-02 12:19:12 4536 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions

  2013-08-02 12:19:12 4536 [Note] InnoDB: Compressed tables use zlib 1.2.3

  2013-08-02 12:19:12 4536 [Note] InnoDB: Not using CPU crc32 instructions

  2013-08-02 12:19:12 4536 [Note] InnoDB: Initializing buffer pool, size = 16.0M

  2013-08-02 12:19:12 4536 [Note] InnoDB: Completed initialization of buffer pool

  2013-08-02 12:19:12 4536 [Note] InnoDB: Highest supported file format is Barracuda.

  2013-08-02 12:19:12 4536 [Note] InnoDB: The log sequence numbers 0 and 0 in ibdata files do not match the log sequence number 1616798 in the ib_logfiles!

  2013-08-02 12:19:12 4536 [Note] InnoDB: Database was not shutdown normally!

  2013-08-02 12:19:12 4536 [Note] InnoDB: Starting crash recovery.

  2013-08-02 12:19:12 4536 [Note] InnoDB: Reading tablespace information from the .ibd files...

The most important error message is here:

2013-08-02 12:19:12 4536 [ERROR] InnoDB:

  Attempted to open a previously opened tablespace.

  Previous tablespace mysql/innodb_table_stats uses space ID: 1 at filepath: .\mysql\innodb_table_stats.ibd.

  Cannot open tablespace xat/payments which uses space ID: 1 at filepath: .\xat\payments.ibd

The rest of the log:

InnoDB: Error: could not open single-table tablespace file .\xat\payments.ibd

  InnoDB: We do not continue the crash recovery, because the table may become

  InnoDB: corrupt if we cannot apply the log records in the InnoDB log to it.

  InnoDB: To fix the problem and start mysqld:

  InnoDB: 1) If there is a permission problem in the file and mysqld cannot

  InnoDB: open the file, you should modify the permissions.

  InnoDB: 2) If the table is not needed, or you can restore it from a backup,

  InnoDB: then you can remove the .ibd file, and InnoDB will do a normal

  InnoDB: crash recovery and ignore that table.

  InnoDB: 3) If the file system or the disk is broken, and you cannot remove

  InnoDB: the .ibd file, you can set innodb_force_recovery > 0 in my.cnf

  InnoDB: and force InnoDB to continue crash recovery here.

What is the cause of these errors and how can I rectify them?

答: If the crash message is "mysql.exe has stopped working". Just run xampp-control.exe as administrator will solve your problem instantly.

ContentLicense: CC BY-SA 4.0


问:
Make .toggleClass() to affect only one element with the same class on click in jQuery
I am trying to make dropdown menu with jQuery. Problem that my script effects all elements with the same class on click. Below is my problem in the snippet:

$(document).ready(function() {
  $('.parent').click(function() {
    $('.sub-nav').toggleClass('visible');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#nav ul.sub-nav {
  display: none;
}

#nav ul.visible {
  display: block;
}</code>```

Home

One

Two

Three

About

Johnny

Julie

Jamie

Contact

```
</div>
</div>
</p>

<p>I was trying to play around with :</p>

```$(document)
    .ready(function () {
    $('.parent')
        .click(function () {
        $(this).children('.sub-nav').toggleClass('visible');
    });
});
```

but without any decent results. Could someone tell where I am missing the point? Many thanks for all possible help, looking forward.

答:
Use current object with this keyword:

$(document).ready(function() {
  $('.parent').click(function() {
    $(this).children('.sub-nav').toggleClass('visible');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#nav ul.sub-nav {
  display: none;
}

#nav ul.visible {
  display: block;
}</code>```

Home

One

Two

Three

About

Johnny

Julie

Jamie

Contact

```

Body:
I am trying to make dropdown menu with jQuery. Problem that my script effects all elements with the same class on click. Below is my problem in the snippet:

$(document).ready(function() {
  $('.parent').click(function() {
    $('.sub-nav').toggleClass('visible');
  });
});

#nav ul.sub-nav {
  display: none;
}

#nav ul.visible {
  display: block;
}

Home

One

Two

Three

About

Johnny

Julie

Jamie

Contact

I was trying to play around with :

$(document)
    .ready(function () {
    $('.parent')
        .click(function () {
        $(this).children('.sub-nav').toggleClass('visible');
    });
});

but without any decent results. Could someone tell where I am missing the point? Many thanks for all possible help, looking forward.

Body:
Use current object with this keyword:

$(document).ready(function() {
  $('.parent').click(function() {
    $(this).children('.sub-nav').toggleClass('visible');
  });
});

#nav ul.sub-nav {
  display: none;
}

#nav ul.visible {
  display: block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="nav">
  <li class="parent">Home
    <ul class="sub-nav">
      <li>One</li>
      <li>Two</li>
      <li>Three</li>
    </ul>
  </li>
  <li class="parent">About
    <ul class="sub-nav">
      <li>Johnny</li>
      <li>Julie</li>
      <li>Jamie</li>
    </ul>
  </li>
  <li>Contact</li>
</ul>


问:
Multiple Checkbox Saving to DB 1 or 0
Creating multiple question checkboxes and I need to send two possible cases 1 or 0 to the database. However, it always sends the last one I click as 1 all the others 0. So for example, if a user clicks/checks the first one and the last I want to send to the database both 1 and the other two unchecked 0.

Controller

```<code><?php

public function create($request)
{
    foreach ($request['options'] as $key => $option) {
        Answer::create([
            'question_id' => $this->get(),
            'text' => $option,
            'correct' => $request['correct'] == $key ? 1 : 0
        ]);
    }
}
</code>```

View

```<code>@for($i = 1; $i<=4; $i++)
    <div class="form-group {{ $errors->has('options.'.$i) ? ' has-error': '' }}" id="option{{ $i }}">
        <div class="checkbox col-xs-2 control-label" style="margin-top: -2px">
            <label>
                <input id="cc" type="checkbox" name="correct" value="{{$i}}" {{ $i==1 ? 'checked' : '' }} >
            <!--
            {!! Form::hidden('correct',0) !!}
            {!! Form::checkbox('correct',1,false) !!}
            -->
            </label>
        </div>
        <div class="col-xs-8">
            <input type="text" name="options[{{ $i }}]" value="{{ old('options.'.$i) }}"
                   class="form-control" placeholder="@lang('general.option') {{ $i }}">
            @if($errors->has('options.'.$i))
                <div class="col-xs-12"></div>
                <span class="help-block">
                    <strong>{{ $errors->first('options.'.$i) }}</strong>
                </span>
            @endif
        </div>
    </div>
@endfor
</code>```

答:
Either mention array of control for checkbox as below

```<code> <input  id="cc" type="checkbox" name="correct[]" value="{{$i}}" {{ $i==1 ? 'checked' : '' }}  >
</code>```

change name="correct" to name="correct[]"

OR

give different name to each checkbox using incremental variable like

name="correct" to name="correct_".$i

Title: Multiple Checkbox Saving to DB 1 or 0

Body:
Creating multiple question checkboxes and I need to send two possible cases 1 or 0 to the database. However, it always sends the last one I click as 1 all the others 0. So for example, if a user clicks/checks the first one and the last I want to send to the database both 1 and the other two unchecked 0.

Controller

<?php

public function create($request)
{
    foreach ($request['options'] as $key => $option) {
        Answer::create([
            'question_id' => $this->get(),
            'text' => $option,
            'correct' => $request['correct'] == $key ? 1 : 0
        ]);
    }
}

View

@for($i = 1; $i<=4; $i++)

has('options.'.$i) ? ' has-error': '' }}" id="option{{ $i }}">

                <input id="cc" type="checkbox" name="correct" value="{{$i}}" {{ $i==1 ? 'checked' : '' }} >

            <input type="text" name="options[{{ $i }}]" value="{{ old('options.'.$i) }}"
                   class="form-control" placeholder="@lang('general.option') {{ $i }}">
            @if($errors->has('options.'.$i))

                    {{ $errors->first('options.'.$i) }}

            @endif

@endfor

Body:
Either mention array of control for checkbox as below

 <input  id="cc" type="checkbox" name="correct[]" value="{{$i}}" {{ $i==1 ? 'checked' : '' }}  >

change name="correct" to name="correct[]"

OR

give different name to each checkbox using incremental variable like

name="correct" to name="correct_".$i


问:
how to create a synchronous news feed in UWP
I want to create a simple news feed, I use web API to get the news updates, users can use combox select category (world news & sports news),and the news will be auto updated every 5 seconds, if I only select once, the news feed can auto updated and repeat, But if I change the selection, it start to show me both categories. here is my code </p>

```<code>public async void NewsRepeat()
    {
        RootObject2 myNews = await NewsProxy.GetNews();
        RootObject3 mySportNews = await sportsNewsProxy.GetSportNews();
        if (newsTpye.SelectedIndex==0)
        {

            for ( k = 0; k <= 8; k++)
            {

                       newsImage.Source = new BitmapImage(new Uri(myNews.articles[k].urlToImage, UriKind.Absolute));
                       showTime.Text = myNews.articles[k].publishedAt.ToString();
                    showDescription.Text = "(" + myNews.source + "): " + myNews.articles[k].description;
                    await Task.Delay(5000);
            }
        }
        else if (newsTpye.SelectedIndex==1)
        {

            for (k = 0; k <= 8; k++)
            {

                   newsImage.Source = new BitmapImage(new Uri(mySportNews.articles[k].urlToImage, UriKind.Absolute));
                    showTime.Text = mySportNews.articles[k].publishedAt;
                showDescription.Text = "(" + mySportNews.source + "): " + mySportNews.articles[k].description;
                await Task.Delay(5000);
            }
        }
        NewsRepeat();
    }
private void newsType_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        NewsRepeat();

    }
</code>```

答:
Your code runs continuously / infinite loops. NewsRepeat never finishes - so when you change selection your now running two instances of NewsRepeat side by side. Change it again and you're running three, and so on.

On SelectionChanged you want to somehow stop the previous instance of NewsRepeat from running.

(Also, creating BitmapImages in the ViewModel is a bad idea generally - bind the  directly in XAML to the URL property - Windows will carry out some performance and memory enhancements for you)

One possible solution is to use a CancellationTokenSource, which is a very simple object you can use to manually throw OperationCanceledException's when you deem it necessary (
frequently used as a pattern to cancel async Tasks). Keep it mind it does not work automatically - it's something you have to handle.

```<code>    CancellationTokenSource cts = null;
    public async void NewsRepeat()
    {
        cts?.Cancel();

        try
        {
            var localCts = cts = new CancellationTokenSource();

            RootObject2 myNews = await NewsProxy.GetNews();
            RootObject3 mySportNews = await sportsNewsProxy.GetSportNews();

            localCts.Token.ThrowIfCancellationRequested();

            if (newsTpye.SelectedIndex == 0)
            {
                for (k = 0; k <= 8; k++)
                {
                    newsImage.Source = new BitmapImage(new Uri(myNews.articles[k].urlToImage, UriKind.Absolute));
                    showTime.Text = myNews.articles[k].publishedAt.ToString();
                    showDescription.Text = "(" + myNews.source + "): " + myNews.articles[k].description;
                    await Task.Delay(5000);
                    localCts.Token.ThrowIfCancellationRequested();
                }
            }
            else if (newsTpye.SelectedIndex == 1)
            {
                for (k = 0; k <= 8; k++)
                {
                    newsImage.Source = new BitmapImage(new Uri(mySportNews.articles[k].urlToImage, UriKind.Absolute));
                    showTime.Text = mySportNews.articles[k].publishedAt;
                    showDescription.Text = "(" + mySportNews.source + "): " + mySportNews.articles[k].description;
                    await Task.Delay(5000);
                    localCts.Token.ThrowIfCancellationRequested();
                }
            }
            NewsRepeat();
        }
        catch (OperationCanceledException)
        {
            // Swallow this exception only - this is probably
            // the one we've thrown ourselves
        }
    }

    private void newsType_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        NewsRepeat();
    }
</code>```

Body:
I want to create a simple news feed, I use web API to get the news updates, users can use combox select category (world news & sports news),and the news will be auto updated every 5 seconds, if I only select once, the news feed can auto updated and repeat, But if I change the selection, it start to show me both categories. here is my code

public async void NewsRepeat()
    {
        RootObject2 myNews = await NewsProxy.GetNews();
        RootObject3 mySportNews = await sportsNewsProxy.GetSportNews();
        if (newsTpye.SelectedIndex==0)
        {

            for ( k = 0; k <= 8; k++)
            {

                       newsImage.Source = new BitmapImage(new Uri(myNews.articles[k].urlToImage, UriKind.Absolute));
                       showTime.Text = myNews.articles[k].publishedAt.ToString();
                    showDescription.Text = "(" + myNews.source + "): " + myNews.articles[k].description;
                    await Task.Delay(5000);
            }
        }
        else if (newsTpye.SelectedIndex==1)
        {

            for (k = 0; k <= 8; k++)
            {

                   newsImage.Source = new BitmapImage(new Uri(mySportNews.articles[k].urlToImage, UriKind.Absolute));
                    showTime.Text = mySportNews.articles[k].publishedAt;
                showDescription.Text = "(" + mySportNews.source + "): " + mySportNews.articles[k].description;
                await Task.Delay(5000);
            }
        }
        NewsRepeat();
    }
private void newsType_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        NewsRepeat();

    }

Body:
Your code runs continuously / infinite loops. NewsRepeat never finishes - so when you change selection your now running two instances of NewsRepeat side by side. Change it again and you're running three, and so on.

On SelectionChanged you want to somehow stop the previous instance of NewsRepeat from running.

(Also, creating BitmapImages in the ViewModel is a bad idea generally - bind the  directly in XAML to the URL property - Windows will carry out some performance and memory enhancements for you)

One possible solution is to use a CancellationTokenSource, which is a very simple object you can use to manually throw OperationCanceledException's when you deem it necessary (
frequently used as a pattern to cancel async Tasks). Keep it mind it does not work automatically - it's something you have to handle.

    CancellationTokenSource cts = null;
    public async void NewsRepeat()
    {
        cts?.Cancel();

        try
        {
            var localCts = cts = new CancellationTokenSource();

            RootObject2 myNews = await NewsProxy.GetNews();
            RootObject3 mySportNews = await sportsNewsProxy.GetSportNews();

            localCts.Token.ThrowIfCancellationRequested();

            if (newsTpye.SelectedIndex == 0)
            {
                for (k = 0; k <= 8; k++)
                {
                    newsImage.Source = new BitmapImage(new Uri(myNews.articles[k].urlToImage, UriKind.Absolute));
                    showTime.Text = myNews.articles[k].publishedAt.ToString();
                    showDescription.Text = "(" + myNews.source + "): " + myNews.articles[k].description;
                    await Task.Delay(5000);
                    localCts.Token.ThrowIfCancellationRequested();
                }
            }
            else if (newsTpye.SelectedIndex == 1)
            {
                for (k = 0; k <= 8; k++)
                {
                    newsImage.Source = new BitmapImage(new Uri(mySportNews.articles[k].urlToImage, UriKind.Absolute));
                    showTime.Text = mySportNews.articles[k].publishedAt;
                    showDescription.Text = "(" + mySportNews.source + "): " + mySportNews.articles[k].description;
                    await Task.Delay(5000);
                    localCts.Token.ThrowIfCancellationRequested();
                }
            }
            NewsRepeat();
        }
        catch (OperationCanceledException)
        {
            // Swallow this exception only - this is probably
            // the one we've thrown ourselves
        }
    }

    private void newsType_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        NewsRepeat();
    }


问:
How to create an animation that rotate CAShapeLayer in swift
This is my code :
import UIKit

```<code>class circularLoaderView: UIView {

    let circlePathLayer = CAShapeLayer()
    let circleRadius: CGFloat = 20.0

    override init(frame: CGRect) {

        super.init(frame: frame)
        configure()

    }

    required init(coder aDecoder: NSCoder) {

        super.init(coder: aDecoder)!
        configure()
    }

    func configure() {

        circlePathLayer.frame = bounds
        circlePathLayer.lineWidth = 2
        circlePathLayer.fillColor = UIColor.clearColor().CGColor
        circlePathLayer.strokeColor = UIColor.redColor().CGColor

        layer.addSublayer(circlePathLayer)
        backgroundColor = UIColor.whiteColor()

    }

    func circleFrame() -> CGRect {
        var circleFrame = CGRect(x: 0, y: 0, width: 2*circleRadius, height: 2*circleRadius)
        circleFrame.origin.x = 20
        circleFrame.origin.y = 20

        return circleFrame
    }

     func circlePath() -> UIBezierPath {

        let startAngle = CGFloat(-M_PI_2)
        let endAngle = startAngle + CGFloat(M_PI * 2)

        return UIBezierPath(arcCenter: CGPoint(x: circleRadius, y: circleRadius), radius: circleRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true)

     }

    override func layoutSubviews() {
        super.layoutSubviews()

        circlePathLayer.frame = bounds
        circlePathLayer.path = circlePath().CGPath
        circlePathLayer.strokeEnd = 0.25

        circlePathLayer.addAnimation(rotationAnimation, forKey: "transform.rotation")

    }

    let rotationAnimation: CAAnimation = {
        let animation = CABasicAnimation(keyPath: "transform.rotation")
        animation.fromValue = 0
        animation.toValue = M_PI * 2
        animation.duration = 4

        animation.repeatCount = MAXFLOAT
        return animation
    }()

}
</code>```

This is my code which I create a CAShapeLayer which will rotate and thus craete a loader effect, but when I add the animation of rotationAnimation,  it rotate the whole CAShapeLayer around a center point but not the CAShapeLayer itself. Why do this happen? How can I solve it? Thank you

答:
Your case shall work perfectly for the view with size(width: 40, height: 40).

If you want to generalise to have your circularLoaderView working for other sizes too, You need to

Assign radius to half of the view's height or width(since height=width).

```<code>var circleRadius: CGFloat {

  return bounds.size.height/2

 }
</code>```

Similarly, your center shall also be at the view's center that is

```<code>circleFrame.origin.x = bounds.size.height/2
circleFrame.origin.y = bounds.size.height/2
</code>```

Below is the modified code that works appropriately in Swift 3

```<code>class circularLoaderView: UIView {

    let circlePathLayer = CAShapeLayer()
    var circleRadius: CGFloat {
        return bounds.height/2
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        configure()

    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
        configure()
    }

    func configure() {
        circlePathLayer.frame = bounds
        circlePathLayer.lineWidth = 2
        circlePathLayer.fillColor = UIColor.clear.cgColor
        circlePathLayer.strokeColor = UIColor.red.cgColor

        layer.addSublayer(circlePathLayer)
        backgroundColor = UIColor.white
    }

    //This method is not being used
    /*func circleFrame() -> CGRect {
        var circleFrame = CGRect(x: circleRadius , y: circleRadius, width: 2*circleRadius, height: 2*circleRadius)
        circleFrame.origin.x = circleRadius
        circleFrame.origin.y = circleRadius

        return circleFrame
    }*/

    func circlePath() -> UIBezierPath {
        let startAngle = CGFloat(-Double.pi/2)
        let endAngle = startAngle + CGFloat(Double.pi * 2)

        return UIBezierPath(arcCenter: CGPoint(x: circleRadius, y: circleRadius), radius: circleRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        circlePathLayer.frame = bounds
        circlePathLayer.path = circlePath().cgPath
        circlePathLayer.strokeEnd = 0.25
        circlePathLayer.add(rotationAnimation, forKey: "transform.rotation")

    }

    let rotationAnimation: CAAnimation = {
        let animation = CABasicAnimation(keyPath: "transform.rotation")
        animation.fromValue = 0
        animation.toValue = Double.pi * 2
        animation.duration = 4
        animation.repeatCount = MAXFLOAT

        return animation
    }()
}
</code>```

I know this question was posted a long way back but I just hope this solves the issue of someone who is looking for the similar issue.

Body:
This is my code :
import UIKit

class circularLoaderView: UIView {

    let circlePathLayer = CAShapeLayer()
    let circleRadius: CGFloat = 20.0

    override init(frame: CGRect) {

        super.init(frame: frame)
        configure()

    }

    required init(coder aDecoder: NSCoder) {

        super.init(coder: aDecoder)!
        configure()
    }

    func configure() {

        circlePathLayer.frame = bounds
        circlePathLayer.lineWidth = 2
        circlePathLayer.fillColor = UIColor.clearColor().CGColor
        circlePathLayer.strokeColor = UIColor.redColor().CGColor

        layer.addSublayer(circlePathLayer)
        backgroundColor = UIColor.whiteColor()

    }

    func circleFrame() -> CGRect {
        var circleFrame = CGRect(x: 0, y: 0, width: 2*circleRadius, height: 2*circleRadius)
        circleFrame.origin.x = 20
        circleFrame.origin.y = 20

        return circleFrame
    }

     func circlePath() -> UIBezierPath {

        let startAngle = CGFloat(-M_PI_2)
        let endAngle = startAngle + CGFloat(M_PI * 2)

        return UIBezierPath(arcCenter: CGPoint(x: circleRadius, y: circleRadius), radius: circleRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true)

     }

    override func layoutSubviews() {
        super.layoutSubviews()

        circlePathLayer.frame = bounds
        circlePathLayer.path = circlePath().CGPath
        circlePathLayer.strokeEnd = 0.25

        circlePathLayer.addAnimation(rotationAnimation, forKey: "transform.rotation")

    }

    let rotationAnimation: CAAnimation = {
        let animation = CABasicAnimation(keyPath: "transform.rotation")
        animation.fromValue = 0
        animation.toValue = M_PI * 2
        animation.duration = 4

        animation.repeatCount = MAXFLOAT
        return animation
    }()

}

This is my code which I create a CAShapeLayer which will rotate and thus craete a loader effect, but when I add the animation of rotationAnimation,  it rotate the whole CAShapeLayer around a center point but not the CAShapeLayer itself. Why do this happen? How can I solve it? Thank you

Body:
Your case shall work perfectly for the view with size(width: 40, height: 40).

If you want to generalise to have your circularLoaderView working for other sizes too, You need to

Assign radius to half of the view's height or width(since height=width).

var circleRadius: CGFloat {

  return bounds.size.height/2

 }

Similarly, your center shall also be at the view's center that is

circleFrame.origin.x = bounds.size.height/2
circleFrame.origin.y = bounds.size.height/2

Below is the modified code that works appropriately in Swift 3

class circularLoaderView: UIView {

    let circlePathLayer = CAShapeLayer()
    var circleRadius: CGFloat {
        return bounds.height/2
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        configure()

    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
        configure()
    }

    func configure() {
        circlePathLayer.frame = bounds
        circlePathLayer.lineWidth = 2
        circlePathLayer.fillColor = UIColor.clear.cgColor
        circlePathLayer.strokeColor = UIColor.red.cgColor

        layer.addSublayer(circlePathLayer)
        backgroundColor = UIColor.white
    }

    //This method is not being used
    /*func circleFrame() -> CGRect {
        var circleFrame = CGRect(x: circleRadius , y: circleRadius, width: 2*circleRadius, height: 2*circleRadius)
        circleFrame.origin.x = circleRadius
        circleFrame.origin.y = circleRadius

        return circleFrame
    }*/

    func circlePath() -> UIBezierPath {
        let startAngle = CGFloat(-Double.pi/2)
        let endAngle = startAngle + CGFloat(Double.pi * 2)

        return UIBezierPath(arcCenter: CGPoint(x: circleRadius, y: circleRadius), radius: circleRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        circlePathLayer.frame = bounds
        circlePathLayer.path = circlePath().cgPath
        circlePathLayer.strokeEnd = 0.25
        circlePathLayer.add(rotationAnimation, forKey: "transform.rotation")

    }

    let rotationAnimation: CAAnimation = {
        let animation = CABasicAnimation(keyPath: "transform.rotation")
        animation.fromValue = 0
        animation.toValue = Double.pi * 2
        animation.duration = 4
        animation.repeatCount = MAXFLOAT

        return animation
    }()
}

I know this question was posted a long way back but I just hope this solves the issue of someone who is looking for the similar issue.


问:
Call a user defined function defined in schemaA from a view defined in SchemaB SQL Server
I am having a problem to call a function from my view. They are both in different schemas, so I have something like this:

```<code>View [SchemaA].[ViewName]
    WITH SCHEMABINDING
    AS
        SELECT DISTINCT
             [SchemaB].[functionName](value) as 'variable'
        FROM
            //Several selects with joins
</code>```

The problem is that I am getting this error: "Cannot schema bind view 'SchemaA.view'. 'SchemaB.functionName' is not schema bound."

I have also tried to include the database name in the call to the function like this:

```<code>[database].[SchemaB].[functionName]
</code>```

But it still didn't work. However it returned a different error: "Cannot schema bind view 'SchemaA.view' because name 'SchemaB.functionName' is invalid for schema binding. Names must be in two-part format and an object cannot reference itself."

Any idea about what I am doing wrong?

Thanks

答:
Your function should be schema bound (WITH SCHEMABINDING):

```<code>CREATE FUNCTION SchemaBinded(@INPUT INT)
RETURNS INT WITH SCHEMABINDING
BEGIN
RETURN @INPUT * 2 + 50
END
GO
</code>```

Body:
I am having a problem to call a function from my view. They are both in different schemas, so I have something like this:

View [SchemaA].[ViewName]
    WITH SCHEMABINDING
    AS
        SELECT DISTINCT
             [SchemaB].[functionName](value) as 'variable'
        FROM
            //Several selects with joins

The problem is that I am getting this error: "Cannot schema bind view 'SchemaA.view'. 'SchemaB.functionName' is not schema bound."

I have also tried to include the database name in the call to the function like this:

[database].[SchemaB].[functionName]

But it still didn't work. However it returned a different error: "Cannot schema bind view 'SchemaA.view' because name 'SchemaB.functionName' is invalid for schema binding. Names must be in two-part format and an object cannot reference itself."

Any idea about what I am doing wrong?

Thanks

Body:
Your function should be schema bound (WITH SCHEMABINDING):

CREATE FUNCTION SchemaBinded(@INPUT INT)
RETURNS INT WITH SCHEMABINDING
BEGIN
RETURN @INPUT * 2 + 50
END
GO


问:
How do I resize high-res photos to thumbnails?
I have a site where a user can upload a photo. I have no idea how to handle photos. To make a thumbnail out of a large res photo, do I just resize the width and the height? Or is there  a better way to do this?

If you could point me to any resources or give me any tips, that would be great.

I'm using Ruby on Rails, if that matters. I don't really want gems for this because I want to learn how to do it myself.

答:
For some of this, "learning how to do it yourself" is going to be a significant undertaking.  Resizing the image, for example.  Go ahead and find an open source library (such as a gem) that resizes images and look through its source code.  It's not impossible to do on your own, but a lot of that sort of thing is built on the expertise that's come before, etc.  There's nothing wrong with making use of a tool somebody else has created, provided that you understand what the tool is doing.

A few points to hopefully help you out:

Go with a white-list approach of which image formats you support.  Don't just let users upload anything that they call an image.

Each format you support is going to have its own standards (possibly multiple) for meta-data.  Stripping out that data wholesale may or may not be a good idea.  For example, a jpeg may contain its orientation in its EXIF data and if you strip that out you may be effectively rotating the image.  Certain fields, such as geotagging, you may want to strip out in the effort to protect your users' privacy, etc.  Again, look into existing libraries for this and see how they do it.

DO NOT implicitly trust the file name extension for determining the type of the image.  It's possible for a user to construct a malicious file that isn't really an image, pass it off as an image to an unsuspecting host, and effectively open a security flaw on that host as it tries to process the file as an image.  There was a question about determining file type in Ruby here, and I'm sure there's a lot more to be found on the subject.


问:
post array inside json object in retrofit?
I m working with retrofit  and sending to request to server via post method i am getting response currectly  for this json see this is post i m sending to server .

adreess class for post i m using this object

```<code>{
     "years":"1855",
     "months":"6",
     "skills":1
}
</code>```

now  i have to implement array inside object in skills how to post this

```<code>{
    "years":"1",
    "months":"6",
    "skills":["1","2","3"],
}
</code>```

how to get array inside object in retrofit
i m using interface like this

```<code>Call<AddressResponce> address(@Body Adreess adreess);
</code>```

答:
```<code>package com.example;

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Example {

@SerializedName("years")
@Expose
private String years;
@SerializedName("months")
@Expose
private String months;
@SerializedName("skills")
@Expose
private List<String> skills = null;

public String getYears() {
return years;
}

public void setYears(String years) {
this.years = years;
}

public String getMonths() {
return months;
}

public void setMonths(String months) {
this.months = months;
}

public List<String> getSkills() {
return skills;
}

public void setSkills(List<String> skills) {
this.skills = skills;
}

}
</code>```

I hope it's useful to you ..!

Body:
I m working with retrofit  and sending to request to server via post method i am getting response currectly  for this json see this is post i m sending to server .

adreess class for post i m using this object

{
     "years":"1855",
     "months":"6",
     "skills":1
}

now  i have to implement array inside object in skills how to post this

{
    "years":"1",
    "months":"6",
    "skills":["1","2","3"],
}

how to get array inside object in retrofit
i m using interface like this

Call<AddressResponce> address(@Body Adreess adreess);

Body:
package com.example;

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Example {

@SerializedName("years")
@Expose
private String years;
@SerializedName("months")
@Expose
private String months;
@SerializedName("skills")
@Expose
private List<String> skills = null;

public String getYears() {
return years;
}

public void setYears(String years) {
this.years = years;
}

public String getMonths() {
return months;
}

public void setMonths(String months) {
this.months = months;
}

public List<String> getSkills() {
return skills;
}

public void setSkills(List<String> skills) {
this.skills = skills;
}

}

I hope it's useful to you ..!


问:
how to obtain license key for here maps api
I am not able to find the license key from here maps. I have my app ID and app Code already but not the license key.</p>

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    NMAApplicationContext.setAppId(yourAppID, appCode: yourAppCode, licenseKey: yourLicenseKey)
    return true
}
</code>```

答:
You can get the API key from here after you sign up.

When you sign up, A project will be created for you.

You will need to add your bundle id and generate the API key from the project settings(Project Page).

Also, when you create the app you will also receive and email which guides you through the steps.

Body:
I am not able to find the license key from here maps. I have my app ID and app Code already but not the license key.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    NMAApplicationContext.setAppId(yourAppID, appCode: yourAppCode, licenseKey: yourLicenseKey)
    return true
}


问:
Button text not visible fully in gridBagLayout
I added main panel and next add to button panel to it. According to check box , select and deselect I change button text. but one text not visible fully.

This is my lay out code.

```<code>    public RestartTreatmentDialog()
  {
    final GridBagLayout gridBagLayout = new GridBagLayout();
    gridBagLayout.columnWidths = new int[] { 0, 0 };
    gridBagLayout.rowHeights = new int[] { 0, 0, 0 };
    gridBagLayout.columnWeights = new double[] { 1.0, Double.MIN_VALUE };
    gridBagLayout.rowWeights = new double[] { 1.0, 0.0, Double.MIN_VALUE };

    getContentPane().setLayout(gridBagLayout);

    final GridBagConstraints gbc_panel = new GridBagConstraints();
    gbc_panel.insets = new Insets(0, 0, 5, 0);
    gbc_panel.fill = GridBagConstraints.BOTH;
    gbc_panel.gridx = 0;
    gbc_panel.gridy = 0;

    getContentPane().add(getTopPanel(), gbc_panel);

    final GridBagConstraints gbc_panel_1 = new GridBagConstraints();
    gbc_panel_1.fill = GridBagConstraints.VERTICAL;
    gbc_panel_1.gridx = 0;
    gbc_panel_1.gridy = 1;

    getContentPane().add(getButtonPanel(), gbc_panel_1);
  }
</code>```

This is button panel.

```<code>if (buttonPanel == null)
    {
      buttonPanel = new Panel();

      final GridBagLayout gbl_buttonPanel = new GridBagLayout();
      gbl_buttonPanel.columnWidths = new int[] { 0, 0, 0 };
      gbl_buttonPanel.rowHeights = new int[] { 0, 0 };
      gbl_buttonPanel.columnWeights = new double[] { 0.0, 0.0, Double.MIN_VALUE };
      gbl_buttonPanel.rowWeights = new double[] { 0.0, Double.MIN_VALUE };

      buttonPanel.setLayout(gbl_buttonPanel);

      final GridBagConstraints gbc_button = new GridBagConstraints();
      gbc_button.insets = new Insets(0, 0, 5, 5);
      gbc_button.gridx = 0;
      gbc_button.gridy = 0;

      buttonPanel.add(getRestartButton(), gbc_button);

      final GridBagConstraints gbc_button_1 = new GridBagConstraints();
      gbc_button_1.insets = new Insets(0, 0, 5, 0);
      gbc_button_1.gridx = 1;
      gbc_button_1.gridy = 0;

      buttonPanel.add(getCancelButton(), gbc_button_1);
    }
</code>```

I expect some expert help to fix this issue?

答:
some solution:

1) set a fix bigger size for your left button, so when you cange size you have no problem some code

2) cange button left to right and set the size like automatic
some code

Body:
I added main panel and next add to button panel to it. According to check box , select and deselect I change button text. but one text not visible fully.

This is my lay out code.

    public RestartTreatmentDialog()
  {
    final GridBagLayout gridBagLayout = new GridBagLayout();
    gridBagLayout.columnWidths = new int[] { 0, 0 };
    gridBagLayout.rowHeights = new int[] { 0, 0, 0 };
    gridBagLayout.columnWeights = new double[] { 1.0, Double.MIN_VALUE };
    gridBagLayout.rowWeights = new double[] { 1.0, 0.0, Double.MIN_VALUE };

    getContentPane().setLayout(gridBagLayout);

    final GridBagConstraints gbc_panel = new GridBagConstraints();
    gbc_panel.insets = new Insets(0, 0, 5, 0);
    gbc_panel.fill = GridBagConstraints.BOTH;
    gbc_panel.gridx = 0;
    gbc_panel.gridy = 0;

    getContentPane().add(getTopPanel(), gbc_panel);

    final GridBagConstraints gbc_panel_1 = new GridBagConstraints();
    gbc_panel_1.fill = GridBagConstraints.VERTICAL;
    gbc_panel_1.gridx = 0;
    gbc_panel_1.gridy = 1;

    getContentPane().add(getButtonPanel(), gbc_panel_1);
  }

This is button panel.

if (buttonPanel == null)
    {
      buttonPanel = new Panel();

      final GridBagLayout gbl_buttonPanel = new GridBagLayout();
      gbl_buttonPanel.columnWidths = new int[] { 0, 0, 0 };
      gbl_buttonPanel.rowHeights = new int[] { 0, 0 };
      gbl_buttonPanel.columnWeights = new double[] { 0.0, 0.0, Double.MIN_VALUE };
      gbl_buttonPanel.rowWeights = new double[] { 0.0, Double.MIN_VALUE };

      buttonPanel.setLayout(gbl_buttonPanel);

      final GridBagConstraints gbc_button = new GridBagConstraints();
      gbc_button.insets = new Insets(0, 0, 5, 5);
      gbc_button.gridx = 0;
      gbc_button.gridy = 0;

      buttonPanel.add(getRestartButton(), gbc_button);

      final GridBagConstraints gbc_button_1 = new GridBagConstraints();
      gbc_button_1.insets = new Insets(0, 0, 5, 0);
      gbc_button_1.gridx = 1;
      gbc_button_1.gridy = 0;

      buttonPanel.add(getCancelButton(), gbc_button_1);
    }

I expect some expert help to fix this issue?


问:
Handling an empty UITableView. Print a friendly message
I have a UITableView that in some cases it is legal to be empty. So instead of showing the
background image of the app, I would prefer to print a friendly message in the screen, such as:

This list is now empty

What is the simplest way to do it?

答:
Probably not the greatest solution, but I did this by just putting a label at the bottom of my table and if the rows = 0 then I assign it some text. Pretty easy, and achieves what you are trying to do with a few lines of code.

I have two sections in my table (jobs and schools)

```<code>    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if (jobs.count == 0 && schools.count == 0) {
        emptyLbl.text = "No jobs or schools"
    } else {
        emptyLbl.text = ""
    }
</code>```

Body:
Probably not the greatest solution, but I did this by just putting a label at the bottom of my table and if the rows = 0 then I assign it some text. Pretty easy, and achieves what you are trying to do with a few lines of code.

I have two sections in my table (jobs and schools)

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if (jobs.count == 0 && schools.count == 0) {
        emptyLbl.text = "No jobs or schools"
    } else {
        emptyLbl.text = ""
    }


问:
Laravel Date Time Based Ads System
I have developed a AD System in Laravel But I am stuck showing AD to user.

Here is the process I follow:

User Create A Ad From Panel

Ad field

Ad Title

Ad description

Ad Start Date

Ad End Date

Here I am stuck that how to get ad record from database according to the start date and end date.

If the start date and end date only have one day period then this AD come first.

答:
If it is the result what you want:</p>

```<code>$results = Ad::select(DB::raw('DATEDIFF(`ad_start_date`, `ad_end_date`) AS date_diff, ad.*'))
    ->where('date_diff', '>=', 1)
    ->orderBy('date_diff', 'desc')
    ->get();
</code>```

Title: Laravel Date Time Based Ads System

Body:
If it is the result what you want:

$results = Ad::select(DB::raw('DATEDIFF(`ad_start_date`, `ad_end_date`) AS date_diff, ad.*'))
    ->where('date_diff', '>=', 1)
    ->orderBy('date_diff', 'desc')
    ->get();


问:
How to ensure sequential primary key in oracle database using sequence table when doing inserts from multiple threads in a spring batch application
I have a data aggregation and loading application that loads data files to an oracle database. We are using spring integration for file poling and spring batch for loading data to the database. When more than one file is being processed (read and loaded to database ) primary key tends to skip some values.
Oracle sequence created is.

```<code>CREATE SEQUENCE  "SCHEMA"."SEQUENCE_TABLE_NAME"  MINVALUE 1 MAXVALUE
    9999999999999999999999999999 INCREMENT BY 1 START WITH 241488161 CACHE
    20 NOORDER  NOCYCLE ;
</code>```

An inbound-channel-adapter has a poller which has as task executor. the inbound channel adapter sends the file to a transformer which creates a JobLaunchRequest object that is launched by the job-launching-gateway.
The job has a reader and a jdbcwriter that executes the following statement.

```<code><bean id="itemWriter" class="org.springframework.batch.item.database.JdbcBatchItemWriter">
    <property name="dataSource" ref="dataSource"/>
    <property name="sql">
        <value>
            <![CDATA[
            insert  into data_table (id,dataA,dataB)
            values(SEQUENCE_TABLE_NAME.nextval,:dataA,:dataB)
            ]]>
        </value>
    </property>
    <property name="itemSqlParameterSourceProvider">
        <bean
             class="org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider"/>
    </property>
</bean>
</code>```

The key reason for loading to database is that an api is exposed which depends on the primary key being ordered and sequential. but once two many files are present in the folder. due to multiple threads reading and writing to the db. the primary key provided by the sequence table is missing some values in between.

A similar case is explained here (oracle perspective alone).

答:
IMHO, if you have a requirement that no gap could exist in a column, then you should not use the sequence of the primary key for that, because the primary key must exist at INSERT time, and if the transaction is later aborted you will get a gap.

A simple solution would be to have a dedicated column distinct from the primary key that would be updated after a successful insertion by a single thread (or a dedicated single threaded application). This task would fetch recently inserted rows for example primary key above current sequence value minus a threshold (to speed up the request if table contains a great number of rows) and dedicated column value as null, assign them consecutive values, commit and iterate. Once per day at the moment of lowest load, the task should fetch all rows that could have a null value on the dedicated column (non indexed query) as a catch all pass.

Body:
I have a data aggregation and loading application that loads data files to an oracle database. We are using spring integration for file poling and spring batch for loading data to the database. When more than one file is being processed (read and loaded to database ) primary key tends to skip some values.
Oracle sequence created is.

CREATE SEQUENCE  "SCHEMA"."SEQUENCE_TABLE_NAME"  MINVALUE 1 MAXVALUE
    9999999999999999999999999999 INCREMENT BY 1 START WITH 241488161 CACHE
    20 NOORDER  NOCYCLE ;

An inbound-channel-adapter has a poller which has as task executor. the inbound channel adapter sends the file to a transformer which creates a JobLaunchRequest object that is launched by the job-launching-gateway.
The job has a reader and a jdbcwriter that executes the following statement.

<bean id="itemWriter" class="org.springframework.batch.item.database.JdbcBatchItemWriter">
    <property name="dataSource" ref="dataSource"/>
    <property name="sql">
        <value>
            <![CDATA[
            insert  into data_table (id,dataA,dataB)
            values(SEQUENCE_TABLE_NAME.nextval,:dataA,:dataB)
            ]]>
        </value>
    </property>
    <property name="itemSqlParameterSourceProvider">
        <bean
             class="org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider"/>
    </property>
</bean>

The key reason for loading to database is that an api is exposed which depends on the primary key being ordered and sequential. but once two many files are present in the folder. due to multiple threads reading and writing to the db. the primary key provided by the sequence table is missing some values in between.

A similar case is explained here (oracle perspective alone).


问:
Email Sending Failed
I am developing a page in that i have to send the email. but i am getting the error in my server mail track and mail is not sending.

ECDHE-RSA-AES128-GCM-SHA256:128 CV=yes: SMTP error from remote mail server after end of data: 550-5.7.1 [188.114.251.250 12] Our system has detected that this message is\n550-5.7.1 likely unsolicited mail. To reduce the amount of spam sent to Gmail,\n550-5.7.1 this message has been blocked. Please visit\n550-5.7.1 https://support.google.com/mail/?p=UnsolicitedMessageError\n550 5.7.1 for more information. a21si10096467lfk.400 - gsmtp

Please give me solution of it.

Thanks in advance

答:
You should configure email headers properly in your script when sending the email message. Like this:

```<code><?
$from = "email@domain.com";

$headers = "From: $from
X-Sender: $from
Reply-To: no-reply@domain.com
MIME-Version: 1.0
X-Priority: 5
X-MSMail-Priority: High
X-Mailer: Microsoft Outlook Express 6.00.2800.1437
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1441
Content-type: text/html; charset=iso-8859-1
";

$subject = "subject";
$message = "whatever";
$to-address = "email address where to send the message";
mail($to-address,$subject,$message,$headers);

?>
</code>```

Please keep in mind that $from address has to be a real address and existing on that server (gmail checks that). Also be sure that you have properly configured SPF, DKIM, DMARC, you have reverse DNS for your server's ip and the server has a valid hostname.

Title: Email Sending Failed

Body:
You should configure email headers properly in your script when sending the email message. Like this:

<?
$from = "email@domain.com";

$headers = "From: $from
X-Sender: $from
Reply-To: no-reply@domain.com
MIME-Version: 1.0
X-Priority: 5
X-MSMail-Priority: High
X-Mailer: Microsoft Outlook Express 6.00.2800.1437
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1441
Content-type: text/html; charset=iso-8859-1
";

$subject = "subject";
$message = "whatever";
$to-address = "email address where to send the message";
mail($to-address,$subject,$message,$headers);

?>

Please keep in mind that $from address has to be a real address and existing on that server (gmail checks that). Also be sure that you have properly configured SPF, DKIM, DMARC, you have reverse DNS for your server's ip and the server has a valid hostname.


问:
Hive JDBC Vs CLI client
I need to access data using Hive programatically (data in the order of GBs per query). I was evaluating CLI driver Vs Hive JDBC driver.

When we use JDBC, there is an extra overhead of thrift server & I am trying to understand how heavy is that. Also can it be a single point bottleneck if multiple clients connect to single thrift server? Or is it a common practice that people configure multiple thrift servers on Hadoop and do some load balancing stuff?

I am looking for the better performance rather than faster prototyping.
Thanks in advance.

答:
You can try using connection pooling. I had a similar issue while submitting hive query through JDBC was taking more time than hive cli.

Also in your connection string mention few parameters as below:

jdbc:hive2://servername:portno/;hive.execution.engine=tez;tez.queue.name=alt;hive.exec.parallel=true;hive.vectorized.execution.enabled=true;hive.vectorized.execution.reduce.enabled=true;

Title: Hive JDBC Vs CLI client


问:
Can't remove contacts from an address book in Outlook 2010
I can add a contact to a address book but for some reason I can't remove it. The code I'm executing is as follows.

```<code>String abName = "Name ofthe targetted address book";
Outlook.Folder addressBook;
if (targetFolder.Folders.OfType<Outlook.Folder>().Any(element
  => element.Name == abName))
  addressBook = targetFolder.Folders[abName] as Outlook.Folder;
else
  addressBook = targetFolder.Folders.Add(
    abName, Outlook.OlDefaultFolders.olFolderContacts) as Outlook.Folder;
addressBook.ShowAsOutlookAB = true;

for (int i = addressBook.Items.Count - 1; i >= 0; i--)
  if (!stringList.Any(element
    => element == addressBook.Items.OfType<Outlook.ContactItem>()
      .ToList()[i].Email1Address))
    addressBook.Items.OfType<Outlook.ContactItem>().ToList().RemoveAt(i);
</code>```

The fetching of the address book works and the matching for strings too. I get into the RemoveAt line for the exactly correct contacts. There's no error or other message when I execute the removal. Still, the contact list remain unaffected.

Why?

What can I do to actually remove the contacts?

I suspect that I may be working on a copy of the actual list containing the contacts. The problem is that if I don't create a List, I'm not sure how to alter the list of contacts.

So, the most helpful answer would shed some light on how to alter addressBook (or perhaps addressBook.Items) given certain condition. E.g., say that we'd like to remove all the contants the name of whom starts with the letter "Q".

At this moment I can only think of a super ugly work-around and it's so rectum-ugly that I don't even mention it here. Really ugly...

答:
Here is a solution

```<code>    private void ClearContact(Outlook.Application outlookApplication)
    {
        Outlook.MAPIFolder contactFolder = outlookApplication.Session.GetDefaultFolder(OlDefaultFolders.olFolderContacts);
        int total = contactFolder.Items.Count;
        while (total > 0)
        {
            // first index number is 1 not 0
            var contact = (Outlook.ContactItem)contactFolder.Items[1];
            contact.Delete();
            total = contactFolder.Items.Count;
        }
    }
</code>```

I use netoffice outlook api
http://netoffice.codeplex.com/wikipage?title=Outlook_Example05
And use while loop to delete all contact

Body:
I can add a contact to a address book but for some reason I can't remove it. The code I'm executing is as follows.

String abName = "Name ofthe targetted address book";
Outlook.Folder addressBook;
if (targetFolder.Folders.OfType<Outlook.Folder>().Any(element
  => element.Name == abName))
  addressBook = targetFolder.Folders[abName] as Outlook.Folder;
else
  addressBook = targetFolder.Folders.Add(
    abName, Outlook.OlDefaultFolders.olFolderContacts) as Outlook.Folder;
addressBook.ShowAsOutlookAB = true;

for (int i = addressBook.Items.Count - 1; i >= 0; i--)
  if (!stringList.Any(element
    => element == addressBook.Items.OfType<Outlook.ContactItem>()
      .ToList()[i].Email1Address))
    addressBook.Items.OfType<Outlook.ContactItem>().ToList().RemoveAt(i);

The fetching of the address book works and the matching for strings too. I get into the RemoveAt line for the exactly correct contacts. There's no error or other message when I execute the removal. Still, the contact list remain unaffected.

Why?

What can I do to actually remove the contacts?

I suspect that I may be working on a copy of the actual list containing the contacts. The problem is that if I don't create a List, I'm not sure how to alter the list of contacts.

So, the most helpful answer would shed some light on how to alter addressBook (or perhaps addressBook.Items) given certain condition. E.g., say that we'd like to remove all the contants the name of whom starts with the letter "Q".

At this moment I can only think of a super ugly work-around and it's so rectum-ugly that I don't even mention it here. Really ugly...

Body:
Here is a solution

    private void ClearContact(Outlook.Application outlookApplication)
    {
        Outlook.MAPIFolder contactFolder = outlookApplication.Session.GetDefaultFolder(OlDefaultFolders.olFolderContacts);
        int total = contactFolder.Items.Count;
        while (total > 0)
        {
            // first index number is 1 not 0
            var contact = (Outlook.ContactItem)contactFolder.Items[1];
            contact.Delete();
            total = contactFolder.Items.Count;
        }
    }

I use netoffice outlook api
http://netoffice.codeplex.com/wikipage?title=Outlook_Example05
And use while loop to delete all contact


问:
Why does react-routing not work directly in the browser?
I am using react-router 2.0 in my universal react app. Navigation trough the Link component works but when I paste the url manually nothing happens(browser hangs). How can I fix this issue? This is the router code:</p>

```<code><Route path="/" component={App}>
  { /* Home (main) route */ }
  <IndexRoute component={Home}/>

  { /* Routes requiring login */ }
  <Route onEnter={requireLogin}>
    <Route path="chat" component={Chat}/>
    <Route path="loginSuccess" component={LoginSuccess}/>
  </Route>

  { /* Routes */ }
  <Route path="about" component={About}/>
  <Route path="login" component={Login}/>
  <Route path="pagination" component={Pagination}/>
  <Route path="survey/:user" component={Survey}/>
  <Route path="widgets" component={Widgets}/>
  <Route path="search" component={Search}/>
  <Route path="make/model/:id" component={Details}/>
  { /* Catch all route */ }
  <Route path="*" component={NotFound} status={404} />
</Route>
</code>```

答:
try this in your routes

add "/" in all routes like this

```<code><Route path="/about" component={About}/>
</code>```

Body:
I am using react-router 2.0 in my universal react app. Navigation trough the Link component works but when I paste the url manually nothing happens(browser hangs). How can I fix this issue? This is the router code:

<Route path="/" component={App}>
  { /* Home (main) route */ }
  <IndexRoute component={Home}/>

  { /* Routes requiring login */ }
  <Route onEnter={requireLogin}>
    <Route path="chat" component={Chat}/>
    <Route path="loginSuccess" component={LoginSuccess}/>
  </Route>

  { /* Routes */ }
  <Route path="about" component={About}/>
  <Route path="login" component={Login}/>
  <Route path="pagination" component={Pagination}/>
  <Route path="survey/:user" component={Survey}/>
  <Route path="widgets" component={Widgets}/>
  <Route path="search" component={Search}/>
  <Route path="make/model/:id" component={Details}/>
  { /* Catch all route */ }
  <Route path="*" component={NotFound} status={404} />
</Route>

Body:
try this in your routes

add "/" in all routes like this

<Route path="/about" component={About}/>


问:
Subquery from different data source (Eclipse report)
My requirement is to have a query that is something like the following:

```<code>SELECT * FROM table1
WHERE oid in (
    SELECT * FROM table 2
    WHERE condition )
</code>```

My problem is that table1 and table2 are on different databases.

I've read around that you can do something like [db1].table but it doesn't work in my case using Eclipse Birt enviroment.

答:
You can solve this in two ways:

1) Use something like a database link. There is limited support in MySQL (note: I've hardly ever used MySQL) See Oracle Database Link - MySQL Equivalent?. This way, you move the problem to the database level.

2) Depending on the actual problem (read: the length of the "select oid FROM table2 where condition" results, you could use either a BIRT data cube or

3) Use two DataSets and a layout structure list-table like this:

The two DataSets need different DataSources.

DataSet "T2_oids" with a query "select oid from table2 where condition".

DataSet "T1_object" with a single parameter param_oid and a query "select * from table1 where oid = ?".

Layout structure:
* Outer ListItem "T2_oids" bound to DataSet "T2_oids"
* Inner TableItem or ListItem "T1_object" bound to DataSet "T1_object" with the parameter bound to row["oid"] (or row["OID"], use the list box). This item must be placed inside the T2_oids detail section.

Since T1_object will return a single row, you can even use a GridItem instead of a TableItem or ListItem.

Body:
My requirement is to have a query that is something like the following:

SELECT * FROM table1
WHERE oid in (
    SELECT * FROM table 2
    WHERE condition )

My problem is that table1 and table2 are on different databases.

I've read around that you can do something like [db1].table but it doesn't work in my case using Eclipse Birt enviroment.


问:
Having bootstrap css and prime ng css files in the same application?
I am planning on using bootstrap on my main dashboard page and Prime NG data tables on a page that will show up from one of the menu options on my dashboard. I am using angular (angular 4) .

Would it be an issue if I reference the bootstrap css file and also prime ng theme css files?

I am planning to import the bootstrap css file as
@import url ('path to bootstrap css file') inside the style.css file  and within my specifyc component css file I plan to import the prime NG theme css file

I am not expert with styling and CSS just wanted to confirm if the above is a good approach and would there be issues having bootstrap and prime NG css files in the same application?

bootstrap - http://getbootstrap.com/getting-started/
Prime NG - https://www.primefaces.org/primeng/#/setup

答:
I am currently working on a project using both primeNG and bootstrap 3. I have absolutely no problem with them.

I am using Angular-CLI and I imported the required css files into the scripts attribute of the angular-cli.json file. But it's up to you to chose how to import them !


问:
create random number from a poisson dist. using MersenneTwister
Hi I have a simulation I'm runnning in which I get random numbers from a uniform and normal distributions easily:

```<code>#include <iostream>
#include "MersenneTwister.h"
using namespace std;
int main()
{
    MTRand mtrand1;
    double r1,r2;
    r1 = mtrand.rand(); // from a uninform dist.
    r2 = mtrand1.randNorm(); //from a normal dist.
}
</code>```

I would like to use this random number generator to obtain a random number from a poisson distribution with mean 'A'.

Any idea about how to implement this procedure using the MersseneTwister code?
the code can be found here:
https://gcc.gnu.org/bugzilla/attachment.cgi?id=11960. and it is widely used.

答:
You can use the standard library

```<code>#include<random>

double mean = 3.1415926;
std::mt19937 mt{std::random_device{}()};
std::poisson_distribution<> pd{mean};

auto n = pd(mt);  // get a number
</code>```

Do note that seeding with std::random_device is unlikely to be satisfactory.

Body:
Hi I have a simulation I'm runnning in which I get random numbers from a uniform and normal distributions easily:

#include <iostream>
#include "MersenneTwister.h"
using namespace std;
int main()
{
    MTRand mtrand1;
    double r1,r2;
    r1 = mtrand.rand(); // from a uninform dist.
    r2 = mtrand1.randNorm(); //from a normal dist.
}

I would like to use this random number generator to obtain a random number from a poisson distribution with mean 'A'.

Any idea about how to implement this procedure using the MersseneTwister code?
the code can be found here:
https://gcc.gnu.org/bugzilla/attachment.cgi?id=11960. and it is widely used.

Body:
You can use the standard library

#include<random>

double mean = 3.1415926;
std::mt19937 mt{std::random_device{}()};
std::poisson_distribution<> pd{mean};

auto n = pd(mt);  // get a number

Do note that seeding with std::random_device is unlikely to be satisfactory.


答: You can! :) But just be careful if you want to overide the bootstrap, put your code, after the @import :) </p>

Title: Having bootstrap css and prime ng css files in the same application?

Body:
I am planning on using bootstrap on my main dashboard page and Prime NG data tables on a page that will show up from one of the menu options on my dashboard. I am using angular (angular 4) .

Would it be an issue if I reference the bootstrap css file and also prime ng theme css files?

I am planning to import the bootstrap css file as
@import url ('path to bootstrap css file') inside the style.css file  and within my specifyc component css file I plan to import the prime NG theme css file

I am not expert with styling and CSS just wanted to confirm if the above is a good approach and would there be issues having bootstrap and prime NG css files in the same application?

bootstrap - http://getbootstrap.com/getting-started/
Prime NG - https://www.primefaces.org/primeng/#/setup


问:
AJAX POST-method not allowed Error 405
I'm trying to send an email when I click on a button. For this I make an ajax call to a php file:

Ajax call:

```<code> function postAjax(arr) {
     $.ajax({
         url: "../BackEnd/AjaxHandler.php",
         data: { 'action': 'mail' },
         type: "GET"
     });
 }
</code>```

php file (Ajaxhandler.php)

```<code><?php
   if(isset($_GET['action']) && !empty($_GET['action'])) {
   $action = $_GET['action'];
   switch($action){
      case 'mail':
         mail('N.Suhner@wigasoft.ch', 'Mein Betreff', 'tsest');
         break;
      }
   }
?>
</code>```

call:

```<code>$("#mailto").click(function() {
   postAjax(listOfTasks);
 });
</code>```

In the call I make some more things but these are not relevant (styling).

When I click on the button I got an error that the POST-method is not allowed. Does anyone know what I am doing wrong?

答:
Try with this</p>

```<code> function postAjax(arr) {
  $.ajax({
   type: "POST",
   url: "../_BackEnd/AjaxHandler.php",
   data: { id: 12 },
   contentType: "application/json; charset=utf-8",
   dataType: "json",
   success: function (data) {
       alert(data);
   }
  });
 }
</code>```

Title: AJAX POST-method not allowed Error 405

Body:
I'm trying to send an email when I click on a button. For this I make an ajax call to a php file:

Ajax call:

 function postAjax(arr) {
     $.ajax({
         url: "../BackEnd/AjaxHandler.php",
         data: { 'action': 'mail' },
         type: "GET"
     });
 }

php file (Ajaxhandler.php)

<?php
   if(isset($_GET['action']) && !empty($_GET['action'])) {
   $action = $_GET['action'];
   switch($action){
      case 'mail':
         mail('N.Suhner@wigasoft.ch', 'Mein Betreff', 'tsest');
         break;
      }
   }
?>

call:

$("#mailto").click(function() {
   postAjax(listOfTasks);
 });

In the call I make some more things but these are not relevant (styling).

When I click on the button I got an error that the POST-method is not allowed. Does anyone know what I am doing wrong?

Body:
Try with this

 function postAjax(arr) {
  $.ajax({
   type: "POST",
   url: "../_BackEnd/AjaxHandler.php",
   data: { id: 12 },
   contentType: "application/json; charset=utf-8",
   dataType: "json",
   success: function (data) {
       alert(data);
   }
  });
 }


问:
why android is built on a VM (Dalvik)
I am curious to know what made google choose to develop android's framework on java VM.

In the process of writing code for android for nearly 6 months now, I observed that running code on a VM in a resource limited platform is really slow. There is a lot of overhead involved. I know that java is portable etc etc, is it not possible at all to use native languages and get both performance and features offered by a VM ? For performance oriented applications one still ends up writing native code and wrap it with JNI,

So why did google choose this particular stack :

Arm based core (understandable, ARM is the best for mobile devices)

Linux (Open source)

Java VM (My question)

EDIT : I know java - JVM runs on par with C++ applications on my server, but not on android.
With respect to android its not the case - As a matter of my experience, a C++ code wrapped with JNI runs far faster than java code (note I have even checked with exact same code from a static block in java) I will agree with your answer on any other platform.

答:
1) Java is, as far as I know, the most universally taught language in universities and even high schools/equivalent. It is used widely in the professional world and has a lot of codebase behind it to help ease developers into creating more quality apps, faster.

2) The overhead is not that great vs. native code, especially with well designed code that is JIT optimized and being monitored by an ever-more-well-designed-gc.

Really, I think these two reasons alone can justify why Java was chosen as the primary language to be supported on Android.

Title: why android is built on a VM (Dalvik)


问:
Assignment using an object and input data JAVA
so my assignment is to create an object named city and have the longitude, latitude and name of the city and then ask for the number of cities, then the users input of the name, longitude, and latitude into an array for access. How would i accomplish this with what i have now?

```<code>import java.util.Scanner;

public class Assignment3 {

    public static void main(String[] args) {

        Scanner lat = new Scanner(System.in);  //for double data
        Scanner lon = new Scanner(System.in);  //for double data
        Scanner city = new Scanner(System.in); //for string data
        Scanner in = new Scanner(System.in);  //for int

        System.out.print("How many cities? ");
        int number = in.nextInt();

        City [] cities = new City [number];

        for(int i = 1; i <= number; i++){

            System.out.println("City # " + i);
            System.out.print("Enter name: " );
            String name = city.Next();
            System.out.print("Enter longitude: ");
            double longitude = lon.nextDouble();
            System.out.println("Enter latitude: ");
            double latitude = lat.nextDouble();

        }

    }

}

public class City {

    String name;      //name of cities
    double lon, lat;  //longitude & latitude

    City(String name, double lon, double lat)
    {
        this.name = name;
        this.lon = lon;
        this.lat = lat;
    }

    public void report(){    //should report current position of a city

        System.out.println("City: " + this.name); // displays city name
        System.out.println("Longitude: " + this.lon);  //displays longitude
        System.out.println("Latitude: " + this.lat);    //displays latitude
    }

    public double distanceFrom(City otherCity){  //should calculate the distance
        return 0;
    }
}
</code>```

The point is so that you can then ask for the cities direct location and then the distance between them. Any help is greatly appreciated thank you

答:
You can achieve that in this simple approach:

Define setter instance methods of City class to each attribute that you want user to input it then in main program iterate over each object of cities and set its Info:

```<code>public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.print("How many cities? ");
        int number = input.nextInt();
        City [] cities = new City [number];
         for(int i = 0; i < number; i++){
            cities[i] = new City(); // create new object of City
            System.out.println("City # " + (i+1));
            System.out.print("Enter name: " );
            String name = input.next();
            cities[i].setName(name);
            System.out.print("Enter longitude: ");
            double longitude = input.nextDouble();
            cities[i].setLongitude(longitude);
            System.out.print("Enter latitude: ");
            double latitude = input.nextDouble();
            cities[i].setLatitude(latitude);
        }
}

public class City {

    private String name;      //name of cities
    private double lon, lat;  //longitude & latitude

    City(){  // default constructor
       name="";
       this.lon = 0;
       this.lat = 0;
    }

    City(String name, double lon, double lat)
    {
        this.name = name;
        this.lon = lon;
        this.lat = lat;
    }

    public void setName(String n){
         name = n;
    }
    public void setLongitude(double longitude){
         lon = longitude;
    }
    public void setLatitude(double latitude){
         lat = latitude;
    }
}
</code>```

Body:
so my assignment is to create an object named city and have the longitude, latitude and name of the city and then ask for the number of cities, then the users input of the name, longitude, and latitude into an array for access. How would i accomplish this with what i have now?

import java.util.Scanner;

public class Assignment3 {

    public static void main(String[] args) {

        Scanner lat = new Scanner(System.in);  //for double data
        Scanner lon = new Scanner(System.in);  //for double data
        Scanner city = new Scanner(System.in); //for string data
        Scanner in = new Scanner(System.in);  //for int

        System.out.print("How many cities? ");
        int number = in.nextInt();

        City [] cities = new City [number];

        for(int i = 1; i <= number; i++){

            System.out.println("City # " + i);
            System.out.print("Enter name: " );
            String name = city.Next();
            System.out.print("Enter longitude: ");
            double longitude = lon.nextDouble();
            System.out.println("Enter latitude: ");
            double latitude = lat.nextDouble();

        }

    }

}

public class City {

    String name;      //name of cities
    double lon, lat;  //longitude & latitude

    City(String name, double lon, double lat)
    {
        this.name = name;
        this.lon = lon;
        this.lat = lat;
    }

    public void report(){    //should report current position of a city

        System.out.println("City: " + this.name); // displays city name
        System.out.println("Longitude: " + this.lon);  //displays longitude
        System.out.println("Latitude: " + this.lat);    //displays latitude
    }

    public double distanceFrom(City otherCity){  //should calculate the distance
        return 0;
    }
}

The point is so that you can then ask for the cities direct location and then the distance between them. Any help is greatly appreciated thank you

Body:
You can achieve that in this simple approach:

Define setter instance methods of City class to each attribute that you want user to input it then in main program iterate over each object of cities and set its Info:

public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.print("How many cities? ");
        int number = input.nextInt();
        City [] cities = new City [number];
         for(int i = 0; i < number; i++){
            cities[i] = new City(); // create new object of City
            System.out.println("City # " + (i+1));
            System.out.print("Enter name: " );
            String name = input.next();
            cities[i].setName(name);
            System.out.print("Enter longitude: ");
            double longitude = input.nextDouble();
            cities[i].setLongitude(longitude);
            System.out.print("Enter latitude: ");
            double latitude = input.nextDouble();
            cities[i].setLatitude(latitude);
        }
}

public class City {

    private String name;      //name of cities
    private double lon, lat;  //longitude & latitude

    City(){  // default constructor
       name="";
       this.lon = 0;
       this.lat = 0;
    }

    City(String name, double lon, double lat)
    {
        this.name = name;
        this.lon = lon;
        this.lat = lat;
    }

    public void setName(String n){
         name = n;
    }
    public void setLongitude(double longitude){
         lon = longitude;
    }
    public void setLatitude(double latitude){
         lat = latitude;
    }
}