问:
Looping dataset in reverse order
I have a dataset with say 1 to 'n' number of DataTables in it and I want to loop it but in the reverse order ie, from DataTable n to DataTable 1. Can anyone suggest me a way to do this. I found some solutions but all are for sorting DataTables not Datasets.

```<code>DataSet _ds = new DataSet();
foreach (DataTable table in _ds.Tables)
{

}
</code>```

答:
or even simpler by decrement i within the array indexer accessor:

```<code>DataSet _ds = new DataSet();
for (int i=_ds.Tables.Count-1; i>=0; )
{
   DataTable table = _ds.Tables[i--];
}
</code>```

or by using a while-loop doing the same:

```<code>int i=_ds.Tables.Count;
while (i>=0)
{
    DataTable table = _ds.Tables[i--];
};
</code>```

Title: Looping dataset in reverse order

Body:
I have a dataset with say 1 to 'n' number of DataTables in it and I want to loop it but in the reverse order ie, from DataTable n to DataTable 1. Can anyone suggest me a way to do this. I found some solutions but all are for sorting DataTables not Datasets.

DataSet _ds = new DataSet();
foreach (DataTable table in _ds.Tables)
{

}

Body:
or even simpler by decrement i within the array indexer accessor:

DataSet _ds = new DataSet();
for (int i=_ds.Tables.Count-1; i>=0; )
{
   DataTable table = _ds.Tables[i--];
}

or by using a while-loop doing the same:

int i=_ds.Tables.Count;
while (i>=0)
{
    DataTable table = _ds.Tables[i--];
};


来源: stackexchange

问:
CAPTCHA validation with JavaScript
I am trying to validate Captcha using JavaScript. But I could't find any resource about Client API's of Captcha. Do you have any documentation?</p>

答:
You can use this it works and is very simple

myFunction();
var val=[];
val.push("VQ7W3");     /** push value in this array  */
val.push("A1234");     /** To maintain image order here   */
val.push("A32BD");   /** if first image 0_capt.jpeg contains value VQ7W3 so push this value into zero(0) index of array   */
val.push("LD673");
val.push("PQ78V");
val.push("MX81W");
var x;
/**This below method generate random number from 0-5
 * name of image starts with that number will set on
 * captcha location
 */
function myFunction() {
    x = Math.floor(Math.random() * 6);     // here 6 stand for how many images you are using return 0-6 number.
 $("#imgCaptchaPlace").html("")  ;
}

/**
 * This below method will call on change of input fields where user enter
 * captcha code value
 */
function chaeckCpatch(id)
{
  if($("#"+id).val()==val[x])
  {
    alert("match");
  }
  else
  {
   alert("No match");
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<body>
<!--  below div use to display captcha image -->
<div id="imgCaptchaPlace"></div>

<!-- below textfield where user enter captcha value -->
<input type="text" id="captchaText" onchange="chaeckCpatch(this.id);"/>

<!-- include this JS file -->
<script src="captchByAarif.js" type="text/javascript"></script>
</body>
</html></code>```

You can download captcha images that are used in this example here

https://github.com/aarifa-ds/Captcha-Code

ContentLicense: CC BY-SA 2.5

Title: CAPTCHA validation with JavaScript

Body:
You can use this it works and is very simple

myFunction();
var val=[];
val.push("VQ7W3");     /** push value in this array  */
val.push("A1234");     /** To maintain image order here   */
val.push("A32BD");   /** if first image 0_capt.jpeg contains value VQ7W3 so push this value into zero(0) index of array   */
val.push("LD673");
val.push("PQ78V");
val.push("MX81W");
var x;
/**This below method generate random number from 0-5
 * name of image starts with that number will set on
 * captcha location
 */
function myFunction() {
    x = Math.floor(Math.random() * 6);     // here 6 stand for how many images you are using return 0-6 number.
 $("#imgCaptchaPlace").html("<img id='abc' src='captcha_images/"+x+"_cpt'/>")  ;
}

/**
 * This below method will call on change of input fields where user enter
 * captcha code value
 */
function chaeckCpatch(id)
{
  if($("#"+id).val()==val[x])
  {
    alert("match");
  }
  else
  {
   alert("No match");
  }

}

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<body>
<!--  below div use to display captcha image -->
<div id="imgCaptchaPlace"></div>

<!-- below textfield where user enter captcha value -->
<input type="text" id="captchaText" onchange="chaeckCpatch(this.id);"/>

<!-- include this JS file -->
<script src="captchByAarif.js" type="text/javascript"></script>
</body>
</html>

You can download captcha images that are used in this example here

https://github.com/aarifa-ds/Captcha-Code

ContentLicense: CC BY-SA 3.0


问:
CollapsingToolbarLayout - Dim/Blur the background image
I've got a collapsing toolbar with an imageview. When extended, it looks like this:

When collapsed, it looks like this:

I know that according to the guidelines, the toolbar should be of the primary color while collapsed, but i like the way i've set it up, and would like to keep it like that.

However, obviously, the toolbar title won't be visible if the image has a lot of white in it. So, is there a way i can blur/dim the background so that the toolbar title is visible at all times?

Edit: The image in question, is loaded from the internet using Picasso.

答: Ok, So, i just ended up using android:tint in the layout file in order to add a grayish tint to the image.For reference, the tint value i set is #55000000. This seems to make the title visible even on entirely white backgrounds.


问:
Vue.js component doesn't react on data updates
Try to render a data into

 and add a event handler to update the data. My initial data is array of arrays. And handler just update these arrays.
Table rendered, handler forks fine and updates arrays, but updates doesn't show on the

. Line {{ grid[row][column] }} doesn't show updated data. Where is my mistake?

```<code>Vue.component('grid-component', {
  template: `
  <table>
    <tbody>
      <tr v-for="(row, rowIndex) in grid">
        <td v-for="(column, columnIndex) in row" @click="onClickHandler" v-bind:row="rowIndex" v-bind:column="columnIndex">
          {{ grid[row][column] }}
        </td>
      </tr>
    </tbody>
  </table>
  `,
  props: ['grid', 'onClickHandler']
})

var app = new Vue({
  el: '#app',
  data: {
    grid: createGrid(columnsInGrid, rowsInGrid),
  },
  methods: {
    put(event) {
      const target = event.target;
      const column = target.getAttribute('column');
      const row = target.getAttribute('row');
      this.grid[row][column] = 1;
    }
  }
})
</code>```

In index.html:

```<code><div id="app">
    <div is="grid-component" v-bind:grid="grid" v-bind:on-click-handler="put"></div>
</div>
</code>```

答:
It doesn't work by design of vue reactivity. Please read https://v2.vuejs.org/v2/guide/list.html#Caveats. There is no technical way to detect changes like grid[index].

Change squared braces the Vue setter like:

```<code>Vue.set(grid[row], column, 1)
</code>```

Body:
Try to render a data into

 and add a event handler to update the data. My initial data is array of arrays. And handler just update these arrays.
Table rendered, handler forks fine and updates arrays, but updates doesn't show on the

. Line {{ grid[row][column] }} doesn't show updated data. Where is my mistake?

Vue.component('grid-component', {
  template: `

          {{ grid[row][column] }}

  `,
  props: ['grid', 'onClickHandler']
})

var app = new Vue({
  el: '#app',
  data: {
    grid: createGrid(columnsInGrid, rowsInGrid),
  },
  methods: {
    put(event) {
      const target = event.target;
      const column = target.getAttribute('column');
      const row = target.getAttribute('row');
      this.grid[row][column] = 1;
    }
  }
})

In index.html:

Body:
It doesn't work by design of vue reactivity. Please read https://v2.vuejs.org/v2/guide/list.html#Caveats. There is no technical way to detect changes like grid[index].

Change squared braces the Vue setter like:

Vue.set(grid[row], column, 1)

ContentLicense: CC BY-SA 4.0


问:
How to put white space after a letter while typing with JavaScript?
I want to put empty spaces after a letter while typing.

We can make it with css letter-spacing property but when we copy this text, i does not keep white spaces.

How can we make it with vanilla javascript?

Added letter-spacing to my css to show what i want exaclty.

JSFIDDLE

var my_text = document.getElementById("my_text");
var output_text = document.getElementById("output_text");

my_text.addEventListener("keyup", function() {
  var val = this.value;
  output_text.innerHTML = val;
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#output_text {
  width: 300px;
  height: 200px;
  border: 1px solid #ccc;
  letter-spacing: 10px;
}</code>```

<textarea id="my_text" cols="30" rows="10"></textarea>

```

答:
Split all the characters and join with a white space: https://jsfiddle.net/wkw72u7e/4/.</p>

```<code>var my_text = document.getElementById("my_text");
var output_text = document.getElementById("output_text");

my_text.addEventListener("keyup", function() {
  output_text.innerHTML = this.value.split('').join(' ');
});

#output_text {
  width: 300px;
  height: 200px;
  border: 1px solid #ccc;
}
</code>```

Body:
I want to put empty spaces after a letter while typing.

We can make it with css letter-spacing property but when we copy this text, i does not keep white spaces.

How can we make it with vanilla javascript?

Added letter-spacing to my css to show what i want exaclty.

JSFIDDLE

var my_text = document.getElementById("my_text");
var output_text = document.getElementById("output_text");

my_text.addEventListener("keyup", function() {
  var val = this.value;
  output_text.innerHTML = val;
});

#output_text {
  width: 300px;
  height: 200px;
  border: 1px solid #ccc;
  letter-spacing: 10px;
}

<textarea id="my_text" cols="30" rows="10"></textarea>

Body:
Split all the characters and join with a white space: https://jsfiddle.net/wkw72u7e/4/.

var my_text = document.getElementById("my_text");
var output_text = document.getElementById("output_text");

my_text.addEventListener("keyup", function() {
  output_text.innerHTML = this.value.split('').join(' ');
});

#output_text {
  width: 300px;
  height: 200px;
  border: 1px solid #ccc;
}


问:
adding to a nested xml element
I have the below code and wondering how to get "sold-product" element and add product to it.</p>

```<code>XDocument xmlDoc = new XDocument();
xmlDoc.Add(new XElement("users"));
var xml = xmlDoc.Root;

foreach (var user in users)
{
    xml.Add(new XElement("user", new XAttribute("first-name", user.FirstName?? ""), new XAttribute("last-name", user.LastName?? ""),
    new XElement("sold-products")));

    foreach (var product in user.Products)
    {
        .Add(new XElement("Product",
            new XElement("name", product.Name),
            new XElement("price", product.Price)));
    }
}
</code>```

答:
You can either do this by keeping a reference to sold-products:

```<code>foreach (var user in users)
{
    var soldProducts = new XElement("sold-products");

    xml.Add(new XElement("user",
        new XAttribute("first-name", user.FirstName?? ""),
        new XAttribute("last-name", user.LastName?? ""),
        soldProducts));

    foreach (var product in user.Products)
    {
        soldProducts.Add(new XElement("Product",
            new XElement("name", product.Name),
            new XElement("price", product.Price)));
    }
}
</code>```

Or by using a more declarative approach, which fits really nicely with LINQ to XML:

```<code>var doc = new XDocument(
    new XElement("users",
        from user in users
        select new XElement("user",
            new XAttribute("first-name", user.FirstName ?? ""),
            new XAttribute("last-name", user.LastName ?? ""),
            new XElement("sold-products",
                from product in user.Products
                select new XElement("Product",
                    new XElement("name", product.Name),
                    new XElement("price", product.Price))))));
</code>```

Title: adding to a nested xml element

Body:
I have the below code and wondering how to get "sold-product" element and add product to it.

XDocument xmlDoc = new XDocument();
xmlDoc.Add(new XElement("users"));
var xml = xmlDoc.Root;

foreach (var user in users)
{
    xml.Add(new XElement("user", new XAttribute("first-name", user.FirstName?? ""), new XAttribute("last-name", user.LastName?? ""),
    new XElement("sold-products")));

    foreach (var product in user.Products)
    {
        .Add(new XElement("Product",
            new XElement("name", product.Name),
            new XElement("price", product.Price)));
    }
}

Body:
You can either do this by keeping a reference to sold-products:

foreach (var user in users)
{
    var soldProducts = new XElement("sold-products");

    xml.Add(new XElement("user",
        new XAttribute("first-name", user.FirstName?? ""),
        new XAttribute("last-name", user.LastName?? ""),
        soldProducts));

    foreach (var product in user.Products)
    {
        soldProducts.Add(new XElement("Product",
            new XElement("name", product.Name),
            new XElement("price", product.Price)));
    }
}

Or by using a more declarative approach, which fits really nicely with LINQ to XML:

var doc = new XDocument(
    new XElement("users",
        from user in users
        select new XElement("user",
            new XAttribute("first-name", user.FirstName ?? ""),
            new XAttribute("last-name", user.LastName ?? ""),
            new XElement("sold-products",
                from product in user.Products
                select new XElement("Product",
                    new XElement("name", product.Name),
                    new XElement("price", product.Price))))));


问:
Can CNNs be faster than classic descriptors?
Disclamer: I don't know almost nothing on CNNs and I have no idea where I could ask this.

My research is focused on high performance on computer vision applications. We generate codes representing an image in less than 20 ms on images with the largest size of 500pxs.

This is done by combining SURF descriptors and VLAD codes, obtaining a vector representing an image that will be used in our object recognition application.

Can CNNs be faster? According to this benchmark (which is based on much smaller images) the times needed is longer, almost double considering that the size of the image is half of ours.

答:
I would be wary of benchmarks and blanket statements.  It's important to know every detail that went into generating the quoted values.  For example, would running CNN on GPU hardware improve the quoted values?

20ms seems very fast to me; so does 40ms.  I have no idea what your requirement is.

What other benefits could CNN offer?  Maybe it's more than just raw speed.

I don't believe that neural networks are the perfect technique for every problem.  Regression, SVM, and other classification techniques are still viable.

There's a bias at work here.  Your question reads as if you are looking only to confirm that your current research is best.  You have a sunk cost that you're loath to throw away, but you're worried that there might be something better out there.  If that's true, I don't think this is a good question for SO.

"I don't know almost nothing on CNNs" - if you're a true researcher, seeking the truth, I think you have an obligation to learn and answer for yourself.  TensorFlow and Keras make this easy to do.


问:
Creating a small struct in C - have some errors
```<code>#include "stdio.h"
#include "stdafx.h"
#define _CRT_SECURE_NO_WARNINGS
#define getch() _getch()

struct Clicker {
    int toggle;
    int average;
};

int main()
{
    struct Clicker *clicker;
    printf("Enter your toggle key: ");
    (*clicker).toggle = _getch();
    printf("Enter your average cps: ");
    scanf_s("%d", (*clicker).average);
    printf("\nCurrent settings: \nToggle: %i \nAverage:%i\n", clicker->toggle, clicker->average);
    getchar();
    return 1;
}
</code>```

There is the code.
Errors:

'_getch' undefined, assuming extern returning int
'scanf_s' format string '%d' requires an argument of type 'int *' but variadic arguemnt 1 has type int.
uninitialized local variable 'clicker' used.
```

What am I doing wrong?

答:
It seems like you have created this code by copying different solutions and snippets without a real understanding of its usage.

There might be reasons to use _getch() but if you don't now why you should probably use more standard solutions like getchar().

Please consider the following solution using standard methods:

```<code>#include <stdio.h>    // use <...> instead of "..."
#include <stdlib.h>    // for malloc()
// #include "stdafx.h"     // not necessary
// #define _CRT_SECURE_NO_WARNINGS // not necessary
// #define getch() _getch()    // not necessary

struct Clicker {
    int toggle;
    int average;
};

int main(){
    struct Clicker *clicker = malloc(sizeof(struct Clicker));
    printf("Enter your toggle key: ");
    // (*clicker).toggle = _getch();   // use scanf()
    scanf("%d",&clicker->toggle);
    printf("Enter your average cps: ");
    scanf("%d", &clicker->average);
    printf("\nCurrent settings: \nToggle: %i \nAverage:%i\n",clicker->toggle, clicker->average);
    // getchar();  // not nessecary
    // return 1;   // 1 is usually an error exit code, use 0 instead
    return 0;
}
</code>```

Another thing you don't seem to understand yet is the proper usage of scanf(). It receives a pointer (to an int in this case). Since you declared clicker as a pointer to your struct Clicker you need do dereference if to get access to its members toggle and average. You do this using clicker->toggle. Then you need a pointer to this dereferenceation which you get using &.

Body:
#include "stdio.h"
#include "stdafx.h"
#define _CRT_SECURE_NO_WARNINGS
#define getch() _getch()

struct Clicker {
    int toggle;
    int average;
};

int main()
{
    struct Clicker *clicker;
    printf("Enter your toggle key: ");
    (*clicker).toggle = _getch();
    printf("Enter your average cps: ");
    scanf_s("%d", (*clicker).average);
    printf("\nCurrent settings: \nToggle: %i \nAverage:%i\n", clicker->toggle, clicker->average);
    getchar();
    return 1;
}

There is the code.
Errors:

'_getch' undefined, assuming extern returning int
'scanf_s' format string '%d' requires an argument of type 'int *' but variadic arguemnt 1 has type int.
uninitialized local variable 'clicker' used.

What am I doing wrong?

Body:
It seems like you have created this code by copying different solutions and snippets without a real understanding of its usage.

There might be reasons to use _getch() but if you don't now why you should probably use more standard solutions like getchar().

Please consider the following solution using standard methods:

#include <stdio.h>    // use <...> instead of "..."
#include <stdlib.h>    // for malloc()
// #include "stdafx.h"     // not necessary
// #define _CRT_SECURE_NO_WARNINGS // not necessary
// #define getch() _getch()    // not necessary

struct Clicker {
    int toggle;
    int average;
};

int main(){
    struct Clicker *clicker = malloc(sizeof(struct Clicker));
    printf("Enter your toggle key: ");
    // (*clicker).toggle = _getch();   // use scanf()
    scanf("%d",&clicker->toggle);
    printf("Enter your average cps: ");
    scanf("%d", &clicker->average);
    printf("\nCurrent settings: \nToggle: %i \nAverage:%i\n",clicker->toggle, clicker->average);
    // getchar();  // not nessecary
    // return 1;   // 1 is usually an error exit code, use 0 instead
    return 0;
}

Another thing you don't seem to understand yet is the proper usage of scanf(). It receives a pointer (to an int in this case). Since you declared clicker as a pointer to your struct Clicker you need do dereference if to get access to its members toggle and average. You do this using clicker->toggle. Then you need a pointer to this dereferenceation which you get using &.


问:
Confusion between thread index with CUDA
lets consider the following statements

```<code>unsigned int tid = threadIdx.x;
data[tid]= data [tid] + data[tid+1];
</code>```

suppose tid =0 so :

```<code>data[0]=data[0]+data[1]
</code>```

My question is in the previous statement we have 2 threads ( thread 0 and thread 1) ? or just one?

答:
As stated by Robert Crovella, the code you show is what each thread executes.

ThreadIdx.x is a read only register which each thread can read to get its own index. It's a equivalent of c#´s:

Environment.CurrentThread.ManagedThreadId.

The amount of thread you have is determined by the way you launch the kernel (the triple bracket thing)

In you case, if you launch you kernel with 1 block of two threads:

```<code>My kernel<<<1,2>>>(data)
</code>```

You will have thread 0 executing

```<code>Data[0] += data[1]
</code>```

While thread 1 executes

```<code>Data[1] += data[2]
</code>```

Which created a race condition

Body:
lets consider the following statements

unsigned int tid = threadIdx.x;
data[tid]= data [tid] + data[tid+1];

suppose tid =0 so :

data[0]=data[0]+data[1]

My question is in the previous statement we have 2 threads ( thread 0 and thread 1) ? or just one?

Body:
As stated by Robert Crovella, the code you show is what each thread executes.

ThreadIdx.x is a read only register which each thread can read to get its own index. It's a equivalent of c#´s:

Environment.CurrentThread.ManagedThreadId.

The amount of thread you have is determined by the way you launch the kernel (the triple bracket thing)

In you case, if you launch you kernel with 1 block of two threads:

My kernel<<<1,2>>>(data)

You will have thread 0 executing

Data[0] += data[1]

While thread 1 executes

Data[1] += data[2]

Which created a race condition


问:
Comparing function of binary_search
I am trying to run binary_search on vector of custom objects.

```<code>struct T{
    string name;
    T(string n):name(n){};
    bool operator < (   T * n  ) const {
        return name < n ->  name;
    }
    bool operator == ( T * n ) const {
      return name == n -> name;
    }
};

    vector<T *> t;
    t.push_back(new T("one"));
    t.push_back(new T("two"));
    t.push_back(new T("three"));

bool has_3 = binary_search( t.begin(), t.end(), new T("two") ) ;
    if( has_3 ){
        cout <<"Its there" << endl;
    }
</code>```

The comparation function should be just fine yet when i run the code has_3 equals to 0 = the element isnt present in vector. Is this problem caused by my overloading of < ? I see no reason why this shouldnt find the value. Considering the order of insertion into vector it should be sorted

Thanks for help.

答:
It's a really dumb requirement to work with a vector of pointers to dynamically allocated objects.  But here is an approach that will work.

```<code>#include <iostream>
#include <string>
#include <algorithm>

struct T
{
    std::string name;
    T(std::string n):name(n){};
};

// this is the comparater needed to work with pointers, but it should
//    NOT be a member of T

bool pointer_comparer(const T *left, const T *right)
{
   // this assumes both left and right point to valid objects

    return left->name < right->name;
}

int main()
{
    std::vector<T *> t;
    t.push_back(new T("one"));
    t.push_back(new T("two"));
    t.push_back(new T("three"));

    //   t is unsorted.  We need to sort it since binary_search will
    //      ASSUME it is sorted

    std::sort(t.begin(), t.end(), pointer_comparer);

    T *value_needed = new T("two");
    bool has_3 = std::binary_search( t.begin(), t.end(), value_needed, pointer_comparer);
    if(has_3)
    {
        std::cout <<"Its there" << std::endl;
    }

    //   since we've been stupidly allocating objects, we need to release them

    delete value_needed;
    for (std::vector<T *>::iterator i = t.begin(), end = t.end();
         i != end;  ++i)
    {
         delete (*i);
    }

    //   and since t now contains a set of dangling pointers, we need to discard them too

    t.resize(0);
    return 0;
}
</code>```

Why do I say the requirement to work with a vector of pointers to dynamically allocated objects.   Compare the above with an approach that works with a vector<T> rather than a vector<T *>.

```<code>#include <iostream>
#include <string>
#include <algorithm>

struct T
{
    std::string name;
    T(std::string n):name(n){};
    bool operator < (const T &) const
    {
        return name < n.name;
    };
};

int main()
{
    std::vector<T> t;
    t.push_back(T("one"));
    t.push_back(T("two"));
    t.push_back(T("three"));

    //   t is unsorted.  We need to sort it since binary_search will
    //      ASSUME it is sorted

    std::sort(t.begin(), t.end());
    bool has_3 = std::binary_search(t.begin(), t.end(), T("two"));
    if(has_3)
    {
        std::cout <<"Its there" << std::endl;
    }

    //  we need do nothing here.  All objects use above will be properly released

    return 0;
}
</code>```

Note:  I've written the above so it works with ALL C++ standards.  Assuming C++11 and later, simplifications are possible in both cases.

Title: Comparing function of binary_search

Body:
I am trying to run binary_search on vector of custom objects.

struct T{
    string name;
    T(string n):name(n){};
    bool operator < (   T * n  ) const {
        return name < n ->  name;
    }
    bool operator == ( T * n ) const {
      return name == n -> name;
    }
};

    vector<T *> t;
    t.push_back(new T("one"));
    t.push_back(new T("two"));
    t.push_back(new T("three"));

bool has_3 = binary_search( t.begin(), t.end(), new T("two") ) ;
    if( has_3 ){
        cout <<"Its there" << endl;
    }

The comparation function should be just fine yet when i run the code has_3 equals to 0 = the element isnt present in vector. Is this problem caused by my overloading of < ? I see no reason why this shouldnt find the value. Considering the order of insertion into vector it should be sorted

Thanks for help.

Body:
It's a really dumb requirement to work with a vector of pointers to dynamically allocated objects.  But here is an approach that will work.

#include <iostream>
#include <string>
#include <algorithm>

struct T
{
    std::string name;
    T(std::string n):name(n){};
};

// this is the comparater needed to work with pointers, but it should
//    NOT be a member of T

bool pointer_comparer(const T *left, const T *right)
{
   // this assumes both left and right point to valid objects

    return left->name < right->name;
}

int main()
{
    std::vector<T *> t;
    t.push_back(new T("one"));
    t.push_back(new T("two"));
    t.push_back(new T("three"));

    //   t is unsorted.  We need to sort it since binary_search will
    //      ASSUME it is sorted

    std::sort(t.begin(), t.end(), pointer_comparer);

    T *value_needed = new T("two");
    bool has_3 = std::binary_search( t.begin(), t.end(), value_needed, pointer_comparer);
    if(has_3)
    {
        std::cout <<"Its there" << std::endl;
    }

    //   since we've been stupidly allocating objects, we need to release them

    delete value_needed;
    for (std::vector<T *>::iterator i = t.begin(), end = t.end();
         i != end;  ++i)
    {
         delete (*i);
    }

    //   and since t now contains a set of dangling pointers, we need to discard them too

    t.resize(0);
    return 0;
}

Why do I say the requirement to work with a vector of pointers to dynamically allocated objects.   Compare the above with an approach that works with a vector<T> rather than a vector<T *>.

#include <iostream>
#include <string>
#include <algorithm>

struct T
{
    std::string name;
    T(std::string n):name(n){};
    bool operator < (const T &) const
    {
        return name < n.name;
    };
};

int main()
{
    std::vector<T> t;
    t.push_back(T("one"));
    t.push_back(T("two"));
    t.push_back(T("three"));

    //   t is unsorted.  We need to sort it since binary_search will
    //      ASSUME it is sorted

    std::sort(t.begin(), t.end());
    bool has_3 = std::binary_search(t.begin(), t.end(), T("two"));
    if(has_3)
    {
        std::cout <<"Its there" << std::endl;
    }

    //  we need do nothing here.  All objects use above will be properly released

    return 0;
}

Note:  I've written the above so it works with ALL C++ standards.  Assuming C++11 and later, simplifications are possible in both cases.


问:
Importing Apache Math Classes in Eclipse ( OSX )
I have downloaded the Apache Commons Math Package from their website, and extracted the .jar files.  Specifically, I took commons-math3-3.6.1.jar, and added it to my /Libraries/Java/Extensions directory ( on OSX ).

I then added this .jar file as an External Jar in my Eclipse Project's Build Path.

What I would like to do is use the WeightedObservedPoints class. But when I write the following line:

```<code>import org.apache.commons.math3.fitting.WeightedObservedPoints;
</code>```

I see the following error:

Access restriction: The type 'WeightedObservedPoints' is not API (restriction on required library '/Library/Java/Extensions/commons-math3-3.6.1.jar')

Does anybody know how I might solve this problem?  It doesn't make sense that this class would not be in the public API.  Am I missing a .jar file to add?  There were several in the original package, but they all seemed like documentation and other optional features like testing.

Thank you for any advice.

答:
Thanks to Ivan, I did find the answer inside his link.  The steps to fix it for me were:

Edit the JRE System Library on the Build Path option from the Project Properties.

Change the "System Library" option to "Use Alternate JRE", but to leave it with the default choice ( which is the same as what was set for Execution Environment )

The error is gone.  Definitely don't know why this works though.

Body:
I have downloaded the Apache Commons Math Package from their website, and extracted the .jar files.  Specifically, I took commons-math3-3.6.1.jar, and added it to my /Libraries/Java/Extensions directory ( on OSX ).

I then added this .jar file as an External Jar in my Eclipse Project's Build Path.

What I would like to do is use the WeightedObservedPoints class. But when I write the following line:

import org.apache.commons.math3.fitting.WeightedObservedPoints;

I see the following error:

Access restriction: The type 'WeightedObservedPoints' is not API (restriction on required library '/Library/Java/Extensions/commons-math3-3.6.1.jar')

Does anybody know how I might solve this problem?  It doesn't make sense that this class would not be in the public API.  Am I missing a .jar file to add?  There were several in the original package, but they all seemed like documentation and other optional features like testing.

Thank you for any advice.


问:
CakePHP 3: Accessing current user in model
Since i'm new to CakePHP, I have simple problems I cannot figure out.

I use CakePHP 3.4. I try to write a simple logger functionality. Every change applied to a record, I want to be logged to the ChangeLog model.

Using afterSave() event, I have following code:

```<code>public function afterSave($event, $entity, $options) {
  $logTable = TableRegistry::get('ChangeLogs');
  foreach ($entity->getDirty() as $key) {
    if($key != 'modified') {
      $record = $logTable->newEntity();
      $record->previous_value = $entity->getOriginal($key);
      $record->new_value = $entity[$key];
      $record->table_name = 'Stars';
      $record->column_name = $key;
      $record->row_id = $entity->id;
      $record->user_id = [what should i put here?]
      $record->user_id = $_SESSION['Auth']['user']['id'];
      $logTable->save($record);
    }
  }
</code>```

It works well, but I also want to know which user performed operation and I don't know how can I obtain current user in the Model.

I try to avoid passing argument in controller, because I want user to be detected automaticly, and as a developer I don't want to remember about it every time I try change/add new functionalities in controller.

答:
Do not fiddle with superglobals directly in CakePHP, this will surely bite you at some point, especially in the test environment! Always use the abstracted methods (like the session object) to access such data!

That being said, you could use events to inject the current user into the model callback/event flow. For example register globally to Model.afterSave, and pass the current user into the options.

Here's a basic example to demonstrate the principle. Imagine somthing like this in your app controller:

```<code>use Cake\Datasource\EntityInterface;
use Cake\Event\Event;
use Cake\Event\EventManager;

// ...

public function initialize()
{
    parent::initialize();

    // ...

    EventManager::instance()->on(
        'Model.afterSave',
        ['priority' => -1],
        function (Event $event, EntityInterface $entity, \ArrayObject $options) {
            // retrieve the user id from the auth component
            $options['user_id'] = $this->Auth->user('id');
        }
    );
}
</code>```

Given the priority of -1 (the default priority is 10) it will be invoked before the model callback for that event, so that in your table class you'll have access to user_id via the $options argument.

```<code>$record->user_id = $options['user_id'];
</code>```

For something more reusable you'd probably use a custom listener class. Also check out events like Auth.afterIdentify, Model.initialize, and Controller.intialize/startup, these could be leaveraged to register your model events listener and to retrieve the current user.

See also

Awesome CakePHP > Auditing / Logging

Cookbook > Events System

Cookbook > Events System > Registering Listeners

Cookbook > Events System > Establishing Priorities

Cookbook > Database Access & ORM > Table Objects > Lifecycle Callbacks

Cookbook > Controllers > Request Life-cycle Callbacks

Body:
Since i'm new to CakePHP, I have simple problems I cannot figure out.

I use CakePHP 3.4. I try to write a simple logger functionality. Every change applied to a record, I want to be logged to the ChangeLog model.

Using afterSave() event, I have following code:

public function afterSave($event, $entity, $options) {
  $logTable = TableRegistry::get('ChangeLogs');
  foreach ($entity->getDirty() as $key) {
    if($key != 'modified') {
      $record = $logTable->newEntity();
      $record->previous_value = $entity->getOriginal($key);
      $record->new_value = $entity[$key];
      $record->table_name = 'Stars';
      $record->column_name = $key;
      $record->row_id = $entity->id;
      $record->user_id = [what should i put here?]
      $record->user_id = $_SESSION['Auth']['user']['id'];
      $logTable->save($record);
    }
  }

It works well, but I also want to know which user performed operation and I don't know how can I obtain current user in the Model.

I try to avoid passing argument in controller, because I want user to be detected automaticly, and as a developer I don't want to remember about it every time I try change/add new functionalities in controller.

Body:
Do not fiddle with superglobals directly in CakePHP, this will surely bite you at some point, especially in the test environment! Always use the abstracted methods (like the session object) to access such data!

That being said, you could use events to inject the current user into the model callback/event flow. For example register globally to Model.afterSave, and pass the current user into the options.

Here's a basic example to demonstrate the principle. Imagine somthing like this in your app controller:

use Cake\Datasource\EntityInterface;
use Cake\Event\Event;
use Cake\Event\EventManager;

// ...

public function initialize()
{
    parent::initialize();

    // ...

    EventManager::instance()->on(
        'Model.afterSave',
        ['priority' => -1],
        function (Event $event, EntityInterface $entity, \ArrayObject $options) {
            // retrieve the user id from the auth component
            $options['user_id'] = $this->Auth->user('id');
        }
    );
}

Given the priority of -1 (the default priority is 10) it will be invoked before the model callback for that event, so that in your table class you'll have access to user_id via the $options argument.

$record->user_id = $options['user_id'];

For something more reusable you'd probably use a custom listener class. Also check out events like Auth.afterIdentify, Model.initialize, and Controller.intialize/startup, these could be leaveraged to register your model events listener and to retrieve the current user.

See also

Awesome CakePHP > Auditing / Logging

Cookbook > Events System

Cookbook > Events System > Registering Listeners

Cookbook > Events System > Establishing Priorities

Cookbook > Database Access & ORM > Table Objects > Lifecycle Callbacks

Cookbook > Controllers > Request Life-cycle Callbacks


问:
Change the menu on click of button
I am trying to change the listing of Menu items from :

menu 1 menu 2

to

menu 3 menu 4

by clicking a button.

There are 2 buttons Div 1 and Div 2.

I click on Div 1 which appears when menu 1 and menu 2 are showing.

Clicking on Div 1 changes the menu 1 menu 2 ==> menu 3 menu 4 and brings Div 2 button.

But clicking on Div 2 does not take me back to menu 1 and menu 2.

The fiddle used is as follows : http://jsfiddle.net/SO_AMK/BcFVv/1/ .

```<code><div id="buttons">
 <a href="#" id="2" class="mybutton myred" >Div 2</a>
 <a href="#" id="1" class="mybutton myblue">Div 1</a>
</div>

<div id="pages">
  <div id="1" class="mydivshow">
    <a href=".menu1page">Menu1</a>
  </div>
  <div id="1" class="mydivshow">
    <a href=".menu2page">Menu2</a>
  </div>
  <div id="1" class="mydivshow">
    <a href=".menu3page">Menu3</a>
  </div>
  <div id="2" class="mydivhide">
    <a href=".menu1page">Home</a>
  </div>
  <div id="2" class="mydivhide">
    <a href=".menu2page">About</a>
  </div>
  <div id="2" class="mydivhide">
    <a href=".menu2page">Contact</a>
  </div>
</div>
</code>```

JS code:-

```<code>$("#buttons a").click(function() {
  var id = $(this).attr("id");
  $("#pages div").css("display", "none");
  $("#pages div#" + id + "").css("display", "block");
  $("#buttons a").css("display", "none");
  $("#buttons a#" + id + "").css("display", "block");
});
$("#pages div:not(#1)").css("display", "none");
$("#buttons a:not(#2)").css("display", "none");
</code>```

This does not change back to Menu 1 and Menu 2. Please advise.

答:
You can't use multiple times the same id.

But you can use mutilple times a class.

$("#buttons a").click(function() {
  var id = $(this).attr("id");
  $("#pages div").css("display", "none");
  $("#pages div." + id + "").css("display", "block");
  $("#buttons a").css("display", "none");
  $("#buttons a:not(#" + id + ")").css("display", "block");
});
$("#pages div:not(.1)").css("display", "none");
$("#buttons a:not(#2)").css("display", "none");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="buttons">
 Div 2
 Div 1
</div>

<div id="pages">
  <div class="1 mydivshow">
    Menu1
  </div>
  <div class="1 mydivshow">
    Menu2
  </div>
  <div class="1 mydivshow">
    Menu3
  </div>
  <div class="2 mydivhide">
    Home
  </div>
  <div class="2 mydivhide">
    About
  </div>
  <div class="2 mydivhide">
    Contact
  </div>
</div></code>```

Title: Change the menu on click of button

Body:
I am trying to change the listing of Menu items from :

menu 1 menu 2

to

menu 3 menu 4

by clicking a button.

There are 2 buttons Div 1 and Div 2.

I click on Div 1 which appears when menu 1 and menu 2 are showing.

Clicking on Div 1 changes the menu 1 menu 2 ==> menu 3 menu 4 and brings Div 2 button.

But clicking on Div 2 does not take me back to menu 1 and menu 2.

The fiddle used is as follows : http://jsfiddle.net/SO_AMK/BcFVv/1/ .

 Div 2
 Div 1

    Menu1

    Menu2

    Menu3

    Home

    About

    Contact

JS code:-

$("#buttons a").click(function() {
  var id = $(this).attr("id");
  $("#pages div").css("display", "none");
  $("#pages div#" + id + "").css("display", "block");
  $("#buttons a").css("display", "none");
  $("#buttons a#" + id + "").css("display", "block");
});
$("#pages div:not(#1)").css("display", "none");
$("#buttons a:not(#2)").css("display", "none");

This does not change back to Menu 1 and Menu 2. Please advise.

Body:
You can't use multiple times the same id.

But you can use mutilple times a class.

$("#buttons a").click(function() {
  var id = $(this).attr("id");
  $("#pages div").css("display", "none");
  $("#pages div." + id + "").css("display", "block");
  $("#buttons a").css("display", "none");
  $("#buttons a:not(#" + id + ")").css("display", "block");
});
$("#pages div:not(.1)").css("display", "none");
$("#buttons a:not(#2)").css("display", "none");

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="buttons">
 <a href="#" id="2" class="mybutton myred" >Div 2</a>
 <a href="#" id="1" class="mybutton myblue">Div 1</a>
</div>

<div id="pages">
  <div class="1 mydivshow">
    <a href=".menu1page">Menu1</a>
  </div>
  <div class="1 mydivshow">
    <a href=".menu2page">Menu2</a>
  </div>
  <div class="1 mydivshow">
    <a href=".menu3page">Menu3</a>
  </div>
  <div class="2 mydivhide">
    <a href=".menu1page">Home</a>
  </div>
  <div class="2 mydivhide">
    <a href=".menu2page">About</a>
  </div>
  <div class="2 mydivhide">
    <a href=".menu3page">Contact</a>
  </div>
</div>


问:
Game crashes upon logging into Google Play Games services
I am creating a 2d game in unity and I have ran into a problem. I have created a developer account for google play and published my game to google play as closed alpha. I am now adding google play games services to the game and I downloaded the latest library from:(https://github.com/playgameservices/play-games-plugin-for-unity) and imported it into Unity. I have set everything up but the Game crashes upon attempting to login.

```<code>using UnityEngine;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using UnityEngine.SocialPlatforms;
using System.Collections;

public class gpgTest : MonoBehaviour {
    void Start () {
        PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder()
        // enables saving game progress.
        .EnableSavedGames()
        // require access to a player's Google+ social graph (usually not needed)
        .RequireGooglePlus()
        .Build();
    PlayGamesPlatform.InitializeInstance(config);
    // recommended for debugging:
    PlayGamesPlatform.DebugLogEnabled = true;
    // Activate the Google Play Games platform
    PlayGamesPlatform.Activate();
}

void Update () {
}

public void LogIn()
{
    Debug.Log("button");
    // authenticate user:
    Social.localUser.Authenticate((bool success) => {
        // handle success or failure
    });
}
}
</code>```

note: I have tried almost all versions of the library and different versions of Unity 5.0 and up.

I also get these messages:

And I did install all the necesary packages in the sdk manager.

答:
OK so for all of those struggling like me the answer is in removing all files with version 10.2.1 in \Assets\Plugins\Android\ and replacing them with ones of version 10.0.1.

Source: https://github.com/playgameservices/play-games-plugin-for-unity/issues/1604

In short: the play games plugin is not compatible with newer libraries.

Another related thread:http://answers.unity3d.com/questions/1324988/android-game-crashes-on-startup-becaus-of-google-p.html

Edit: only Unity version 5.0 - 5.5 is supported (for now)

Body:
I am creating a 2d game in unity and I have ran into a problem. I have created a developer account for google play and published my game to google play as closed alpha. I am now adding google play games services to the game and I downloaded the latest library from:(https://github.com/playgameservices/play-games-plugin-for-unity) and imported it into Unity. I have set everything up but the Game crashes upon attempting to login.

using UnityEngine;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using UnityEngine.SocialPlatforms;
using System.Collections;

public class gpgTest : MonoBehaviour {
    void Start () {
        PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder()
        // enables saving game progress.
        .EnableSavedGames()
        // require access to a player's Google+ social graph (usually not needed)
        .RequireGooglePlus()
        .Build();
    PlayGamesPlatform.InitializeInstance(config);
    // recommended for debugging:
    PlayGamesPlatform.DebugLogEnabled = true;
    // Activate the Google Play Games platform
    PlayGamesPlatform.Activate();
}

void Update () {
}

public void LogIn()
{
    Debug.Log("button");
    // authenticate user:
    Social.localUser.Authenticate((bool success) => {
        // handle success or failure
    });
}
}

note: I have tried almost all versions of the library and different versions of Unity 5.0 and up.

I also get these messages:

And I did install all the necesary packages in the sdk manager.


问:
How do I "Hide()" a Modal WPF Window without it closing?
I have a WPF window that is run on a background thread as a sort of "notifier window"... when an event is raised, it displays a message... a user clicks the "Snooze" button and I call this.Visibility = Visibility.Collapsed

The very moment that I hide the window (either by calling this.Hide() or setting the Visibility as mentioned above)... the "ShowDialog()" code releases the window and closes it.

This is absolutely a bug in the WPF code (which I've identified via reflector)... but my question remains. Has anyone been able to come up with a work-around for this issue?

I've tried many things and am now reaching out to ya'll smart people :)

答:
You can't hide a modal dialog. That's like asking, "How do I get to 100mph in reverse?" You don't, you drive the car forwards.

Use Show, not ShowDialog. Alternately you can simply re-ShowDialog when it needs to become visible again.


问:
SSE echo from PHP duplicating at random intervals
I'm trying to set up a PHP server send event, which works okay. But at random intervals it is pushing the same data repeatedly.

Here's a quick scenario to clarify what I'm describing: Let's say I insert a db record at 1:00:00. The record's data is pushed as it should. However, at 1:03:00 that record's data is pushed a second time. Then at 1:03:17, it is pushed again. And I now have 3 instances of the record displayed.

Why is this happening, and why at random intervals?

I increased php execution time, but the issue is still occurring.

In the browser console, I'm getting this error: net::ERR_INCOMPLETE_CHUNKED_ENCODING.

I have this for client side:

```<code>  <script>
    var source = new EventSource('pdo_updates.php');
    var pdo_updates;
    source.onmessage = function(e) {
        pdo_updates = e.lastEventId + '' + e.data + '<br>';
        document.getElementById("videoID").innerHTML += pdo_updates;
    };
    evtSource.close();
  </script>
</code>```

And this for server side:

```<code>header('Content-Type: text/event-stream');
header('Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0');
function send_msg($id, $msg) {
    echo "data: $msg" . PHP_EOL;
    echo PHP_EOL;
    ob_flush();
    flush();
}
    $last_event_id = floatval(isset($_SERVER["HTTP_LAST_EVENT_ID"]) ? $_SERVER["HTTP_LAST_EVENT_ID"] : False);
    if ($last_event_id == 0) {
        $last_event_id = floatval(isset($_GET["lastEventId"]) ? $_GET["lastEventId"] : False);
    }

    $last_id = 0;
    try {
        $conn = new PDO('mysql:host=localhost;dbname=my_db', $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        while(1) {
            $id  = $last_event_id != False ? $last_event_id : $last_id;
            $stmt = $conn->prepare("SELECT id, message FROM messages WHERE id > :id ORDER BY id DESC LIMIT 1");
            $result = $stmt->execute(array('id' => $id));
            $stmt->bindValue('id', $id);

            if ($result) {
                while($data = $stmt->fetch(PDO::FETCH_ASSOC)) {
                    if ($data) {
                        send_msg($data['id'], $data['message']);
                        $last_id = $data['id'];
                    }
                }
            }
            sleep(1);
        }
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }
</code>```

答:
So, after trying just about every keepalive related header, and every apache timeout adjustment config, I ended up running a packet capture. I discovered there was a TCP reset was being triggered by the remote end. I have my site behind Cloudflare, and once I disabled Cloudflare the issue partially disappeared. The TCP session was being refreshed every 100 seconds and would cause the last message to appear again when that happened. This was responsible for the browser console error: net::ERR_INCOMPLETE_CHUNKED_ENCODING

At the same time, however, there was an issue in my submit code. But I'm not 100% sure why.

```<code>$.ajax({
       type: "POST",
       url: url,
       data: $("#submitmessage").serialize(), // serializes the form's elements.
       success: function(data)
       {
</code>```

```<code>         $("#myvideo").val("");
</code>```

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

I needed to clear the value in my input field after submit. I haven't had any duplicates since.

Body:
I'm trying to set up a PHP server send event, which works okay. But at random intervals it is pushing the same data repeatedly.

Here's a quick scenario to clarify what I'm describing: Let's say I insert a db record at 1:00:00. The record's data is pushed as it should. However, at 1:03:00 that record's data is pushed a second time. Then at 1:03:17, it is pushed again. And I now have 3 instances of the record displayed.

Why is this happening, and why at random intervals?

I increased php execution time, but the issue is still occurring.

In the browser console, I'm getting this error: net::ERR_INCOMPLETE_CHUNKED_ENCODING.

I have this for client side:

And this for server side:

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0');
function send_msg($id, $msg) {
    echo "data: $msg" . PHP_EOL;
    echo PHP_EOL;
    ob_flush();
    flush();
}
    $last_event_id = floatval(isset($_SERVER["HTTP_LAST_EVENT_ID"]) ? $_SERVER["HTTP_LAST_EVENT_ID"] : False);
    if ($last_event_id == 0) {
        $last_event_id = floatval(isset($_GET["lastEventId"]) ? $_GET["lastEventId"] : False);
    }

    $last_id = 0;
    try {
        $conn = new PDO('mysql:host=localhost;dbname=my_db', $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        while(1) {
            $id  = $last_event_id != False ? $last_event_id : $last_id;
            $stmt = $conn->prepare("SELECT id, message FROM messages WHERE id > :id ORDER BY id DESC LIMIT 1");
            $result = $stmt->execute(array('id' => $id));
            $stmt->bindValue('id', $id);

            if ($result) {
                while($data = $stmt->fetch(PDO::FETCH_ASSOC)) {
                    if ($data) {
                        send_msg($data['id'], $data['message']);
                        $last_id = $data['id'];
                    }
                }
            }
            sleep(1);
        }
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }

Body:
So, after trying just about every keepalive related header, and every apache timeout adjustment config, I ended up running a packet capture. I discovered there was a TCP reset was being triggered by the remote end. I have my site behind Cloudflare, and once I disabled Cloudflare the issue partially disappeared. The TCP session was being refreshed every 100 seconds and would cause the last message to appear again when that happened. This was responsible for the browser console error: net::ERR_INCOMPLETE_CHUNKED_ENCODING

At the same time, however, there was an issue in my submit code. But I'm not 100% sure why.

$.ajax({
       type: "POST",
       url: url,
       data: $("#submitmessage").serialize(), // serializes the form's elements.
       success: function(data)
       {

         $("#myvideo").val("");

       }
     });

I needed to clear the value in my input field after submit. I haven't had any duplicates since.


答:
And why vanilla javascript? Ordinary javascript can do it:

var my_text = document.getElementById("my_text");
var output_text = document.getElementById("output_text");

my_text.addEventListener("keypress", function(event) {
  event.preventDefault();
  output_text.innerHTML += " " + String.fromCharCode(event.keyCode);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#output_text {
  width: 300px;
  height: 200px;
  border: 1px solid #ccc;
}</code>```

<textarea id="my_text" cols="30" rows="10"></textarea>

```

Title: How to put white space after a letter while typing with JavaScript?

Body:
I want to put empty spaces after a letter while typing.

We can make it with css letter-spacing property but when we copy this text, i does not keep white spaces.

How can we make it with vanilla javascript?

Added letter-spacing to my css to show what i want exaclty.

JSFIDDLE

var my_text = document.getElementById("my_text");
var output_text = document.getElementById("output_text");

my_text.addEventListener("keyup", function() {
  var val = this.value;
  output_text.innerHTML = val;
});

#output_text {
  width: 300px;
  height: 200px;
  border: 1px solid #ccc;
  letter-spacing: 10px;
}

<textarea id="my_text" cols="30" rows="10"></textarea>

Body:
And why vanilla javascript? Ordinary javascript can do it:

var my_text = document.getElementById("my_text");
var output_text = document.getElementById("output_text");

my_text.addEventListener("keypress", function(event) {
  event.preventDefault();
  output_text.innerHTML += " " + String.fromCharCode(event.keyCode);
});

#output_text {
  width: 300px;
  height: 200px;
  border: 1px solid #ccc;
}

<textarea id="my_text" cols="30" rows="10"></textarea>
<div id="output_text"></div>


问:
How to make automatic grader with Python3
I'm a beginner for coding.
I'm struggling to make student grader which each student names would be corresponded to each grade averages and show total average score among students.
This is my code :

```<code>Ken = [5,8,9]
Hiro = [10,11,20]
Nick = [20,20,20]

list1 = [Ken,Hiro,Nick]

total_average = 0
for j in list1:
   x = 0
   count = 0
   for i in j:
       x += i
       count += 1

   average = x / count
   print (round(average,2))
   total_average += average

final_average = total_average / len(list1)
print (round(final_average,2))
</code>```

and result is :

```<code>7.33
13.67
20.0
13.67
</code>```

However, I actually want to make code which returns like :

```<code>13.67, {'Ken': 13.67, 'Hiro': 20.0, 'Nick': 13.67}
</code>```

How could I express like this ?

It would be greatly appreciated if you could explain the details !!

答:
Try using dictionary instead of lists.
Initialize the dictionary:
students = {'Hiro': 0, 'Ken': 0, 'Nick': 0}

Then assign values based on the computed average:
students = {'Hiro': 20.0, 'Ken': 13.67, 'Nick': 13.67}

print(students)

Body:
I'm a beginner for coding.
I'm struggling to make student grader which each student names would be corresponded to each grade averages and show total average score among students.
This is my code :

Ken = [5,8,9]
Hiro = [10,11,20]
Nick = [20,20,20]

list1 = [Ken,Hiro,Nick]

total_average = 0
for j in list1:
   x = 0
   count = 0
   for i in j:
       x += i
       count += 1

   average = x / count
   print (round(average,2))
   total_average += average

final_average = total_average / len(list1)
print (round(final_average,2))

and result is :

7.33
13.67
20.0
13.67

However, I actually want to make code which returns like :

13.67, {'Ken': 13.67, 'Hiro': 20.0, 'Nick': 13.67}

How could I express like this ?

It would be greatly appreciated if you could explain the details !!


问:
Why doesn't my counter count?
This really suprised me. One of the simplest things doesn't work, making a counter. I'm making a kinda game application in c# and there is also a timer who counts the time. Very simple right? I know how to code this and this is something I did before but I don't understand why it isn't working now.

```<code>int i = 0;
i++;
label1.Text = i.ToString();
</code>```

label1.Text turns in to 1 and nothing else happens. Also tryied this with a timer but it freeezes in 1. I know this post isn't really going to help other people but it is very frustrating.

答:
Why you are always getting 1 in your label1 text?

The reason is very simple, each time you are getting to the first line, i is 0:

```<code>// Line 1
int i = 0;  // declaring and setting i to 0
// Line 2
i++;        // incrementing i to 1
// Line 3
label1.Text = i.ToString();  // displaying i (which is equal to 1)
</code>```

and then again you are getting to the Line 1 and setting i=0, etc...

I presume you have a UI application (win form, web form etc...)
You already mentioned you have a timer that works fine and a label where you output the incremented i variable.

As already commented in order to see a change in your label you can use a loop as following:

```<code>int length = 100;  // for example
for (int i = 0; i < length; i++)
{
    label1.Text = i.ToString();
}
</code>```

The output in label1 text will be 0, then 1, then 2 .... and finally 99.
Obviously you won't be able to see all those values except the last one 99 at run-time but you can debug and see how it works.

I presume, what you needed is to have your label text changing each time the timer will tick.
Following a code example how you could implement it:

```<code>private int i = 0; // initialized once in this UI class

private void timer1_Tick(object sender, EventArgs e)
{
    label1.Text = i.ToString();
    i++; // will increment by one each time the timer is ticking
}
</code>```

Set your timer interval to ~1000 so you could clearly see how your text label increments at run-time.

Title: Why doesn't my counter count?

Body:
This really suprised me. One of the simplest things doesn't work, making a counter. I'm making a kinda game application in c# and there is also a timer who counts the time. Very simple right? I know how to code this and this is something I did before but I don't understand why it isn't working now.

int i = 0;
i++;
label1.Text = i.ToString();

label1.Text turns in to 1 and nothing else happens. Also tryied this with a timer but it freeezes in 1. I know this post isn't really going to help other people but it is very frustrating.

Body:
Why you are always getting 1 in your label1 text?

The reason is very simple, each time you are getting to the first line, i is 0:

// Line 1
int i = 0;  // declaring and setting i to 0
// Line 2
i++;        // incrementing i to 1
// Line 3
label1.Text = i.ToString();  // displaying i (which is equal to 1)

and then again you are getting to the Line 1 and setting i=0, etc...

I presume you have a UI application (win form, web form etc...)
You already mentioned you have a timer that works fine and a label where you output the incremented i variable.

As already commented in order to see a change in your label you can use a loop as following:

int length = 100;  // for example
for (int i = 0; i < length; i++)
{
    label1.Text = i.ToString();
}

The output in label1 text will be 0, then 1, then 2 .... and finally 99.
Obviously you won't be able to see all those values except the last one 99 at run-time but you can debug and see how it works.

I presume, what you needed is to have your label text changing each time the timer will tick.
Following a code example how you could implement it:

private int i = 0; // initialized once in this UI class

private void timer1_Tick(object sender, EventArgs e)
{
    label1.Text = i.ToString();
    i++; // will increment by one each time the timer is ticking
}

Set your timer interval to ~1000 so you could clearly see how your text label increments at run-time.


问:
How to append a matrix inside a WHILE loop that s nested iside a PARFOR loop in MATLAB?
I have a code that I use to compute the iterations needed to converge a number's Collatz sequence to one:

```<code>nums = input('Enter a number: ');

iter = zeros(1, nums, 'uint16');

collatz = zeros(1, nums, 'uint64');
seqn = zeros(nums, 'uint64');

parfor ii = 1:nums

    num = ii;
    collatz(ii) = num;
    % seqn(ii) = num;

    while num ~= 1

        % writes the maximum number reached
        if collatz(ii) < num
            collatz(ii) = num;
        end

        if rem(num, 2) == 0
            num = num / 2;
        else
            num = 3 * num + 1;
        end

        % counts iterations needed to reduce each number to one
        iter(ii) = iter(ii) + 1;

        % records the sequence
        seqn(:, iter(ii)) = num;

    end
end
</code>```

Shortly, it computes the Collatz sequence for each number up to num, records the maximum number in the sequence, and records the number of iterations ot took to reduce the number to one.

With the seqn matrix, I'm trying to record the Collatz sequnece of each number I run the loop for.

The problem here is that MATLAB won't run this PARFOR loop because of the changes done to seqn. I don't understand the reason! It seems to me that what I do to iter is essentially the same thing I do to seqn, in the sense that it executes inside the nested WHILE loop and does not depend on previous iterations.

What can I do to fix this?

答:
I've changed your while loop into for loop and set the final value of iter outside. additionally I'm only setting one element of seqn instead of entire column like you did. now matlab lets you run that but I'm not sure it's what you wanted, so take a look:

```<code>nums = input('Enter a number: ');

iter = zeros(1, nums, 'uint16');
maxitr = 1e6;
collatz = zeros(1, nums, 'uint64');
seqn = zeros(nums, 'uint64');

parfor ii = 1:nums

    num = ii;
    collatz(ii) = num;
    % seqn(ii) = num;

    for itr = 1:maxitr
        if num == 1
            break
        end
        % writes the maximum number reached
        if collatz(ii) < num
            collatz(ii) = num;
        end

        if rem(num, 2) == 0
            num = num / 2;
        else
            num = 3 * num + 1;
        end

        % records the sequence
        seqn(ii, itr) = num;
    end
    iter(ii) = itr - 1;
end
</code>```

Body:
I have a code that I use to compute the iterations needed to converge a number's Collatz sequence to one:

nums = input('Enter a number: ');

iter = zeros(1, nums, 'uint16');

collatz = zeros(1, nums, 'uint64');
seqn = zeros(nums, 'uint64');

parfor ii = 1:nums

    num = ii;
    collatz(ii) = num;
    % seqn(ii) = num;

    while num ~= 1

        % writes the maximum number reached
        if collatz(ii) < num
            collatz(ii) = num;
        end

        if rem(num, 2) == 0
            num = num / 2;
        else
            num = 3 * num + 1;
        end

        % counts iterations needed to reduce each number to one
        iter(ii) = iter(ii) + 1;

        % records the sequence
        seqn(:, iter(ii)) = num;

    end
end

Shortly, it computes the Collatz sequence for each number up to num, records the maximum number in the sequence, and records the number of iterations ot took to reduce the number to one.

With the seqn matrix, I'm trying to record the Collatz sequnece of each number I run the loop for.

The problem here is that MATLAB won't run this PARFOR loop because of the changes done to seqn. I don't understand the reason! It seems to me that what I do to iter is essentially the same thing I do to seqn, in the sense that it executes inside the nested WHILE loop and does not depend on previous iterations.

What can I do to fix this?

Body:
I've changed your while loop into for loop and set the final value of iter outside. additionally I'm only setting one element of seqn instead of entire column like you did. now matlab lets you run that but I'm not sure it's what you wanted, so take a look:

nums = input('Enter a number: ');

iter = zeros(1, nums, 'uint16');
maxitr = 1e6;
collatz = zeros(1, nums, 'uint64');
seqn = zeros(nums, 'uint64');

parfor ii = 1:nums

    num = ii;
    collatz(ii) = num;
    % seqn(ii) = num;

    for itr = 1:maxitr
        if num == 1
            break
        end
        % writes the maximum number reached
        if collatz(ii) < num
            collatz(ii) = num;
        end

        if rem(num, 2) == 0
            num = num / 2;
        else
            num = 3 * num + 1;
        end

        % records the sequence
        seqn(ii, itr) = num;
    end
    iter(ii) = itr - 1;
end


问:
How to set an environment variable from a Gradle build?
I'm trying to set an environment variable from my Gradle build. I'm on MacOS X (El Capitan).
The command is "gradle test".

I'm trying this in my build.gradle:

```<code>task setenv(type: Exec) {
    commandLine "export", "SOME_TEST_VAR=aaa"
}
test.dependsOn setenv
</code>```

and the build fails:

Execution failed for task ':myproject:setenv'.

A problem occurred starting process 'command 'export''

I also tried this:

```<code>test.doFirst {
    ProcessBuilder pb1 = new ProcessBuilder("export SOME_TEST_VAR=some test value")
    pb1.start();
}
</code>```

The build succeeds. However, if I check the environment variable in my JUnit test it fails:

```<code>assertTrue(System.getenv().containsKey("SOME_TEST_VAR"));
</code>```

Is there any way to set an environment variable from a Gradle build (in the build.gradle file)?

Update:

I've tested it in isolation: the values do get passed and my test task receives everything, be it a systemProperty, environment variables or jvmArgs.

So, it's nothing wrong with Gradle itself here.

The problem arises when I'm trying it on the real project. It uses Spring for dependency injection. I may be wrong but it looks like the Spring framework purges those values somewhere.

That sub-project is currently being frozen and I can't check my guess in detail right now.

答:
This one is working for me for settings environment variable for the test plugin</p>

```<code>test {
    systemProperties = [
        'catalina.home': 'c:/test'
    ]
    println "Starting Tests"
    beforeTest { descriptor ->
       logger.lifecycle("Running test: " + descriptor)
    }
}
</code>```

Body:
I'm trying to set an environment variable from my Gradle build. I'm on MacOS X (El Capitan).
The command is "gradle test".

I'm trying this in my build.gradle:

task setenv(type: Exec) {
    commandLine "export", "SOME_TEST_VAR=aaa"
}
test.dependsOn setenv

and the build fails:

Execution failed for task ':myproject:setenv'.

A problem occurred starting process 'command 'export''

I also tried this:

test.doFirst {
    ProcessBuilder pb1 = new ProcessBuilder("export SOME_TEST_VAR=some test value")
    pb1.start();
}

The build succeeds. However, if I check the environment variable in my JUnit test it fails:

assertTrue(System.getenv().containsKey("SOME_TEST_VAR"));

Is there any way to set an environment variable from a Gradle build (in the build.gradle file)?

Update:

I've tested it in isolation: the values do get passed and my test task receives everything, be it a systemProperty, environment variables or jvmArgs.

So, it's nothing wrong with Gradle itself here.

The problem arises when I'm trying it on the real project. It uses Spring for dependency injection. I may be wrong but it looks like the Spring framework purges those values somewhere.

That sub-project is currently being frozen and I can't check my guess in detail right now.

Body:
This one is working for me for settings environment variable for the test plugin

test {
    systemProperties = [
        'catalina.home': 'c:/test'
    ]
    println "Starting Tests"
    beforeTest { descriptor ->
       logger.lifecycle("Running test: " + descriptor)
    }
}


问:
Is it possible to use a single task in multiple DAGS in airflow?
I have a task_a that I want to use in DAG_1 and DAG_2. Is this possible in airflow?

```<code>task_a = SomeOperator(
task_id='some_id',
bash_command='some_command',
#instead of just
dag= DAG_1 # I want to assign this task to multiple dags
#dag=assign_multiple_dags_here(DAG_1 and DAG_2)
)
</code>```

Is this possible?

答:
As per Current Design no.

Tasks are part of DAG's. Each DAG run creates a task instance.

This is to keep the framework's housekeeping simple

Body:
I have a task_a that I want to use in DAG_1 and DAG_2. Is this possible in airflow?

task_a = SomeOperator(
task_id='some_id',
bash_command='some_command',
#instead of just
dag= DAG_1 # I want to assign this task to multiple dags
#dag=assign_multiple_dags_here(DAG_1 and DAG_2)
)

Is this possible?


问:
Discard a servant from CORBA after calling "servant_to_reference"
The following sequence gives me an IOR and keeps the MyObj instance
somewhere inside CORBA (JacORB) so that the IOR can be used at a later stage:

```<code>MyObj myObj = new MyObj();
org.omg.CORBA.Object ref = poa.servant_to_reference(myObj);
org.omg.CORBA.Object href = MyObjHelper.narrow(ref);
String ior = orb.object_to_string(href);
</code>```

Can I somehow tell JacORB to discard "myObj" (at a later stage, of course)? References are kept forever
in some Hastable (inside JacORB), and when creating a lot of entries, a
wild OutOfMemory appears at some point. I want JacORB to forget about my
object when I tell it to.

答:
Whenever you reference Corba object, it's internal reference count increases by one. This is similar to Java garbage collector mechanism.

That means that myObj will be garbage collected only when ior, href and ref are garbage collected.

There's also an option to manually decrease Corba reference count of myObj but this is not recommended because then you will defeat Corba's reference count mechanism and cause unpredictable behavior.

Body:
The following sequence gives me an IOR and keeps the MyObj instance
somewhere inside CORBA (JacORB) so that the IOR can be used at a later stage:

MyObj myObj = new MyObj();
org.omg.CORBA.Object ref = poa.servant_to_reference(myObj);
org.omg.CORBA.Object href = MyObjHelper.narrow(ref);
String ior = orb.object_to_string(href);

Can I somehow tell JacORB to discard "myObj" (at a later stage, of course)? References are kept forever
in some Hastable (inside JacORB), and when creating a lot of entries, a
wild OutOfMemory appears at some point. I want JacORB to forget about my
object when I tell it to.


问:
Modify x-frame-options in apache2
I want to use an iframe in my localhost web server (wamp).
This iframe loads a form from a remote web server.

I have access to the remote web server, it uses apache2 (https://help.ubuntu.com/lts/serverguide/httpd.html), and i modify its security.conf file and i load the module 'headers'.

I modify security.conf by this line (the ip is the ip of my local computer):

Header append X-Frame-Options "ALLOW-FROM http://localhost, http://172.18.48.120, 172.18.48.120"

But when i test the changes, always says the same:

Refused to display 'http://externalURL.net/form.php' in a frame because it set 'X-Frame-Options' to 'sameorigin'.

Any idea? Where's the problem?

答:
Just for completeness:

Here are the lines to add to your apache2/conf-available/security.conf file to make your iframed content available in browsers supporting either or both X-Frame-Options and Content-Security-Policy header options (as stated on this survey site)

Header set X-Frame-Options: "ALLOW_FROM https://www.example.com"

  Header set Content-Security-Policy: "frame-ancestors
  https://www.example.com"

Make sure that header module is enabled

```<code>a2enmod headers
</code>```

restart apache

```<code>service apache2 restart
</code>```

That's it !

Title: Modify x-frame-options in apache2

Body:
Just for completeness:

Here are the lines to add to your apache2/conf-available/security.conf file to make your iframed content available in browsers supporting either or both X-Frame-Options and Content-Security-Policy header options (as stated on this survey site)

Header set X-Frame-Options: "ALLOW_FROM https://www.example.com"

  Header set Content-Security-Policy: "frame-ancestors
  https://www.example.com"

Make sure that header module is enabled

a2enmod headers

restart apache

service apache2 restart

That's it !


问:
Update sorted list
I think there is common name for algorithm I am searching.

I have a big list of players sorted by their score. e.g 1 million or billion players.
Every second one player is changing its score and I wish to updated sorted list to keep it sorted and I wish to know a new player position.

I can update score and re-sort hole list. (not efficient)
or I can re-sort from [oldpos, newpos] (better)
or I can move player and shift other players. (best)

Is there name for such algorithm?

Is that correct that regular databases will not handle that task efficiently and I have to develop service in Java, C#, Go, etc that will keep sorted list in RAM and make shifts?

答:
You can hold an AVL tree, the insertion and deletions operation taken O(logn) time on such data structure. each time you need to update a player: remove from tree, change score, insert to tree.

This is the exact trade-off you are looking for, all the operations takes O(logn) and since you need all the operations (lookup and update - delete\insert) this is the best match for you. The memory consumption is O(n) btw.

Title: Update sorted list


问:
Complex List Comprehension slower than straight loop
I saw an interesting solution for a programming exercise on leetcode  It's not even about the problem/solution itself, so you can read it up on the link provided if you wish. However a high voted solution is this one liner:

Snippet 1

```<code>def fizzBuzz2(n):
    return  ["Fizz" * (not i%3) + "Buzz" * (not i%5) or str(i) for i in range(1, n+1)]
</code>```

Snippet 2

```<code>def fizzBuzz(n):
    out = []
    for i in range(1, n+1):
        if i % 3 == 0 and i % 5 == 0:
            out.append("FizzBuzz")
        elif i % 3 == 0:
            out.append("Fizz")
        elif i % 5 == 0:
            out.append("Buzz")
        else:
            out.append(str(i))

    return out
</code>```

However, I've expected that the list comprehension is going to beat the common loop, but when I've timed it and it wasn't the case. Even doing a dis, Snippet 2 has more instructions.

What is making Snippet 1 slow?

答:
While we’re exploring implementations, here’s a fun slice one that’s faster than the single list comprehension, but not as fast as @seenorth’s solution:</p>

```<code>from math import ceil

def fizz_buzz(n):
    result = list(range(n))
    result[::3] = ["Fizz"] * ceil(n / 3)
    result[::5] = ["Buzz"] * ceil(n / 5)
    result[::15] = ["FizzBuzz"] * ceil(n / 15)

    return list(map(str, result))
</code>```

Body:
I saw an interesting solution for a programming exercise on leetcode  It's not even about the problem/solution itself, so you can read it up on the link provided if you wish. However a high voted solution is this one liner:

Snippet 1

def fizzBuzz2(n):
    return  ["Fizz" * (not i%3) + "Buzz" * (not i%5) or str(i) for i in range(1, n+1)]

Snippet 2

def fizzBuzz(n):
    out = []
    for i in range(1, n+1):
        if i % 3 == 0 and i % 5 == 0:
            out.append("FizzBuzz")
        elif i % 3 == 0:
            out.append("Fizz")
        elif i % 5 == 0:
            out.append("Buzz")
        else:
            out.append(str(i))

    return out

However, I've expected that the list comprehension is going to beat the common loop, but when I've timed it and it wasn't the case. Even doing a dis, Snippet 2 has more instructions.

What is making Snippet 1 slow?

Body:
While we’re exploring implementations, here’s a fun slice one that’s faster than the single list comprehension, but not as fast as @seenorth’s solution:

from math import ceil

def fizz_buzz(n):
    result = list(range(n))
    result[::3] = ["Fizz"] * ceil(n / 3)
    result[::5] = ["Buzz"] * ceil(n / 5)
    result[::15] = ["FizzBuzz"] * ceil(n / 15)

    return list(map(str, result))


问:
How can I show a formset in Django with a AJAX success function?
For example if I have the following Ajax request:

```<code>$.ajax({
        type: "POST",
        url: url,
        traditional : true,
        data: { csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
                data: data,
         },

    success: function(data){
        var html_text =` <div>
            {% for form in formset %}
                {{form.as_p}}
            {% endfor %}
            </div> `
        $("#formset-div").append(html_text);

        }
    });
</code>```

I always get just text in the div after execute Ajax success function

How can I show form set with the created data that created by the python function that executed with the Ajax request?

答:
The template code doesn't belong in the Ajax function. Apart from anything else, that code (presumably) is in an external JS function which isn't parsed as a Django template; and, just as important, it doesn't have access to any of the context from the updated POST.

What you should do is to get the Django view that is called by the Ajax to render a template and return that; then the success function only needs to insert the resulting HTML.

Body:
For example if I have the following Ajax request:

$.ajax({
        type: "POST",
        url: url,
        traditional : true,
        data: { csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
                data: data,
         },

    success: function(data){
        var html_text =`

            {% for form in formset %}
                {{form.as_p}}
            {% endfor %}

 `
        $("#formset-div").append(html_text);

        }
    });

I always get just text in the div after execute Ajax success function

How can I show form set with the created data that created by the python function that executed with the Ajax request?


问:
How can I execute this sql backup script with JDBC?
How can I execute the following query against my database instance using JDBC, Everything I am trying is returning "no result set" errors.

```<code>com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set.
</code>```

What do I do when I'm not really looking data back as such?

.sql file

```<code>DECLARE @name VARCHAR(50) -- database name
DECLARE @path VARCHAR(256) -- path for backup files
DECLARE @fileName VARCHAR(256) -- filename for backup
DECLARE @fileDate VARCHAR(20) -- used for file name
DECLARE @fileFolder VARCHAR(20) -- used for file name

-- specify database backup directory
SET @path = 'C:\SQLBackups\'

-- specify filename format
SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112)

DECLARE db_cursor CURSOR FOR
SELECT name
FROM master.dbo.sysdatabases
WHERE name NOT IN ('master','model','msdb','tempdb')  -- exclude these databases

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @name

WHILE @@FETCH_STATUS = 0
BEGIN
       SET @fileName = @path + @name + '_' + @fileDate + '.BAK'
       BACKUP DATABASE @name TO DISK = @fileName

       FETCH NEXT FROM db_cursor INTO @name
END

CLOSE db_cursor
DEALLOCATE db_cursor
</code>```

My code for executing said query (so far)

```<code>    public static void connect(String instance, String saPassword, String query)  {
    Connection conn = null;
    query = "DECLARE @name VARCHAR(50) -- database name   " +
            "DECLARE @path VARCHAR(256) -- path for backup files   " +
            "DECLARE @fileName VARCHAR(256) -- filename for backup   " +
            "DECLARE @fileDate VARCHAR(20) -- used for file name " +
            "-- specify database backup directory " +
            "SET @path = 'C:\\SQLBackups\\'   " +
            "-- specify filename format " +
            "SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112)  " +
            "DECLARE db_cursor CURSOR FOR   " +
            "SELECT name  " +
            "FROM master.dbo.sysdatabases  " +
            "WHERE name NOT IN ('master','model','msdb','tempdb')  -- exclude these databases " +
            "OPEN db_cursor    " +
            "FETCH NEXT FROM db_cursor INTO @name    " +
            "WHILE @@FETCH_STATUS = 0    " +
            "BEGIN    " +
            "       SET @fileName = @path + @name + '_' + @fileDate + '.BAK'   " +
            "       BACKUP DATABASE @name TO DISK = @fileName   " +
            "       FETCH NEXT FROM db_cursor INTO @name    " +
            "END    " +
            "CLOSE db_cursor    " +
            "DEALLOCATE db_cursor ";
    try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
        String dbURL = "jdbc:sqlserver://10.0.0.0\\"+ instance;
        String user = "user";
        String pass = saPassword;
        conn = DriverManager.getConnection(dbURL, user, pass);
        Statement stmt = conn.createStatement();
        stmt.executeQuery(query);

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
</code>```

I can execute my query just fine in SSMS, is the conversion of the .sql text into the string causing issues here? I'm not too bothered about a result here as it should be creating a lot of .bak files on the server (which does happen when I execute it via SSMS, I changed around the query with grabbing a simple SELECT resultset which works just fine, so I'm a tad lost now.

overwriting the (query) in the method is just for testing purposes, once I get the .bak files landing on the remote server directory I will tidy it up, credentials masked for obvious reasons.

Thanks

答:
Your code is NOT readable (and therefore hard to maintain) as you are mixing both SQL & Java languages together, so I strongly recommend to use callableStatement, you can look here for a simple example.
In simple terms, you need to move all your SQL code to a procedure in the database and then callableStatement.execute()

Body:
How can I execute the following query against my database instance using JDBC, Everything I am trying is returning "no result set" errors.

com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set.

What do I do when I'm not really looking data back as such?

.sql file

DECLARE @name VARCHAR(50) -- database name
DECLARE @path VARCHAR(256) -- path for backup files
DECLARE @fileName VARCHAR(256) -- filename for backup
DECLARE @fileDate VARCHAR(20) -- used for file name
DECLARE @fileFolder VARCHAR(20) -- used for file name

-- specify database backup directory
SET @path = 'C:\SQLBackups\'

-- specify filename format
SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112)

DECLARE db_cursor CURSOR FOR
SELECT name
FROM master.dbo.sysdatabases
WHERE name NOT IN ('master','model','msdb','tempdb')  -- exclude these databases

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @name

WHILE @@FETCH_STATUS = 0
BEGIN
       SET @fileName = @path + @name + '_' + @fileDate + '.BAK'
       BACKUP DATABASE @name TO DISK = @fileName

       FETCH NEXT FROM db_cursor INTO @name
END

CLOSE db_cursor
DEALLOCATE db_cursor

My code for executing said query (so far)

    public static void connect(String instance, String saPassword, String query)  {
    Connection conn = null;
    query = "DECLARE @name VARCHAR(50) -- database name   " +
            "DECLARE @path VARCHAR(256) -- path for backup files   " +
            "DECLARE @fileName VARCHAR(256) -- filename for backup   " +
            "DECLARE @fileDate VARCHAR(20) -- used for file name " +
            "-- specify database backup directory " +
            "SET @path = 'C:\\SQLBackups\\'   " +
            "-- specify filename format " +
            "SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112)  " +
            "DECLARE db_cursor CURSOR FOR   " +
            "SELECT name  " +
            "FROM master.dbo.sysdatabases  " +
            "WHERE name NOT IN ('master','model','msdb','tempdb')  -- exclude these databases " +
            "OPEN db_cursor    " +
            "FETCH NEXT FROM db_cursor INTO @name    " +
            "WHILE @@FETCH_STATUS = 0    " +
            "BEGIN    " +
            "       SET @fileName = @path + @name + '_' + @fileDate + '.BAK'   " +
            "       BACKUP DATABASE @name TO DISK = @fileName   " +
            "       FETCH NEXT FROM db_cursor INTO @name    " +
            "END    " +
            "CLOSE db_cursor    " +
            "DEALLOCATE db_cursor ";
    try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
        String dbURL = "jdbc:sqlserver://10.0.0.0\\"+ instance;
        String user = "user";
        String pass = saPassword;
        conn = DriverManager.getConnection(dbURL, user, pass);
        Statement stmt = conn.createStatement();
        stmt.executeQuery(query);

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

I can execute my query just fine in SSMS, is the conversion of the .sql text into the string causing issues here? I'm not too bothered about a result here as it should be creating a lot of .bak files on the server (which does happen when I execute it via SSMS, I changed around the query with grabbing a simple SELECT resultset which works just fine, so I'm a tad lost now.

overwriting the (query) in the method is just for testing purposes, once I get the .bak files landing on the remote server directory I will tidy it up, credentials masked for obvious reasons.

Thanks


问:
What is the mAP metric and how is it calculated?
In Computer Vision and Object Detection, a common evaluation method is mAP.
What is it and how is it calculated?</p>

答:
Quotes are from the above mentioned Zisserman paper - 4.2 Evaluation of Results (Page 11):

First an "overlap criterion" is defined as an intersection-over-union greater than 0.5. (e.g. if a predicted box satisfies this criterion with respect to a ground-truth box, it is considered a detection). Then a matching is made between the GT boxes and the predicted boxes using this "greedy" approach:

Detections output by a method were assigned to ground truth objects
  satisfying the overlap criterion in order ranked by the (decreasing)
  confidence output. Multiple detections of the same object in an image
  were considered false detections e.g. 5 detections of a single object
  counted as 1 correct detection and 4 false detections

Hence each predicted box is either True-Positive or False-Positive.
Each ground-truth box is True-Positive.
There are no True-Negatives.

Then the average precision is computed by averaging the precision values on the precision-recall curve where the recall is in the range [0, 0.1, ..., 1] (e.g. average of 11 precision values). To be more precise, we consider a slightly corrected PR curve, where for each curve point (p, r), if there is a different curve point (p', r') such that p' > p and r' >= r, we replace p with maximum p' of those points.

What is still unclear to me is what is done with those GT boxes that are never detected (even if the confidence is 0). This means that there are certain recall values that the precision-recall curve will never reach, and this makes the average precision computation above undefined.

Edit:

Short answer: in the region where the recall is unreachable, the precision drops to 0.

One way to explain this is to assume that when the threshold for the confidence approaches 0, an infinite number of predicted bounding boxes light up all over the image.  The precision then immediately goes to 0 (since there is only a finite number of GT boxes) and the recall keeps growing on this flat curve until we reach 100%.


问:
XSLT and base URIs with copy-of - Why does the uri change from the XML-file to the XSLT-file?
Given the following stylesheet

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template name="start">
        <base-uris>
            <node-base-uri>
                <xsl:value-of select="base-uri(.)" />
            </node-base-uri>
            <node-base-uri-from-copy>
                <xsl:variable name="doc">
                    <xsl:copy-of select="." />
                </xsl:variable>
                <xsl:value-of select="base-uri($doc)" />
            </node-base-uri-from-copy>
        </base-uris>
    </xsl:template>

</xsl:stylesheet>
</code>```

After transforming an arbitrary XML file with Saxon from the command line with the following command:

```<code>java net.sf.saxon.Transform -s:xml/index.xml -xsl:xsl/base-uri.xsl -it:start
</code>```

I expected the same values for the base URIs pointing to the XML source file. But the base URI in the second case (with copy-of) points to the XSLT file.

```<code><base-uris>
    <node-base-uri>file:/xml/index.xml</node-base-uri>
    <node-base-uri-from-copy>file:/xsl/base-uri.xsl</node-base-uri-from-copy>
</base-uris>
</code>```

Motivation: In the "real world stylesheet" I use a template to include other XML sources. They are specified in the source XML itself (relative paths in a href attribute).

```<code><xsl:template match="include" mode="includes">
    <xsl:copy-of select="document(@href, .)/*"/>
</xsl:template>
</code>```

From the Spec:

The base URI of a node is copied, except in the case of an element node having an xml:base attribute

My question(s):

First of all, I would like to know, how to preserve/set/copy the base URI from the XML file and not from the XSLT file.

Second, I do not understand the Spec and/or do not understand the xml:base attribute thing. I simply thought: I do not see any xml:base attribute in my code, so the base URI of the node should be copied.

Last remark:

Playing around, I came up with something like this, which feels clumsy or simply the wrong way to go:

```<code><node-base-uri-work-around>
    <xsl:variable name="doc">
        <wrapper>
            <xsl:attribute name="xml:base" select="base-uri(.)" />
            <xsl:copy-of select="." />
        </wrapper>
    </xsl:variable>
    <xsl:value-of select="base-uri($doc/wrapper)" />
</node-base-uri-work-around>
</code>```

答:
As for understanding

```<code>            <xsl:variable name="doc">
                <xsl:copy-of select="." />
            </xsl:variable>
</code>```

see https://www.w3.org/TR/xslt-30/#temporary-trees which says:

The construct:

<xsl:variable name="tree"></xsl:variable>

can be regarded as a shorthand for:

<xsl:variable name="tree" as="document-node()"><xsl:document validation="preserve"></xsl:document></xsl:variable>

and then explains that "The base URI of the document node is taken from the base URI of the variable binding element in the stylesheet.". So that explains why the base URI is the stylesheet URI in that case. If you want to change that you can use xml:base on the xsl:variable binding element as needed.

I am currently not sure how <xsl:copy-of select="document(@href, .)/*"/> relates to the problem you first describe in your question, you will have to elaborate where/how you experience base URI problems in that case.

Body:
Given the following stylesheet

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template name="start">
        <base-uris>
            <node-base-uri>
                <xsl:value-of select="base-uri(.)" />
            </node-base-uri>
            <node-base-uri-from-copy>
                <xsl:variable name="doc">
                    <xsl:copy-of select="." />
                </xsl:variable>
                <xsl:value-of select="base-uri($doc)" />
            </node-base-uri-from-copy>
        </base-uris>
    </xsl:template>

</xsl:stylesheet>

After transforming an arbitrary XML file with Saxon from the command line with the following command:

java net.sf.saxon.Transform -s:xml/index.xml -xsl:xsl/base-uri.xsl -it:start

I expected the same values for the base URIs pointing to the XML source file. But the base URI in the second case (with copy-of) points to the XSLT file.

<base-uris>
    <node-base-uri>file:/xml/index.xml</node-base-uri>
    <node-base-uri-from-copy>file:/xsl/base-uri.xsl</node-base-uri-from-copy>
</base-uris>

Motivation: In the "real world stylesheet" I use a template to include other XML sources. They are specified in the source XML itself (relative paths in a href attribute).

<xsl:template match="include" mode="includes">
    <xsl:copy-of select="document(@href, .)/*"/>
</xsl:template>

From the Spec:

The base URI of a node is copied, except in the case of an element node having an xml:base attribute

My question(s):

First of all, I would like to know, how to preserve/set/copy the base URI from the XML file and not from the XSLT file.

Second, I do not understand the Spec and/or do not understand the xml:base attribute thing. I simply thought: I do not see any xml:base attribute in my code, so the base URI of the node should be copied.

Last remark:

Playing around, I came up with something like this, which feels clumsy or simply the wrong way to go:

<node-base-uri-work-around>
    <xsl:variable name="doc">
        <wrapper>
            <xsl:attribute name="xml:base" select="base-uri(.)" />
            <xsl:copy-of select="." />
        </wrapper>
    </xsl:variable>
    <xsl:value-of select="base-uri($doc/wrapper)" />
</node-base-uri-work-around>

Body:
As for understanding

            <xsl:variable name="doc">
                <xsl:copy-of select="." />
            </xsl:variable>

see https://www.w3.org/TR/xslt-30/#temporary-trees which says:

The construct:

<xsl:variable name="tree"><a/></xsl:variable>

can be regarded as a shorthand for:

<xsl:variable name="tree" as="document-node()"><xsl:document validation="preserve"><a/></xsl:document></xsl:variable>

and then explains that "The base URI of the document node is taken from the base URI of the variable binding element in the stylesheet.". So that explains why the base URI is the stylesheet URI in that case. If you want to change that you can use xml:base on the xsl:variable binding element as needed.

I am currently not sure how <xsl:copy-of select="document(@href, .)/*"/> relates to the problem you first describe in your question, you will have to elaborate where/how you experience base URI problems in that case.


问:
How can I build a Android app with local MySQL database?
I would like to build a local database android app with MySQL. Can I do that? Does the user need MySQL server installed in their phone to run the app? Is there any special stuff to do? Thanks.</p>

答:
I don't think you can install MYSQL in phone. You have to connect to the remote server/database as told by @Fahad Alkami above.

You have to use sqlite which is pre-installed in android phone and you can use ORMs for easy like greenDAO, sugar, etc. Also you can use realm, if you would like to use other than sqlite.


问:
Python. Cannot make a request to simple site api. Flask and requests
I am trying to create simple API for my site. I created the route with flask:

```<code>@api.route('/api/rate&message_id=<message_id>&performer=<performer_login>', methods=['POST'])
def api_rate_msg(message_id, performer_login):
    print("RATE API ", message_id, ' ', performer_id)
    return 400
</code>```

print(...) function don't execute...

I use flask-socketio to communicate between client and server.

I send json from client and process it with:

```<code>@socket.on('rate')
def handle_rate(data):
    print(data)
    payload = {'message_id':data['message_id'], 'performer':data['performer']}
    r = requests.post('/api/rate', params=payload)
    print (r.status_code)
</code>```

Note, that data variable is sending from client and is correct(I've checked it).

print(r.status_code) don't exec too...

Where I'm wrong?
Please, sorry for my bad english :(

This api function must increase rate of message, which stored in mongodb, if interesting.

答:
Remove the below part from your api route

```<code>&message_id=<message_id>&performer=<performer_login
</code>```

This is not required in POST request. It helps in GET requests. API call in request is not matching the route definition and therefore you have the current problem

Body:
I am trying to create simple API for my site. I created the route with flask:

@api.route('/api/rate&message_id=<message_id>&performer=<performer_login>', methods=['POST'])
def api_rate_msg(message_id, performer_login):
    print("RATE API ", message_id, ' ', performer_id)
    return 400

print(...) function don't execute...

I use flask-socketio to communicate between client and server.

I send json from client and process it with:

@socket.on('rate')
def handle_rate(data):
    print(data)
    payload = {'message_id':data['message_id'], 'performer':data['performer']}
    r = requests.post('/api/rate', params=payload)
    print (r.status_code)

Note, that data variable is sending from client and is correct(I've checked it).

print(r.status_code) don't exec too...

Where I'm wrong?
Please, sorry for my bad english :(

This api function must increase rate of message, which stored in mongodb, if interesting.

Body:
Remove the below part from your api route

&message_id=<message_id>&performer=<performer_login

This is not required in POST request. It helps in GET requests. API call in request is not matching the route definition and therefore you have the current problem