问:
Is it possible to convert between two case class with different name and slightly different field in scala
for example, I have case classes

```<code>case class foo(timestamp:String, epochSecond: Long)
</code>```

and

```<code>case class bar(epochSecond: Long, timestamp:String)
</code>```

Is it possible to make conversion between the instance of these two classes?

答:
Your question is rather vague because there are so many ways to accomplish this. Here's one option.

With the definition of the case classes ...

```<code>case class Foo(timestamp:String, epochSecond: Long)
case class Bar(epochSecond: Long, timestamp:String)
</code>```

... add auxiliary factory methods.

```<code>object Foo {
  def apply(b: Bar): Foo = this(b.timestamp, b.epochSecond)
}
object Bar {
  def apply(f: Foo): Bar = this(f.epochSecond, f.timestamp)
}
</code>```

Now you can transition from one type to the other very simply.

```<code>val fooX = Foo("noon", 42L)
val barY = Bar(99L, "none")

val fooY = Foo(barY)  //fooY: Foo = Foo(none,99)
val barX = Bar(fooX)  //barX: Bar = Bar(42,noon)
</code>```

Body:
for example, I have case classes

case class foo(timestamp:String, epochSecond: Long)

and

case class bar(epochSecond: Long, timestamp:String)

Is it possible to make conversion between the instance of these two classes?

Body:
Your question is rather vague because there are so many ways to accomplish this. Here's one option.

With the definition of the case classes ...

case class Foo(timestamp:String, epochSecond: Long)
case class Bar(epochSecond: Long, timestamp:String)

... add auxiliary factory methods.

object Foo {
  def apply(b: Bar): Foo = this(b.timestamp, b.epochSecond)
}
object Bar {
  def apply(f: Foo): Bar = this(f.epochSecond, f.timestamp)
}

Now you can transition from one type to the other very simply.

val fooX = Foo("noon", 42L)
val barY = Bar(99L, "none")

val fooY = Foo(barY)  //fooY: Foo = Foo(none,99)
val barX = Bar(fooX)  //barX: Bar = Bar(42,noon)


来源: stackexchange

问:
Eclipse Maven project structure
I am fairly new to maven. In Eclipse, I created a maven project
Inside this I can see src/main/java and src/test/java also there is one more src folder which again contains main and test folder. Here I am confused in which src folder I need to write the code. What is the main benefit of using main and test folder? Why there are two main and two src folder

答:
I don't see src/main/test I see src/test in your screenshot.

It's a valid structure of separating tests from real code.

test package will not be deployed to production site. It'll be used only in development/QA/integration environments.

ContentLicense: CC BY-SA 3.0

Title: Eclipse Maven project structure


问:
How to stop gcc from passing -L with standard library paths to the linker
I have a script that needs to prevent gcc from passing -L with the standard library paths to ld. Using -nostdlib inhibits the -lc -lgcc etc. but not the -L. Using -Wl,-nostdlib prevents the linker from using its own standard path, but doesn't stop gcc from passing -L with the standard paths. Is there any way to ensure that gcc calls the linker with nothing in the library path expect the directories I explicitly write on the command line?

答:
I found a solution but it depends on gcc 4.4 or later for the -wrapper option (slightly updated version of the script):

```<code>inc=/path/to/alt/incl
lib=/path/to/alt/libs
crt=/path/to/alt/crt1.o
gcc -wrapper sh,-c,'
x= ; z= ; s= ; for i ; do
[ "$z" ] || set -- ; z=1
case "$i" in
-shared) s=1 ; set -- "$@" "$i" ;;
-Lxxxxxx) x=1 ;;
-xxxxxx) x= ; [ "$s" ] || set -- "$@" '"'$crt'"' ;;
*) [ "$x" ] || set -- "$@" "$i" ;;
esac
done
exec "$0" "$@"
' -nostdinc -nostdlib -isystem "$inc" -Wl,-xxxxxx "$@" -L"$lib" -Lxxxxxx -Wl,-nostdlib -lc -lgcc
</code>```

My version of this wrapper is tuned to re-add alternate crt1.o and libc and libgcc files in place of the ones it prevents access to, but you could just as easily omit them if needed.

ContentLicense: CC BY-SA 2.5

Body:
I found a solution but it depends on gcc 4.4 or later for the -wrapper option (slightly updated version of the script):

inc=/path/to/alt/incl
lib=/path/to/alt/libs
crt=/path/to/alt/crt1.o
gcc -wrapper sh,-c,'
x= ; z= ; s= ; for i ; do
[ "$z" ] || set -- ; z=1
case "$i" in
-shared) s=1 ; set -- "$@" "$i" ;;
-Lxxxxxx) x=1 ;;
-xxxxxx) x= ; [ "$s" ] || set -- "$@" '"'$crt'"' ;;
*) [ "$x" ] || set -- "$@" "$i" ;;
esac
done
exec "$0" "$@"
' -nostdinc -nostdlib -isystem "$inc" -Wl,-xxxxxx "$@" -L"$lib" -Lxxxxxx -Wl,-nostdlib -lc -lgcc

My version of this wrapper is tuned to re-add alternate crt1.o and libc and libgcc files in place of the ones it prevents access to, but you could just as easily omit them if needed.


问:
qsort not working properly with long long
I am sorting a two dimensional array a[n][2], with respect to a[i][0],a[i+1][0] breaking ties with non-decreasing a[i][1],a[i+1][1].
qsort is working fine with integer array but not with long long array.

Integer array code

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>

int cmpfunc(const void* a, const void* b)
{
    int x = ((int*)a)[0] - ((int*)b)[0];
    if (x != 0) {
        return x;
    }
    return ((int*)a)[1] - ((int*)b)[1];
}

int main(int argc, char const* argv[])
{
    int n, i, j;
    scanf("%d", &n);
    int a[n][2];
    for (i = 0; i < n; i = i + 1) {
        scanf("%d %d", &a[i][0], &a[i][1]);
    }
    qsort(a, n, sizeof(a[0]), cmpfunc);
    for (i = 0; i < n; i = i + 1) {
        printf("%d %d\n", a[i][0], a[i][1]);
    }
    return 0;
}
</code>```

long long array code

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>

int cmpfunc(const void* a, const void* b)
{
    int x = ((int*)a)[0] - ((int*)b)[0];
    if (x != 0) {
        return x;
    }
    return ((int*)a)[1] - ((int*)b)[1];
}

int main(int argc, char const* argv[])
{
    int n, i, j;
    scanf("%d", &n);
    long long a[n][2];
    for (i = 0; i < n; i = i + 1) {
        scanf("%I64d %I64d", &a[i][0], &a[i][1]);
    }
    qsort(a, n, sizeof(a[0]), cmpfunc);
    for (i = 0; i < n; i = i + 1) {
        printf("%I64d %I64d\n", a[i][0], a[i][1]);
    }
    return 0;
}
</code>```

Input:

```<code>5
4 3
4 2
4 1
4 1
4 1
</code>```

Output for first code:

```<code>4 1
4 1
4 1
4 2
4 3
</code>```

Output for second code:

```<code>4 2
4 1
4 1
4 1
4 3
</code>```

答:
If you enable warning while compiling (-Wall -pedantic for gcc) you should notice that you need different place holder for long long int and you can't assume that it's 64-bit. You also mis-cast arguments of compare function.
Notice that the difference between two long long int can be outside the range of an int so you can't use that (the one I wrote) qsort() compare implementation. Here's the code:

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>
int cmpfunc(const void *a,const void *b){
    long long int x=((long long int *)a)[0]-((long long int *)b)[0];
    if(x!=0){
        return x;
    }
    return ((long long int *)a)[1]-((long long int *)b)[1];
    }

int main(int argc, char const *argv[]){
    int n,i;
    scanf("%d",&n);
    long long a[n][2];
    for(i=0;i<n;i=i+1){
        scanf("%lld %lld",&a[i][0],&a[i][1]);
    }
    qsort(a,n,sizeof(a[0]),cmpfunc);
    for(i=0;i<n;i=i+1){
        printf("%lld %lld\n",a[i][0],a[i][1]);
    }
    return 0;
}
</code>```

Body:
I am sorting a two dimensional array a[n][2], with respect to a[i][0],a[i+1][0] breaking ties with non-decreasing a[i][1],a[i+1][1].
qsort is working fine with integer array but not with long long array.

Integer array code

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>

int cmpfunc(const void* a, const void* b)
{
    int x = ((int*)a)[0] - ((int*)b)[0];
    if (x != 0) {
        return x;
    }
    return ((int*)a)[1] - ((int*)b)[1];
}

int main(int argc, char const* argv[])
{
    int n, i, j;
    scanf("%d", &n);
    int a[n][2];
    for (i = 0; i < n; i = i + 1) {
        scanf("%d %d", &a[i][0], &a[i][1]);
    }
    qsort(a, n, sizeof(a[0]), cmpfunc);
    for (i = 0; i < n; i = i + 1) {
        printf("%d %d\n", a[i][0], a[i][1]);
    }
    return 0;
}

long long array code

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>

int cmpfunc(const void* a, const void* b)
{
    int x = ((int*)a)[0] - ((int*)b)[0];
    if (x != 0) {
        return x;
    }
    return ((int*)a)[1] - ((int*)b)[1];
}

int main(int argc, char const* argv[])
{
    int n, i, j;
    scanf("%d", &n);
    long long a[n][2];
    for (i = 0; i < n; i = i + 1) {
        scanf("%I64d %I64d", &a[i][0], &a[i][1]);
    }
    qsort(a, n, sizeof(a[0]), cmpfunc);
    for (i = 0; i < n; i = i + 1) {
        printf("%I64d %I64d\n", a[i][0], a[i][1]);
    }
    return 0;
}

Input:

5
4 3
4 2
4 1
4 1
4 1

Output for first code:

4 1
4 1
4 1
4 2
4 3

Output for second code:

4 2
4 1
4 1
4 1
4 3

Body:
If you enable warning while compiling (-Wall -pedantic for gcc) you should notice that you need different place holder for long long int and you can't assume that it's 64-bit. You also mis-cast arguments of compare function.
Notice that the difference between two long long int can be outside the range of an int so you can't use that (the one I wrote) qsort() compare implementation. Here's the code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>
int cmpfunc(const void *a,const void *b){
    long long int x=((long long int *)a)[0]-((long long int *)b)[0];
    if(x!=0){
        return x;
    }
    return ((long long int *)a)[1]-((long long int *)b)[1];
    }

int main(int argc, char const *argv[]){
    int n,i;
    scanf("%d",&n);
    long long a[n][2];
    for(i=0;i<n;i=i+1){
        scanf("%lld %lld",&a[i][0],&a[i][1]);
    }
    qsort(a,n,sizeof(a[0]),cmpfunc);
    for(i=0;i<n;i=i+1){
        printf("%lld %lld\n",a[i][0],a[i][1]);
    }
    return 0;
}


问:
Puppet Enterprise 2017.1 PAYG Marketplace Connectivity Iissue
Puppet Enterprise 2017.1 PAYG Marketplace may have connectivity issue to the marketplace when following this document:
https://docs.puppet.com/pe/latest/ami_intro.html</p>

答: Resolved: assign EIP to the instance during launch.</p>


问:
AWS NVMe Storage - hosting a database
Now that AWS are offering NVMe through the i3 range of servers, is there a best practice for hosting a database on the instance storage of one of these?

My understanding is that if the instance is stopped, the storage may be completely wiped.  This doesn't appear to be the case if the server reboots, intentionally or unintentionally, but you are still one button press away from wiping important data so this is quite scary.

My understanding of the underlying infrastructure is that this is because the NVMe storage is directly attached to the physical host, and therefore if Amazon decide to move your VM to another host you would lose your data.  Also it would be bad to store mission-critical data on a single hardware device AWS aside.

But given the performance benefits of NVMe over EBS (SAN?) storage, what would a recommended setup be? VM Replicas, transaction log backups to permanent storage, etc.

答:
It is possible to turn the NVMe SSDs on i3 instances into persistent highly available storage.

Options:

1) Mirroring between NVMe SSDs on 2 or 3 instances

2) Mirroring between NVMe SSDs and EBS (EBS can be on a different instance) with reads primarily from NVMe SSDs.

While write performance will still be limited by network or EBS, you do get full read performance of NVMe. In most cases read bandwidth is what large databases really need for running heavy queries.

However, there are still questions about failing over the database between the instances and restoring redundancy after instance stop/start of failure.

Check this whitepaper and page 9 specifically for details about how it is done for Oracle database clusters:
https://www.flashgrid.io/wp-content/sideuploads/resources/FlashGrid_OracleRAC_on_AWS.pdf

The paper is focused on Oracle RAC databases, but same solution works for single-instance Oracle and also for any other Linux-based database. Although, you would still need Oracle Clusterware (free).

Title: AWS NVMe Storage - hosting a database


问:
Turbolinks 5 and Android: Fails when use file upload (webview)

Problem

When the user clicks on choose file, I intercept that click natively and I call the native view (screen 3 in the mockup).

After the user select the file he wants to upload, I need to "reload" the view in order to add the name of the file in the form, so the user can get the feedback that he selected the file correctly.

In order to do this, I'm calling onRestart with the following code:

```<code> @Override
 protected void onRestart() {
     super.onRestart();

     // mCM is a variable to detect when the user is choosing a file.
     if (null == mCM) {
         // Since the webView is shared between activities, we need to tell Turbolinks
         // to load the location from the previous activity upon restarting
         TurbolinksSession.getDefault(this)
                 .activity(this)
                 .adapter(this)
                 .restoreWithCachedSnapshot(true)
                 .view(turbolinksView)
                 .visit(location);
      }
 }
</code>```

As you can see, in this method when is uploading a file I do NOT reload the view using TurbolinksSession.

But if I don't call TurbolinksSession, Turbolinks never calls visitProposedToLocationWithAction.

Scenario

NOTE: Download the image if you want to see the image bigger.

What am I missing? Is there a way to solve this problem and get the expected result?

答:
In this 2 issues you can find a solution and resolution of the problem (read it in this order):

https://github.com/turbolinks/turbolinks-android/issues/53

https://github.com/turbolinks/turbolinks-android/issues/65

https://github.com/turbolinks/turbolinks/issues/88

Body:
Problem

When the user clicks on choose file, I intercept that click natively and I call the native view (screen 3 in the mockup).

After the user select the file he wants to upload, I need to "reload" the view in order to add the name of the file in the form, so the user can get the feedback that he selected the file correctly.

In order to do this, I'm calling onRestart with the following code:

 @Override
 protected void onRestart() {
     super.onRestart();

     // mCM is a variable to detect when the user is choosing a file.
     if (null == mCM) {
         // Since the webView is shared between activities, we need to tell Turbolinks
         // to load the location from the previous activity upon restarting
         TurbolinksSession.getDefault(this)
                 .activity(this)
                 .adapter(this)
                 .restoreWithCachedSnapshot(true)
                 .view(turbolinksView)
                 .visit(location);
      }
 }

As you can see, in this method when is uploading a file I do NOT reload the view using TurbolinksSession.

But if I don't call TurbolinksSession, Turbolinks never calls visitProposedToLocationWithAction.

Scenario

NOTE: Download the image if you want to see the image bigger.

What am I missing? Is there a way to solve this problem and get the expected result?


问:
Want to Sort an array by ascending but Zero should be at Last
I am doing a php application for a sports event in some cases the minimum value scored is the winner. Like if there is 100mt running event then the winner is the fastest running. Winner has the minimum time taken to complete the race.

But what i am facing that when someone is absent or quit before finish then we are providing score ZERO. In that case when we are going to sort then the First Place will be the ZERO. But that should be at last.

Below is my code in javascript

```<code>var sorted = $(".result").sort(function (ib1, ib2) {
  return parseFloat($(ib2).val()) - parseFloat($(ib1).val());
});

// Result Names
$('#result_first').val($("#participant"+$(sorted.get(9)).data("section")).val());
$('#result_second').val($("#participant"+$(sorted.get(8)).data("section")).val());
$('#result_third').val($("#participant"+$(sorted.get(7)).data("section")).val());
$('#result_fourth').val($("#participant"+$(sorted.get(6)).data("section")).val());
$('#result_fifth').val($("#participant"+$(sorted.get(5)).data("section")).val());
$('#result_sixth').val($("#participant"+$(sorted.get(4)).data("section")).val());
$('#result_seventh').val($("#participant"+$(sorted.get(3)).data("section")).val());
$('#result_eighth').val($("#participant"+$(sorted.get(2)).data("section")).val());
$('#result_ninth').val($("#participant"+$(sorted.get(1)).data("section")).val());
$('#result_tenth').val($("#participant"+$(sorted.get(0)).data("section")).val());

// Result Numbers
$('#result_first_no').val($(sorted.get(9)).val());
$('#result_second_no').val($(sorted.get(8)).val());
$('#result_third_no').val($(sorted.get(7)).val());
$('#result_fourth_no').val($(sorted.get(6)).val());
$('#result_fifth_no').val($(sorted.get(5)).val());
$('#result_sixth_no').val($(sorted.get(4)).val());
$('#result_seventh_no').val($(sorted.get(3)).val());
$('#result_eighth_no').val($(sorted.get(2)).val());
$('#result_ninth_no').val($(sorted.get(1)).val());
$('#result_tenth_no').val($(sorted.get(0)).val());
</code>```

Please help me to sort these values and the ZERO values should be last.

答:
The basic idea here is to treat a 0 as Infinity:

```<code>var sorted = $(".result").sort(function (ib1, ib2) {
    function value(el) {
        var x = parseFloat($(el).val());
        return x === 0 ? Infinity : x;
    }

    return value(ib2) - value(ib1);
});
</code>```

A simple test:

var sorted = [5, 2, 0, 9, 4].sort(function(ib1, ib2) {
  function value(el) {
    var x = el; // parseFloat($(el).val());
    return x === 0 ? Infinity : x;
  }

  return value(ib2) - value(ib1);
});

console.log(sorted);```

Body:
I am doing a php application for a sports event in some cases the minimum value scored is the winner. Like if there is 100mt running event then the winner is the fastest running. Winner has the minimum time taken to complete the race.

But what i am facing that when someone is absent or quit before finish then we are providing score ZERO. In that case when we are going to sort then the First Place will be the ZERO. But that should be at last.

Below is my code in javascript

var sorted = $(".result").sort(function (ib1, ib2) {
  return parseFloat($(ib2).val()) - parseFloat($(ib1).val());
});

// Result Names
$('#result_first').val($("#participant"+$(sorted.get(9)).data("section")).val());
$('#result_second').val($("#participant"+$(sorted.get(8)).data("section")).val());
$('#result_third').val($("#participant"+$(sorted.get(7)).data("section")).val());
$('#result_fourth').val($("#participant"+$(sorted.get(6)).data("section")).val());
$('#result_fifth').val($("#participant"+$(sorted.get(5)).data("section")).val());
$('#result_sixth').val($("#participant"+$(sorted.get(4)).data("section")).val());
$('#result_seventh').val($("#participant"+$(sorted.get(3)).data("section")).val());
$('#result_eighth').val($("#participant"+$(sorted.get(2)).data("section")).val());
$('#result_ninth').val($("#participant"+$(sorted.get(1)).data("section")).val());
$('#result_tenth').val($("#participant"+$(sorted.get(0)).data("section")).val());

// Result Numbers
$('#result_first_no').val($(sorted.get(9)).val());
$('#result_second_no').val($(sorted.get(8)).val());
$('#result_third_no').val($(sorted.get(7)).val());
$('#result_fourth_no').val($(sorted.get(6)).val());
$('#result_fifth_no').val($(sorted.get(5)).val());
$('#result_sixth_no').val($(sorted.get(4)).val());
$('#result_seventh_no').val($(sorted.get(3)).val());
$('#result_eighth_no').val($(sorted.get(2)).val());
$('#result_ninth_no').val($(sorted.get(1)).val());
$('#result_tenth_no').val($(sorted.get(0)).val());

Please help me to sort these values and the ZERO values should be last.

Body:
The basic idea here is to treat a 0 as Infinity:

var sorted = $(".result").sort(function (ib1, ib2) {
    function value(el) {
        var x = parseFloat($(el).val());
        return x === 0 ? Infinity : x;
    }

    return value(ib2) - value(ib1);
});

A simple test:

var sorted = [5, 2, 0, 9, 4].sort(function(ib1, ib2) {
  function value(el) {
    var x = el; // parseFloat($(el).val());
    return x === 0 ? Infinity : x;
  }

  return value(ib2) - value(ib1);
});

console.log(sorted);


问:
codeigniter A Database Error Occurred
Can someone help me?

I am a beginner and trying to make wearing CodeIgniter authentication, but when I try to make an error like this

A Database Error Occurred

```<code>Error Number: 1046
</code>```

No database selected

```<code>SELECT * FROM (`user`) WHERE `user_username` = 'amanda' AND user_passwordMD5("12345") =

Filename: C:\xampp\htdocs\codeigniter\system\database\DB_driver.php

Line Number: 330
</code>```

thanx

答:
Lost connection to MySQL server during query
Line Number: 337</p>

Title: codeigniter A Database Error Occurred

Body:
Can someone help me?

I am a beginner and trying to make wearing CodeIgniter authentication, but when I try to make an error like this

A Database Error Occurred

Error Number: 1046

No database selected

SELECT * FROM (`user`) WHERE `user_username` = 'amanda' AND user_passwordMD5("12345") =

Filename: C:\xampp\htdocs\codeigniter\system\database\DB_driver.php

Line Number: 330

thanx


问:
Draw rectangle with Ghostscript (using PostScript language)
I'm trying to draw a rectangle and output it to a PDF using Ghostscript.
If I put the following PostScript code in a file named rect.eps, I get what I want:

```<code>newpath
100 100 moveto
0 100 rlineto
100 0 rlineto
0 -100 rlineto
-100 0 rlineto
closepath
gsave
0 0 0 setrgbcolor
fill
stroke
showpage
</code>```

But if I try to include that PostScript into my Ghostscript-command, I just get a blank page:

```<code>gs -o rect.pdf -sDEVICE=pdfwrite -g300x300 -c "newpath 100 100 moveto 0 100 rlineto 100 0 rlineto 0 -100 rlineto -100 0 rlineto closepath gsave 0 0 0 setrgbcolor fill stroke showpage"
</code>```

What am I doing wrong, shouldn't it be possible to draw a rectangle with Ghostscript?

Best Regards
Niclas

答:
Stefan's comment is effectively correct.

You have set a media size in pixels of 300x300. Now given that the pdfwrite device's default resolution is 720 dpi, and you haven't changed that, this means that the media size is less than half an inch in each direction.

You have then drawn a rectangle, staring at 100,100 units on the page, and extending by 100 units in each direction. PostScritp units are 1/72 of an inch, so your rectangle's lower left corner begins at just over 1 inch up and right.

That's outside the half-inch square defined by your media, so the result is simply that the rectangle is drawn off the page.

If you don't set the media size Ghostscript will use its default, either A4 or Letter depending, and you will see the output. As to why it works when you make an EPS file, I have no idea, I expect there is content in the EPS that you haven't shared which is making a difference.

When creating a PDF file, which is a resolution-independent format, its better to specify the media size in resolution-independent units, like PostScript units, than pixels.

Note that your code has an additional problem, also mentioned by Stefan, the dangling gsave, which looks like it ought to have a grestore before the stroke. As it is the stroke will do nothing, I suspect you want:

```<code>gsave
0 0 0 setrgbcolor
fill
grestore
stroke
showpage
</code>```

Body:
I'm trying to draw a rectangle and output it to a PDF using Ghostscript.
If I put the following PostScript code in a file named rect.eps, I get what I want:

newpath
100 100 moveto
0 100 rlineto
100 0 rlineto
0 -100 rlineto
-100 0 rlineto
closepath
gsave
0 0 0 setrgbcolor
fill
stroke
showpage

But if I try to include that PostScript into my Ghostscript-command, I just get a blank page:

gs -o rect.pdf -sDEVICE=pdfwrite -g300x300 -c "newpath 100 100 moveto 0 100 rlineto 100 0 rlineto 0 -100 rlineto -100 0 rlineto closepath gsave 0 0 0 setrgbcolor fill stroke showpage"

What am I doing wrong, shouldn't it be possible to draw a rectangle with Ghostscript?

Best Regards
Niclas

Body:
Stefan's comment is effectively correct.

You have set a media size in pixels of 300x300. Now given that the pdfwrite device's default resolution is 720 dpi, and you haven't changed that, this means that the media size is less than half an inch in each direction.

You have then drawn a rectangle, staring at 100,100 units on the page, and extending by 100 units in each direction. PostScritp units are 1/72 of an inch, so your rectangle's lower left corner begins at just over 1 inch up and right.

That's outside the half-inch square defined by your media, so the result is simply that the rectangle is drawn off the page.

If you don't set the media size Ghostscript will use its default, either A4 or Letter depending, and you will see the output. As to why it works when you make an EPS file, I have no idea, I expect there is content in the EPS that you haven't shared which is making a difference.

When creating a PDF file, which is a resolution-independent format, its better to specify the media size in resolution-independent units, like PostScript units, than pixels.

Note that your code has an additional problem, also mentioned by Stefan, the dangling gsave, which looks like it ought to have a grestore before the stroke. As it is the stroke will do nothing, I suspect you want:

gsave
0 0 0 setrgbcolor
fill
grestore
stroke
showpage


问:
How to get the id of selected option in datalist
I know the method to get the id while the value in option is unique but my case is different

```<code><select id="product-list">
   <option value="Product" id="1">
   <option value="Product1" id="2">
   <option value="Product1" id="3">
   <option value="Product2" id="4">
</select>
</code>```

Options are dynamically generated from database depending on the search query typed in input field.
There are situations when multiple products come with same name but other different properties like rate or unit.
So in order to solve the issue i want get the id of the selected option

答:
Do like this</p>

```<code>$("#product-list").change(function() {
  var id = $(this).children(":selected").attr("id");
  alert(id);
})
</code>```

Body:
I know the method to get the id while the value in option is unique but my case is different

<select id="product-list">
   <option value="Product" id="1">
   <option value="Product1" id="2">
   <option value="Product1" id="3">
   <option value="Product2" id="4">
</select>

Options are dynamically generated from database depending on the search query typed in input field.
There are situations when multiple products come with same name but other different properties like rate or unit.
So in order to solve the issue i want get the id of the selected option

Body:
Do like this

$("#product-list").change(function() {
  var id = $(this).children(":selected").attr("id");
  alert(id);
})


问:
Subscription downgrade in sandbox produces SSServerErrorDomain/SKErrorDomain (code 0) error
I got this when downgrading a subscription. The paymentQueue:updatedTransactions: function provides a transaction with error Error Domain=SSServerErrorDomain Code=0 "You are all set" UserInfo={NSLocalizedDescription=You are all set} and state as .failed.

Note the error domain is SSServerErrorDomain
NOT the more common SKErrorDomain. There seems to be no documentation about SSServerErrorDomain either.

If I try to purchase the same downgraded plan again, I will get “You are already subscribed.”.

The receipt right after the downgrade does not contain the new plan, which is expected because a downgrade will take effect at next renewal date. After 1 hour, I check the receipt again and it contains the new downgraded plan. (Monthly subscription interval is 5 mins in sandbox, and renews for about 6 times.)

I don't think we can do anything here because it comes from StoreKit. May be it's an Apple sandbox bug.

Steps to Reproduce:

Set up 2 subscriptions with different levels (will call plan A and B) in a subscription group in iTunes Connect

Go to the app, purchase the plan with higher level (A), observe successful purchase

Then immediately purchase lower level plan (B)

Got the mentioned error.

Version:
iOS 10.3.2 (14F89), iPhone 7 plus

Seems like some other people are seeing this also: https://github.com/bizz84/SwiftyStoreKit/issues/231

I filed a radar: http://www.openradar.me/radar?id=4998361958580224

Questions:

Has anyone experience this?

Could this be a sandbox only issue?

If it's also in production, how can I get around this?

Update:
I tested again today and it's returning error domain SKErrorDomain code=0 now. Apple, please tell us how to test subscription downgrade!

答: Have you tried with refreshing receipt just after paymentQueue:updatedTransactions: gets called? Are you receiving receipt with plan B?</p>


问:
how to sort an array based on the contents of another array
I have an array X = [12,14,12,45,12] and another array Y = [34,12,23,47,20]. I am sorting the X array, so now X = [12,12,12,14,45]. Now I want to sort Y as Y = [34,23,20,12,47]. Any help would be appreciated. Thanks</p>

答:
You can combine the arrays into a single array. Sort by the original values of X, and then separate back into 2 arrays.

const X = [12,14,12,45,12];
const Y = [34,12,23,47,20];

const [Xsorted, Ysorted] =
  X.map((x, i) => [x, Y[i]])
  .sort((a, b) => a[0] - b[0])
  .reduce((arrs, [x, y]) => {
    const [X, Y] = arrs;
    X.push(x);
    Y.push(y);

    return arrs;
  }, [[], []]);

console.log(Xsorted);
console.log(Ysorted);```


问:
How to use Header in Codeigniter
In the example above, we are using “dynamically added data”, which you will see below.

controller

```<code>public function index()
{

    $data['main_menus'] = '';
    if(count($this->menu_model->findActive()) > 0){
        $data['main_menus'] = $this->link_class->bootstrap_menu($this->menu_model->findActive());
    }

    $data['header'] = $this->load->view('common/header',$data);

    $data['posts'] = $this->home_model->find_active(3);
    $data['content'] = $this->load->view('common/content',$data);

    $this->load->view('layout',$data);

}
</code>```

view

```<code><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html lang="es">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="DBlog : Material Style Personal Blog Theme from Wowbootstrap">
    <meta name="author" content="wowbootstrap.com">
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,700|Merriweather:400,400italic,700italic" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Roboto:400,100,100italic,500,400italic,700,700italic,900,900italic,300,300italic,500italic" rel="stylesheet" type="text/css">
    <title><?php echo $page_title?> - CI Blog</title>
  </head>
  <body>
    <div id="wrapper">
      <?php echo $header;?>
      <section class="main">
        <div class="container">
          <div class="row">
            <div class="col-md-8">
            <?php //echo $content;?>
            </div>
            <div class="col-md-4">
            <?php //echo $right_sidebar;?>
            </div>
          </div>
        </div>
      </section>
      <?php //echo $footer;?>

    </div>

    <script>
      $.material.init();
    </script>

    <?php if(!empty($home_page)):?>
    <script type="text/javascript">

      $(window).scroll(function(){
        if ($(this).scrollTop() > 1){
          $('.top-navbar').removeClass('navbar-transparent');
        }else{
          $('.top-navbar').addClass('navbar-transparent');
        }
      });
    </script>
    <?php endif;?>

    <script type="text/javascript">
      $(document).ready(function () {
          $('[data-toggle="tooltip"]').tooltip();
      });
    </script>

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

I am using codeigniter to develop php web site. Now I have the question.
In controller,$this->load->view('index', $data);
I want $data can also share in header.php that included in index.php.

How to do???

答:
In Your Controller : to load view file like this,

```<code>public function index()
{

$data['main_menus'] = '';
if(count($this->menu_model->findActive()) > 0){
    $data['main_menus'] = $this->link_class->bootstrap_menu($this->menu_model->findActive());
}

$data['posts'] = $this->home_model->find_active(3);

// To load view files
$this->load->view('common/header',$data);    // header view file
$this->load->view('common/content',$data);    // body content view file
$this->load->view('layout',$data);            // footer view file
</code>```

}

Title: How to use Header in Codeigniter

Body:
In the example above, we are using “dynamically added data”, which you will see below.

controller

public function index()
{

    $data['main_menus'] = '';
    if(count($this->menu_model->findActive()) > 0){
        $data['main_menus'] = $this->link_class->bootstrap_menu($this->menu_model->findActive());
    }

    $data['header'] = $this->load->view('common/header',$data);

    $data['posts'] = $this->home_model->find_active(3);
    $data['content'] = $this->load->view('common/content',$data);

    $this->load->view('layout',$data);

}

view

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="DBlog : Material Style Personal Blog Theme from Wowbootstrap">
    <meta name="author" content="wowbootstrap.com">
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,700|Merriweather:400,400italic,700italic" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Roboto:400,100,100italic,500,400italic,700,700italic,900,900italic,300,300italic,500italic" rel="stylesheet" type="text/css">
    <title><?php echo $page_title?> - CI Blog</title>

      <?php echo $header;?>

            <?php //echo $content;?>

            <?php //echo $right_sidebar;?>

      <?php //echo $footer;?>

    <?php if(!empty($home_page)):?>

    <?php endif;?>

I am using codeigniter to develop php web site. Now I have the question.
In controller,$this->load->view('index', $data);
I want $data can also share in header.php that included in index.php.

How to do???

Body:
In Your Controller : to load view file like this,

public function index()
{

$data['main_menus'] = '';
if(count($this->menu_model->findActive()) > 0){
    $data['main_menus'] = $this->link_class->bootstrap_menu($this->menu_model->findActive());
}

$data['posts'] = $this->home_model->find_active(3);

// To load view files
$this->load->view('common/header',$data);    // header view file
$this->load->view('common/content',$data);    // body content view file
$this->load->view('layout',$data);            // footer view file

}


问:
docker build - exactly 1 argument
I've been trying to build syntaxnet on my ubuntu setup and bumped into a problem (simple as it may be) that I had hard time finding the solution to.

Whenever I try to build using the command:

```<code>docker build -t dragnn-oss:latest-minimal -f docker-devel/Dockerile.min
</code>```

I get the error message:

```<code>"docker build" requires exactly 1 argument(s).
</code>```

Now, my docker version is 17.06 and according to this page,
[docker: "build" requires 1 argument. See 'docker build --help', I should be able to specify a Dockerfile that is located in a different directory, so I don't see what the problem is.

Edit: I created a symlink by doing:

```<code>ln -s docker-devel/Dockerfile.min link1
</code>```

Then I just went through with the command:

```<code>docker build -t dragnn-oss:latest-minimal -f link1 .
</code>```

and it worked.

I thought I did not need to put the . at the end since I specified the Dockerfile with -f but learned the mistake.

答:
Specify a directory and in this directory, a Dockerfile : </p>

```<code>docker build -t dragnn-oss:latest-minimal -f Dockerile.min docker-devel
</code>```

Title: docker build - exactly 1 argument

Body:
I've been trying to build syntaxnet on my ubuntu setup and bumped into a problem (simple as it may be) that I had hard time finding the solution to.

Whenever I try to build using the command:

docker build -t dragnn-oss:latest-minimal -f docker-devel/Dockerile.min

I get the error message:

"docker build" requires exactly 1 argument(s).

Now, my docker version is 17.06 and according to this page,
[docker: "build" requires 1 argument. See 'docker build --help', I should be able to specify a Dockerfile that is located in a different directory, so I don't see what the problem is.

Edit: I created a symlink by doing:

ln -s docker-devel/Dockerfile.min link1

Then I just went through with the command:

docker build -t dragnn-oss:latest-minimal -f link1 .

and it worked.

I thought I did not need to put the . at the end since I specified the Dockerfile with -f but learned the mistake.

Body:
Specify a directory and in this directory, a Dockerfile :

docker build -t dragnn-oss:latest-minimal -f Dockerile.min docker-devel


问:
How to enable tungsten sort shuffle in Spark 2.1?
In previous versions, there is a configuration called spark.shuffle.manage which is used to determine the type of shuffle algorithm in Spark. Since Spark 2.0, this configuration is deleted. The default shuffle algorithm is the sort-based. As my understanding, the Tungsten shuffle will be enabled only if all the requirements are satisfied. How can I know whether the current job uses the original sort-based shuffle or Tungsten sort?

Thank you very much.

答:
SortShuffleManager is the one and only ShuffleManager in Apache Spark.

In other words, there's no way you could use any other ShuffleManager but SortShuffleManager (unless you enabled one using spark.shuffle.manager property).

ContentLicense: CC BY-SA 4.0


问:
Regex Searching in vim
I'm using vim to do some pattern matching on a text file. I've enabled search highlighting so that I know exactly what is getting matched on each search and am getting confused.

Consider searching for [a-z]* on the following text:```123456789abcdefghijklmnopqrstuvwxyxz987654321ABCDEFGHIJKLMNOPQRSTUVWQXZ```

I expected this search to match zero or more consecutive characters that are in the range [a-z]. Instead, I get a match on the entire line.

Should this be the expected behaviour?

Thanks,

Andrew

答: Empty string matches [a-z]*... therefore this thing is matching everywhere. Perhaps you want to cut down some of the cases by doing [a-z]+ (1 or more), or [a-z]{4,} (4 or more).

Title: Regex Searching in vim

Body:
I'm using vim to do some pattern matching on a text file. I've enabled search highlighting so that I know exactly what is getting matched on each search and am getting confused.

Consider searching for [a-z]* on the following text:
123456789abcdefghijklmnopqrstuvwxyxz987654321ABCDEFGHIJKLMNOPQRSTUVWQXZ

I expected this search to match zero or more consecutive characters that are in the range [a-z]. Instead, I get a match on the entire line.

Should this be the expected behaviour?

Thanks,

Andrew


问:
AngularDart Dialog service
I need to open a dialog (modal) in a component in an ngFor loop. I'm pretty sure repeating the modal inside my component is not the answer.

I'm looking for a way to have a Dialog Service in AngulatDart, in Angular2 (TS) I would do something like :

```<code>@Injectable()
export class MyDialogService {
  constructor(private dialog: MdDialog) {
  }

  public openDialog() {
    let dialogRef: MdDialogRef<MyDialogComponent>;
    dialogRef = this.dialog.open(MyDialogComponent);
    return dialogRef.afterClosed();
  }
}
</code>```

I didn't find a way to do the same in AngularDart

答:
As suggested by Günter and matanlurey, I end up creating a simple service with a LazyEventEmitter to trigger the dialog :

dialog_service.dart

```<code>@Injectable()
class DialogService {
  final LazyEventEmitter<bool> modalEvents = new LazyEventEmitter<bool>();

  DialogService() {
  }

  void openDialog() {
    modalEvents.add(true);
  }
}
</code>```

The parent component (eg AppComponent) contains the Dialog component :

dialog_component.html

```<code><modal [(visible)]="showDialog">
  <material-dialog headered class="headered-dialog">
    [...]
  </material-dialog>
</modal>
</code>```

dialog_component.dart

```<code>@Component(
  selector: 'my-dialog',
  styleUrls: const ['dialog_component.css'],
  templateUrl: 'dialog_component.html',
  directives: const [materialDirectives],
  providers: const [materialProviders]
)
class DialogComponent implements OnInit {
  final DialogService _dialogService;
  bool showDialog = false;

  DialogComponent(this._dialogService);

  @override
  ngOnInit() {
    _dialogService.modalEvents.listen((showDialog) {
      this.showDialog = showDialog;
    });
  }
}
</code>```

Title: AngularDart Dialog service

Body:
I need to open a dialog (modal) in a component in an ngFor loop. I'm pretty sure repeating the modal inside my component is not the answer.

I'm looking for a way to have a Dialog Service in AngulatDart, in Angular2 (TS) I would do something like :

@Injectable()
export class MyDialogService {
  constructor(private dialog: MdDialog) {
  }

  public openDialog() {
    let dialogRef: MdDialogRef<MyDialogComponent>;
    dialogRef = this.dialog.open(MyDialogComponent);
    return dialogRef.afterClosed();
  }
}

I didn't find a way to do the same in AngularDart

Body:
As suggested by Günter and matanlurey, I end up creating a simple service with a LazyEventEmitter to trigger the dialog :

dialog_service.dart

@Injectable()
class DialogService {
  final LazyEventEmitter<bool> modalEvents = new LazyEventEmitter<bool>();

  DialogService() {
  }

  void openDialog() {
    modalEvents.add(true);
  }
}

The parent component (eg AppComponent) contains the Dialog component :

dialog_component.html

<modal [(visible)]="showDialog">
  <material-dialog headered class="headered-dialog">
    [...]
  </material-dialog>
</modal>

dialog_component.dart

@Component(
  selector: 'my-dialog',
  styleUrls: const ['dialog_component.css'],
  templateUrl: 'dialog_component.html',
  directives: const [materialDirectives],
  providers: const [materialProviders]
)
class DialogComponent implements OnInit {
  final DialogService _dialogService;
  bool showDialog = false;

  DialogComponent(this._dialogService);

  @override
  ngOnInit() {
    _dialogService.modalEvents.listen((showDialog) {
      this.showDialog = showDialog;
    });
  }
}


问:
SQL Server Config manager error: Cannot connect to WMI provider
I cant open my SQL server configuration manager getting this error message:

```<code>Cannot connect to WMI provider. You do not have permission or the server is unreachable. Note that you can only manage SQL Server 2005 and later servers with SQL Server Configuration Manager.
Invalid
</code>```

I have searched online material and ran the mofcomp command as recommended: mofcomp “C:\Program Files (x86)\Microsoft SQL Server\120\Shared\sqlmgmproviderxpsp2up.mof”

I am now getting this error message:

```<code>MOF file has been successfully parsed
Storing data in the repository…
An error occurred while processing item 10 defined on lines 73 – 79 in file C:\Program Files (x86)\Microsoft SQL Server\120\Shared\sqlmgmproviderxpsp2up.mof:
Compiler returned error 0x80070005Error Number: 0x80070005, Facility: Win32
Description: Access is denied.
</code>```

Can you please help me out, been 2 weeks sited with this problem

答:
doing a fresh OS installation also worked for me as well. but this is a pain. Sometimes you can run the:

```<code>“C:\Program Files (x86)\Microsoft SQL Server\120\Shared\sqlmgmproviderxpsp2up.mof”
</code>```

Sometimes it helps and sometimes it doesn't, all you need to do is do a fresh OS installation and then SQL installation.

Body:
I cant open my SQL server configuration manager getting this error message:

Cannot connect to WMI provider. You do not have permission or the server is unreachable. Note that you can only manage SQL Server 2005 and later servers with SQL Server Configuration Manager.
Invalid

I have searched online material and ran the mofcomp command as recommended: mofcomp “C:\Program Files (x86)\Microsoft SQL Server\120\Shared\sqlmgmproviderxpsp2up.mof”

I am now getting this error message:

MOF file has been successfully parsed
Storing data in the repository…
An error occurred while processing item 10 defined on lines 73 – 79 in file C:\Program Files (x86)\Microsoft SQL Server\120\Shared\sqlmgmproviderxpsp2up.mof:
Compiler returned error 0x80070005Error Number: 0x80070005, Facility: Win32
Description: Access is denied.

Can you please help me out, been 2 weeks sited with this problem

Body:
doing a fresh OS installation also worked for me as well. but this is a pain. Sometimes you can run the:

“C:\Program Files (x86)\Microsoft SQL Server\120\Shared\sqlmgmproviderxpsp2up.mof”

Sometimes it helps and sometimes it doesn't, all you need to do is do a fresh OS installation and then SQL installation.


问:
List.remove() is behaving differently for negative values
I have a requirement in our code, where we need to catch ArrayIndexOutOfBoundsException and move forward with other elements.

However, when i try to do that i am getting ConcurrentModificationException

Following code is something that i want but it is throwing ConcurrentModificationException exception at line #1

Note that list.remove(1000) is not causing any issue  but list.remove(-1) does

```<code>public class Test1 {
        public static void main(String[] argv) {
            test(new ArrayList<>());
        }

        public static void test(List<Integer> list) {
            list.add(42);
            Iterator<Integer> it = list.iterator();

            try {
                list.remove(-1);
            } catch (Exception e) {
                System.out.println(e);
            }

            try {
                if (it.next() != 42);//Line #1
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }
</code>```

Can some one help me understand this behavior and how can I fix this problem ?

答:
The easiest way to fix this problem is not to pass a negative index to list.remove().

The reason this second exception occurs is that remove performs a partial range check, that only checks if the passed index is too large. It doesn't check if it's negative, since it relies on the access of the backing array to throw the exception in this case.

So, for negative index, the modCount of the ArrayList is incremented before the ArrayIndexOutOfBoundsException is thrown. As a result, trying to continue iterating over the list after catching this exception throws ConcurrentModificationException.

```<code>public E remove(int index) {
    rangeCheck(index);

    modCount++;
    E oldValue = elementData(index); // ArrayIndexOutOfBoundsException is thrown here

    int numMoved = size - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index,
                         numMoved);
    elementData[--size] = null; // clear to let GC do its work

    return oldValue;
}
</code>```

Note that list.remove(1000) will not cause this issue, since the IndexOutOfBoundsException will be thrown before modCount is incremented.

Of course, if the element removal was successful, you may still fail with ConcurrentModificationException, since the only way to safely remove elements from the List while iterating over it is to use the Iterator's remove() method.

One more thing - I'm not sure if you intended to call public E remove(int index) or public boolean remove(Object o). The former (which is the one that was chosen by the compiler) attempts to remove the element at the specified index, while the latter removes the specified element if found.

For a List<Integer>, passing an int to that method will attempt to remove by index even if you wanted to remove by element. If you wanted to remove by element, you should pass a reference type - list.remove(Integer.valueOf(-1)).

Body:
I have a requirement in our code, where we need to catch ArrayIndexOutOfBoundsException and move forward with other elements.

However, when i try to do that i am getting ConcurrentModificationException

Following code is something that i want but it is throwing ConcurrentModificationException exception at line #1

Note that list.remove(1000) is not causing any issue  but list.remove(-1) does

public class Test1 {
        public static void main(String[] argv) {
            test(new ArrayList<>());
        }

        public static void test(List<Integer> list) {
            list.add(42);
            Iterator<Integer> it = list.iterator();

            try {
                list.remove(-1);
            } catch (Exception e) {
                System.out.println(e);
            }

            try {
                if (it.next() != 42);//Line #1
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }

Can some one help me understand this behavior and how can I fix this problem ?

Body:
The easiest way to fix this problem is not to pass a negative index to list.remove().

The reason this second exception occurs is that remove performs a partial range check, that only checks if the passed index is too large. It doesn't check if it's negative, since it relies on the access of the backing array to throw the exception in this case.

So, for negative index, the modCount of the ArrayList is incremented before the ArrayIndexOutOfBoundsException is thrown. As a result, trying to continue iterating over the list after catching this exception throws ConcurrentModificationException.

public E remove(int index) {
    rangeCheck(index);

    modCount++;
    E oldValue = elementData(index); // ArrayIndexOutOfBoundsException is thrown here

    int numMoved = size - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index,
                         numMoved);
    elementData[--size] = null; // clear to let GC do its work

    return oldValue;
}

Note that list.remove(1000) will not cause this issue, since the IndexOutOfBoundsException will be thrown before modCount is incremented.

Of course, if the element removal was successful, you may still fail with ConcurrentModificationException, since the only way to safely remove elements from the List while iterating over it is to use the Iterator's remove() method.

One more thing - I'm not sure if you intended to call public E remove(int index) or public boolean remove(Object o). The former (which is the one that was chosen by the compiler) attempts to remove the element at the specified index, while the latter removes the specified element if found.

For a List<Integer>, passing an int to that method will attempt to remove by index even if you wanted to remove by element. If you wanted to remove by element, you should pass a reference type - list.remove(Integer.valueOf(-1)).


问:
Windows form application exception
I get application exception

```<code>   at System.Windows.Forms.CurrencyManager.get_Item(Int32 index)
   at System.Windows.Forms.CurrencyManager.get_Current()
   at System.Windows.Forms.DataGridView.DataGridViewDataConnection.OnRowEnter(DataGridViewCellEventArgs e)
   at System.Windows.Forms.DataGridView.OnRowEnter(DataGridViewCell& dataGridViewCell, Int32 columnIndex, Int32 rowIndex, Boolean canCreateNewRow, Boolean validationFailureOccurred)
   at System.Windows.Forms.DataGridView.SetCurrentCellAddressCore(Int32 columnIndex, Int32 rowIndex, Boolean setAnchorCellAddress, Boolean validateCurrentCell, Boolean throughMouseClick)
   at System.Windows.Forms.DataGridView.OnCellMouseDown(HitTestInfo hti, Boolean isShiftDown, Boolean isControlDown)
   at System.Windows.Forms.DataGridView.OnCellMouseDown(DataGridViewCellMouseEventArgs e)
   at System.Windows.Forms.DataGridView.OnMouseDown(MouseEventArgs e)
   at System.Windows.Forms.Control.WmMouseDown(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.DataGridView.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.Run(Form mainForm)
   at MedForms.Program.Main() in F:\Projects\Vstu\MedForms\MedForms\Program.cs:line 18
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()
</code>```

each time when I try to click on DataGridView.

I get error message

{"Index -1 does not have a value."}
  (SystemIndexOutOfaRange exception).

on row

```<code>Application.Run(new MainForm());
</code>```

and I am not able to debug it. Please help me find what can cause such problem and how I can to debug it?

答:
I'm guessing that you have bound a List that is initially empty, (or other sort of collection that does not generate list changed events) to your DataGridView, and then added items to this List.

The items you add will display correctly on your grid, but clicking on a row will cause this exception. This is because the underlying CurrencyManager will be reporting its current row position as an offset of -1. It will stay this way because the List does not report changes to the grid.

You should only bind your list to the grid if it has some items in it to begin with, or rebind when you add them.

See also my answer to this question, which is essentially the same problem.

Title: Windows form application exception

Body:
I get application exception

   at System.Windows.Forms.CurrencyManager.get_Item(Int32 index)
   at System.Windows.Forms.CurrencyManager.get_Current()
   at System.Windows.Forms.DataGridView.DataGridViewDataConnection.OnRowEnter(DataGridViewCellEventArgs e)
   at System.Windows.Forms.DataGridView.OnRowEnter(DataGridViewCell& dataGridViewCell, Int32 columnIndex, Int32 rowIndex, Boolean canCreateNewRow, Boolean validationFailureOccurred)
   at System.Windows.Forms.DataGridView.SetCurrentCellAddressCore(Int32 columnIndex, Int32 rowIndex, Boolean setAnchorCellAddress, Boolean validateCurrentCell, Boolean throughMouseClick)
   at System.Windows.Forms.DataGridView.OnCellMouseDown(HitTestInfo hti, Boolean isShiftDown, Boolean isControlDown)
   at System.Windows.Forms.DataGridView.OnCellMouseDown(DataGridViewCellMouseEventArgs e)
   at System.Windows.Forms.DataGridView.OnMouseDown(MouseEventArgs e)
   at System.Windows.Forms.Control.WmMouseDown(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.DataGridView.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.Run(Form mainForm)
   at MedForms.Program.Main() in F:\Projects\Vstu\MedForms\MedForms\Program.cs:line 18
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

each time when I try to click on DataGridView.

I get error message

{"Index -1 does not have a value."}
  (SystemIndexOutOfaRange exception).

on row

Application.Run(new MainForm());

and I am not able to debug it. Please help me find what can cause such problem and how I can to debug it?


问:
How read(get) css style value of a server-side div in code behind(not set)?
i want to get 'display' css value of a server side div!

the code below does not work :

```<code>    if (div.Style["display"] == "none")
    {
        div.Style.Add("display", "table-row");
    }
</code>```

how can i get that value in c#?

thanks in advance

答:
better solution:

HTML

```<code><div id="divID" runat="server" style="display:none;"></div>
</code>```

C#

```<code>if(divID.Style.Value.ToLower() == "display:none;")
{
   divID.Style.Add("display", "table-row");
}
</code>```

Body:
i want to get 'display' css value of a server side div!

the code below does not work :

    if (div.Style["display"] == "none")
    {
        div.Style.Add("display", "table-row");
    }

how can i get that value in c#?

thanks in advance

Body:
better solution:

HTML

<div id="divID" runat="server" style="display:none;"></div>

C#

if(divID.Style.Value.ToLower() == "display:none;")
{
   divID.Style.Add("display", "table-row");
}


Title: How to get the id of selected option in datalist

Body: $('#product-list').find(":selected").attr('id');


问:
Remove last character from dictionary<string, dictionary<string, string>> using C#
I have

```<code>Dictionary<string, Dictionary<string, string>>
</code>```

My inner dictionary has the following data

```<code>{
  "1": {
    "message-Code1": "   0",
    "msg-Number-Pos11": "0",
    "msg-Number-Pos21": "0",
    "msg-Number-Pos31": " "
  },
  "2": {
    "message-Code2": "   0",
    "msg-Number-Pos12": "0",
    "msg-Number-Pos22": "0",
    "msg-Number-Pos32": " "
  }
</code>```

But I want a out like below

```<code>{
  "1": {
    "message-Code": "   0",
    "msg-Number-Pos1": "0",
    "msg-Number-Pos2": "0",
    "msg-Number-Pos3": " "
  },
  "2": {
    "message-Code": "   0",
    "msg-Number-Pos1": "0",
    "msg-Number-Pos2": "0",
    "msg-Number-Pos3": " "
  }
</code>```

Last character of the all the Key's is removed i.e 1 in the first set and 2 in the second set of result.

I was trying with below code

```<code>var result = dictionary.Where(pair => pair.Value.Remove(pair.Value.Key.Last()));
</code>```

This is throwing an error.
Can anyone help me in bringing the output that I need.

答:
Since you cant change a dictionary key you would have to re-create the nested dictionary using your new key.</p>

```<code>foreach (var item in dic.ToArray())
    dic[item.Key] = item.Value.ToDictionary(x =>
                      x.Key.Remove(x.Key.Length - 1), x => x.Value);
</code>```

Body:
I have

Dictionary<string, Dictionary<string, string>>

My inner dictionary has the following data

{
  "1": {
    "message-Code1": "   0",
    "msg-Number-Pos11": "0",
    "msg-Number-Pos21": "0",
    "msg-Number-Pos31": " "
  },
  "2": {
    "message-Code2": "   0",
    "msg-Number-Pos12": "0",
    "msg-Number-Pos22": "0",
    "msg-Number-Pos32": " "
  }

But I want a out like below

{
  "1": {
    "message-Code": "   0",
    "msg-Number-Pos1": "0",
    "msg-Number-Pos2": "0",
    "msg-Number-Pos3": " "
  },
  "2": {
    "message-Code": "   0",
    "msg-Number-Pos1": "0",
    "msg-Number-Pos2": "0",
    "msg-Number-Pos3": " "
  }

Last character of the all the Key's is removed i.e 1 in the first set and 2 in the second set of result.

I was trying with below code

var result = dictionary.Where(pair => pair.Value.Remove(pair.Value.Key.Last()));

This is throwing an error.
Can anyone help me in bringing the output that I need.

Body:
Since you cant change a dictionary key you would have to re-create the nested dictionary using your new key.

foreach (var item in dic.ToArray())
    dic[item.Key] = item.Value.ToDictionary(x =>
                      x.Key.Remove(x.Key.Length - 1), x => x.Value);


答: You're not getting a match on the entire line, you're getting a match on every character. Your pattern also matches nothing at all, which is matched by every single character.</p>

Title: Regex Searching in vim


问:
RabbitMq refuses connection when run in docker
My docker-compose file looks like this:

```<code>version: '2'

services:
  explore:
    image: explore
    build:
      context: ./Explore
      dockerfile: VsDockerfile
    environment:
      - "ElasticUrl=http://localhost:9200"
      - "RabbitMq/Host=localhost"
      - "RabbitMq/Username=guest"
      - "RabbitMq/Password=guest"
    networks:
      - localnet

  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:5.4.3
    container_name: elasticsearch
    environment:
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
    ports:
      - 9200:9200
    volumes:
      - ./esdata:/usr/share/elasticsearch/data
    networks:
      - localnet

  rabbit:
    image: rabbitmq:3.6.7-management
    hostname: rabbit
    ports:
      - 15672:15672
      - 5672:5672
    networks:
      - localnet

networks:
  localnet:
    external:
      name: localnet
</code>```

If I type http://localhost:15672 in the browser, I get the rabbitmq interface, but if I tries to connect from my Explore project like this:

```<code>public SqlToRabbitProcessor(SqlToRabbitRepository sqlToRabbitRepository)
{
    _sqlToRabbitRepository = sqlToRabbitRepository;

    var factory = new ConnectionFactory
    {
        HostName = Environment.GetEnvironmentVariable("RabbitMq/Host"),
        UserName = Environment.GetEnvironmentVariable("RabbitMq/Username"),
        Password = Environment.GetEnvironmentVariable("RabbitMq/Password")
    };

    var rabbit = factory.CreateConnection();
    channel = rabbit.CreateModel();
}
</code>```

Then it breaks in the line

```<code>var rabbit = factory.CreateConnection();
</code>```

with the error saying

ExtendedSocketException: Connection refused 127.0.0.1:5672
System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)

ConnectFailureException: Connection failed
RabbitMQ.Client.EndpointResolverExtensions.SelectOne(IEndpointResolver resolver, Func selector)

BrokerUnreachableException: None of the specified endpoints were reachable
RabbitMQ.Client.ConnectionFactory.CreateConnection(IEndpointResolver endpointResolver, string clientProvidedName)

答:
As my comment under the question suggested, it's because the "localhost" defined in the web application part is it's containers localhost, and not the docker host..

just needed to change

```<code>- "ElasticUrl=http://localhost:9200"
- "RabbitMq/Host=localhost"
</code>```

to

```<code>- "ElasticUrl=http://elasticsearch:9200"
- "RabbitMq/Host=rabbit"
</code>```

Body:
My docker-compose file looks like this:

version: '2'

services:
  explore:
    image: explore
    build:
      context: ./Explore
      dockerfile: VsDockerfile
    environment:
      - "ElasticUrl=http://localhost:9200"
      - "RabbitMq/Host=localhost"
      - "RabbitMq/Username=guest"
      - "RabbitMq/Password=guest"
    networks:
      - localnet

  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:5.4.3
    container_name: elasticsearch
    environment:
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
    ports:
      - 9200:9200
    volumes:
      - ./esdata:/usr/share/elasticsearch/data
    networks:
      - localnet

  rabbit:
    image: rabbitmq:3.6.7-management
    hostname: rabbit
    ports:
      - 15672:15672
      - 5672:5672
    networks:
      - localnet

networks:
  localnet:
    external:
      name: localnet

If I type http://localhost:15672 in the browser, I get the rabbitmq interface, but if I tries to connect from my Explore project like this:

public SqlToRabbitProcessor(SqlToRabbitRepository sqlToRabbitRepository)
{
    _sqlToRabbitRepository = sqlToRabbitRepository;

    var factory = new ConnectionFactory
    {
        HostName = Environment.GetEnvironmentVariable("RabbitMq/Host"),
        UserName = Environment.GetEnvironmentVariable("RabbitMq/Username"),
        Password = Environment.GetEnvironmentVariable("RabbitMq/Password")
    };

    var rabbit = factory.CreateConnection();
    channel = rabbit.CreateModel();
}

Then it breaks in the line

var rabbit = factory.CreateConnection();

with the error saying

ExtendedSocketException: Connection refused 127.0.0.1:5672
System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)

ConnectFailureException: Connection failed
RabbitMQ.Client.EndpointResolverExtensions.SelectOne(IEndpointResolver resolver, Func selector)

BrokerUnreachableException: None of the specified endpoints were reachable
RabbitMQ.Client.ConnectionFactory.CreateConnection(IEndpointResolver endpointResolver, string clientProvidedName)

Body:
As my comment under the question suggested, it's because the "localhost" defined in the web application part is it's containers localhost, and not the docker host..

just needed to change

- "ElasticUrl=http://localhost:9200"
- "RabbitMq/Host=localhost"

to

- "ElasticUrl=http://elasticsearch:9200"
- "RabbitMq/Host=rabbit"


问:
How do I print Excel without hidden cells with C#?
I'm using C# and I want to make an Excel file without hidden cells.

I did some actions to hide rows, and I want to make an Excel file with that, but the Excel file showed full rows with hidden rows.

Is there any options or tip to hide invisible rows?

```<code>List_Com.Sheets[0].Rows[i].Visible = false;
</code>```

答: Try also to set the row height to 0.</p>

Body:
I'm using C# and I want to make an Excel file without hidden cells.

I did some actions to hide rows, and I want to make an Excel file with that, but the Excel file showed full rows with hidden rows.

Is there any options or tip to hide invisible rows?

List_Com.Sheets[0].Rows[i].Visible = false;

Body: Try also to set the row height to 0.


问:
A function can take another function as one of its arguments
I wrote the following code in playground and try to learn from Apple doc function & classes.

Here is my code..

```<code>func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
    for item in list {
        if condition(item) {
            return true
        }
    }
    return false
}
func lessThanTen(number: Int) -> Bool {
    return number < 10
}
var numbers = [20, 19, 7, 12]
hasAnyMatches(numbers, condition: lessThanTen)
</code>```

How can I directly pass the different condition?
can I write like that..

```<code>hasAnyMatches(numbers, condition: { $0 < 10 })
</code>```

Actually this function return true/false, but when I write like that so in play ground behalf of this line o/p: (4 times)
So what happen when I'm write like that.

And give me solution to direct pass the condition in hasAnyMatches() func.

答:
hasAnyMatches function takes the list of numbers and the condition closure so you can pass any closure which takes a Int and returns bool

```<code>let numbers = [20, 19, 7, 12]
let lessThan: (Int) -> Bool = { $0 < 10 }
let match = hasAnyMatches(list: numbers, condition: lessThan)
print(match)
</code>```

Another way to write the same thing would be to use filters which iterates over a collection and return an Array containing only those elements that match an include condition. main advantage of using filter is its inbuilt and you don't need separate hasAnyMatches function to check the condition

```<code>let numbers = [20, 19, 7, 12]
let match = numbers.filter ({ $0 < 10 }).count > 0
print(match)
</code>```

Body:
I wrote the following code in playground and try to learn from Apple doc function & classes.

Here is my code..

func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
    for item in list {
        if condition(item) {
            return true
        }
    }
    return false
}
func lessThanTen(number: Int) -> Bool {
    return number < 10
}
var numbers = [20, 19, 7, 12]
hasAnyMatches(numbers, condition: lessThanTen)

How can I directly pass the different condition?
can I write like that..

hasAnyMatches(numbers, condition: { $0 < 10 })

Actually this function return true/false, but when I write like that so in play ground behalf of this line o/p: (4 times)
So what happen when I'm write like that.

And give me solution to direct pass the condition in hasAnyMatches() func.

Body:
hasAnyMatches function takes the list of numbers and the condition closure so you can pass any closure which takes a Int and returns bool

let numbers = [20, 19, 7, 12]
let lessThan: (Int) -> Bool = { $0 < 10 }
let match = hasAnyMatches(list: numbers, condition: lessThan)
print(match)

Another way to write the same thing would be to use filters which iterates over a collection and return an Array containing only those elements that match an include condition. main advantage of using filter is its inbuilt and you don't need separate hasAnyMatches function to check the condition

let numbers = [20, 19, 7, 12]
let match = numbers.filter ({ $0 < 10 }).count > 0
print(match)


问:
Python tox and py.test: how to run just a single test rather than the whole test suite
I'm new to Django and testing so please bear with me.

Trying to run on the terminal a new test for code I developed in a Django project, but unfortunatly I inherited several test failures (already confirmed that by analyzing commits prior to mine). I'm trying to run/fix just my test/code. Not fix all the failling tests (at least not right now). Today we run the tests by just running tox in the main project folder, and tox ends up calling py.test, with a different database (in development/production we use Postgresql, but for tests we use SQLite). Here is the tox.ini configuration

```<code>[tox]
envlist = unit
skipsdist = True

[testenv:unit]
deps = -rrequirements/test.txt
commands =
    bash -c 'TESTING_DB=db.sqlite3 python manage.py initdb --settings telessaude.settings.test'
    py.test -n 4

passenv = *
setenv =
    DJANGO_SETTINGS_MODULE=telessaude.settings.test
whitelist_externals =
    /bin/bash

[flake8]
max-line-length = 110

[pytest]
setenv=
    DJANGO_SETTINGS_MODULE=telessaude.settings.test
python_files = **/tests.py **/tests/*.py **/tests.py
norecursedirs = requirements .tox media
</code>```

And here is my test, located at ~/project_name/servicos/tests.py

```<code># encoding: utf-8
from fluxos.tests import BaseFluxoTestCase
from core.tests import BaseTestCase
from servicos.models import Estomatologia

class EstomatologiaTestCase(BaseTestCase):

    def testa_formata_campos(self):
        estomato = Estomatologia()
        return_value = estomato.formata_campos()
        self.assertEquals(return_value['comorbidades_paciente'], '')

    ...
</code>```

What should I do with either tox or py.test to run just this newly created test? Thanks!

Update 1: Unfortunatly the suggested answers didn't worked. When I run a single test as suggested by phd and Windsooon, tox doesn't seem to be running any tests. I wrote a test that fails (on purpose) and when I run all tests with tox command, the error shows up:

```<code>    def test_formata_campos_para_estomatologia(self):
        estomatologia = Estomatologia()
        retorno = formata_campos(estomatologia)
>       self.assertIn('objetivos', retorno) E       AssertionError: 'objetivos' not found in {'comorbidades_paciente': '', 'tempo_transcorrido': '', 'sinais_e_sintomas_locais': ''}
</code>```

But when I run only the test individually, the test passes! I get this result:

```<code>tox -e py27 -- servicos.tests:FormatacaoDeCamposTestCase.test_formata_campos_para_estomatologia
py27 installed:
py27 runtests: PYTHONHASHSEED='3025337440'
______________________________________________________________ summary ______________________________________________________________
  py27: commands succeeded
  congratulations :)
</code>```

Digging around the internet, I found that I must have the {posargs} otherwise tox will ignore whatever I supply to it. However only the second line of my commands will use it. The first line will set the test database to SQLite (faster database set for testing). Can this be a bug on tox? Any idea on how to solve this?

Update 2: The answer from @phd was the closest one, but I had to adapt a few things:

Need to use 2 colon marks instead of one

Must use 2 colon marks instead of dot for separating method name from the class

Also had to drop the "-e" parameter, since that enviroment wasn't set on my tox.ini file.

Final command looks like this:

```<code>tox -- folder1/folder2/file_name.py::ClassName::test_method_name
</code>```

答:
You should prepare tox.ini to accept command line arguments and pass them to pytest:

```<code>[testenv:…]
commands =
    py.test -n 4 {posargs}
</code>```

After that you can pass as little or as many arguments:

```<code>tox -e $TOXENV -- test1.py test2.py…
</code>```

Body:
I'm new to Django and testing so please bear with me.

Trying to run on the terminal a new test for code I developed in a Django project, but unfortunatly I inherited several test failures (already confirmed that by analyzing commits prior to mine). I'm trying to run/fix just my test/code. Not fix all the failling tests (at least not right now). Today we run the tests by just running tox in the main project folder, and tox ends up calling py.test, with a different database (in development/production we use Postgresql, but for tests we use SQLite). Here is the tox.ini configuration

[tox]
envlist = unit
skipsdist = True

[testenv:unit]
deps = -rrequirements/test.txt
commands =
    bash -c 'TESTING_DB=db.sqlite3 python manage.py initdb --settings telessaude.settings.test'
    py.test -n 4

passenv = *
setenv =
    DJANGO_SETTINGS_MODULE=telessaude.settings.test
whitelist_externals =
    /bin/bash

[flake8]
max-line-length = 110

[pytest]
setenv=
    DJANGO_SETTINGS_MODULE=telessaude.settings.test
python_files = **/tests.py **/tests/*.py **/tests.py
norecursedirs = requirements .tox media

And here is my test, located at ~/project_name/servicos/tests.py

# encoding: utf-8
from fluxos.tests import BaseFluxoTestCase
from core.tests import BaseTestCase
from servicos.models import Estomatologia

class EstomatologiaTestCase(BaseTestCase):

    def testa_formata_campos(self):
        estomato = Estomatologia()
        return_value = estomato.formata_campos()
        self.assertEquals(return_value['comorbidades_paciente'], '')

    ...

What should I do with either tox or py.test to run just this newly created test? Thanks!

Update 1: Unfortunatly the suggested answers didn't worked. When I run a single test as suggested by phd and Windsooon, tox doesn't seem to be running any tests. I wrote a test that fails (on purpose) and when I run all tests with tox command, the error shows up:

    def test_formata_campos_para_estomatologia(self):
        estomatologia = Estomatologia()
        retorno = formata_campos(estomatologia)
>       self.assertIn('objetivos', retorno) E       AssertionError: 'objetivos' not found in {'comorbidades_paciente': '', 'tempo_transcorrido': '', 'sinais_e_sintomas_locais': ''}

But when I run only the test individually, the test passes! I get this result:

tox -e py27 -- servicos.tests:FormatacaoDeCamposTestCase.test_formata_campos_para_estomatologia
py27 installed:
py27 runtests: PYTHONHASHSEED='3025337440'
______________________________________________________________ summary ______________________________________________________________
  py27: commands succeeded
  congratulations :)

Digging around the internet, I found that I must have the {posargs} otherwise tox will ignore whatever I supply to it. However only the second line of my commands will use it. The first line will set the test database to SQLite (faster database set for testing). Can this be a bug on tox? Any idea on how to solve this?

Update 2: The answer from @phd was the closest one, but I had to adapt a few things:

Need to use 2 colon marks instead of one

Must use 2 colon marks instead of dot for separating method name from the class

Also had to drop the "-e" parameter, since that enviroment wasn't set on my tox.ini file.

Final command looks like this:

tox -- folder1/folder2/file_name.py::ClassName::test_method_name

Body:
You should prepare tox.ini to accept command line arguments and pass them to pytest:

[testenv:…]
commands =
    py.test -n 4 {posargs}

After that you can pass as little or as many arguments:

tox -e $TOXENV -- test1.py test2.py…


问:
Manipulating date format in hive
I have the date with 2 formats 2001-11-28T06:00:00.000Z and 10/20/09 in my Avro data  and I want to convert this to common format, How can we achieve this in  hive-0.10.0

I want to convert this to 2015-01-01 00:00:00 format

答:
Date functions in hive can be used

something like

CAST(FROM_UNIXTIME(UNIX_TIMESTAMP(column,'your-format'),"<desired-format>")AS STRING)

for more help look here Date Functions

Title: Manipulating date format in hive


问:
Syntax for Id'ing if Access DB was open by user or programmatically
I'm Looking for the syntax for Id'ing if Access DB was open by user or programmatically. I have seen it before and can't find it now. It was just a simple one line function that has a boolean output. Anyone know what I'm talking about?</p>

答:
Read into Application.UserControl (https://msdn.microsoft.com/VBA/Access-VBA/articles/application-usercontrol-property-access). It does exactly what you want.

Note that it isn't a ReadOnly property, and I tend to set it to true to make sure Access doesn't close when the program that opened it quit.


问:
Create a directory if it doesn't exist
In my app I want to copy a file to the other hard disk so this is my code:

```<code> #include <windows.h>

using namespace std;

int main(int argc, char* argv[] )
{
    string Input = "C:\\Emploi NAm.docx";
    string CopiedFile = "Emploi NAm.docx";
    string OutputFolder = "D:\\test";
    CopyFile(Input.c_str(), string(OutputFolder+CopiedFile).c_str(), TRUE);

    return 0;
}
</code>```

so after executing this, it shows me in the D:HDD a file testEmploi NAm.docx
but I want him to create the test folder if it doesn't exist.

I want to do that without using the Boost library.

答:
You can use cstdlib

Although- http://www.cplusplus.com/articles/j3wTURfi/

```<code>#include <cstdlib>

const int dir= system("mkdir -p foo");
if (dir< 0)
{
     return;
}
</code>```

you can also check if the directory exists already by using

```<code>#include <dirent.h>
</code>```

Title: Create a directory if it doesn't exist

Body:
In my app I want to copy a file to the other hard disk so this is my code:

 #include <windows.h>

using namespace std;

int main(int argc, char* argv[] )
{
    string Input = "C:\\Emploi NAm.docx";
    string CopiedFile = "Emploi NAm.docx";
    string OutputFolder = "D:\\test";
    CopyFile(Input.c_str(), string(OutputFolder+CopiedFile).c_str(), TRUE);

    return 0;
}

so after executing this, it shows me in the D:HDD a file testEmploi NAm.docx
but I want him to create the test folder if it doesn't exist.

I want to do that without using the Boost library.

Body:
You can use cstdlib

Although- http://www.cplusplus.com/articles/j3wTURfi/

#include <cstdlib>

const int dir= system("mkdir -p foo");
if (dir< 0)
{
     return;
}

you can also check if the directory exists already by using

#include <dirent.h>


问:
Grouping switch statement cases together?
I may be over looking something but is there a simple way in C++ to group cases together instead of writing them out individually? I remember in basic I could just do:

```<code>SELECT CASE Answer
CASE 1, 2, 3, 4
</code>```

Example in C++ (For those that need it):

```<code>#include <iostream.h>
#include <stdio.h>
int main()
{
   int Answer;
   cout << "How many cars do you have?";
   cin >> Answer;
   switch (Answer)
      {
      case 1:
      case 2:
      case 3:
      case 4:
         cout << "You need more cars. ";
         break;
      case 5:
      case 6:
      case 7:
      case 8:
         cout << "Now you need a house. ";
         break;
      default:
         cout << "What are you? A peace-loving hippie freak? ";
      }
      cout << "\nPress ENTER to continue... " << endl;
      getchar();
      return 0;
}
</code>```

答:
You can't remove keyword case. But  your example can be written shorter like this:

```<code>switch ((Answer - 1) / 4)
{
   case 0:
      cout << "You need more cars.";
      break;
   case 1:
      cout << "Now you need a house.";
      break;
   default:
      cout << "What are you? A peace-loving hippie freak?";
}
</code>```

Body:
I may be over looking something but is there a simple way in C++ to group cases together instead of writing them out individually? I remember in basic I could just do:

SELECT CASE Answer
CASE 1, 2, 3, 4

Example in C++ (For those that need it):

#include <iostream.h>
#include <stdio.h>
int main()
{
   int Answer;
   cout << "How many cars do you have?";
   cin >> Answer;
   switch (Answer)
      {
      case 1:
      case 2:
      case 3:
      case 4:
         cout << "You need more cars. ";
         break;
      case 5:
      case 6:
      case 7:
      case 8:
         cout << "Now you need a house. ";
         break;
      default:
         cout << "What are you? A peace-loving hippie freak? ";
      }
      cout << "\nPress ENTER to continue... " << endl;
      getchar();
      return 0;
}

Body:
You can't remove keyword case. But  your example can be written shorter like this:

switch ((Answer - 1) / 4)
{
   case 0:
      cout << "You need more cars.";
      break;
   case 1:
      cout << "Now you need a house.";
      break;
   default:
      cout << "What are you? A peace-loving hippie freak?";
}


问:
Aspect ratio constraint relative to the screen width
I have set a cell image to my UITableViewCell. It is a custom cell. I have set the aspect ratio as 1:1 and the width of the image view to 50. But for iphone 5 and 5s this size is too big as I feel. So how can I change the size of the UIImageView relative to the screen width.
Please help me.
Thanks

This is my current view

答:
There are at least 2 ways you could configure image size based on the screen size:

Size-Classes allows you to set different width constraint value based on Trait Variation: Compact or Regular. Just select the width constraint, click on the Plus button on the left of it's Constant value and add a new variation for the iPhone device screens.

Manual approach with Aspect Ration constraint. This way you should select both ImageView and cell's ContentView, create "Equal Width" constraint and change it's multiplier value. Start with a 1:5 value - looking good.


问:
Git: How to solve Permission denied (publickey) error when using Git?
I'm on Mac Snow Leopard and I just installed git.

I just tried

```<code>git clone git@thechaw.com:cakebook.git
</code>```

but that gives me this error:

```<code>Initialized empty Git repository in `/Users/username/Documents/cakebook/.git/`
Permission denied (publickey).
fatal: The remote end hung up unexpectedly
</code>```

What am I missing?

I've also tried doing ssh-keygen with no passphase but still same error.

答:
In my case, I have reinstalled ubuntu and the user name is changed from previous. In this case the the generated ssh key also differs from the previous one.

The issue solved by just copy the current ssh public key, in the repository. The key will be available in your user's /home/.ssh/id_rsa.pub

Body:
I'm on Mac Snow Leopard and I just installed git.

I just tried

git clone git@thechaw.com:cakebook.git

but that gives me this error:

Initialized empty Git repository in `/Users/username/Documents/cakebook/.git/`
Permission denied (publickey).
fatal: The remote end hung up unexpectedly

What am I missing?

I've also tried doing ssh-keygen with no passphase but still same error.


问:
How to set proxy host on HttpClient request in Java
I want to set proxy before sending HttpClient request on a URL. As I am able to connect it curl command setting up the proxy but with Java code I am not able to do that.

Curl command:

```<code>**curl -I -x IP:80  URL**
</code>```

Code change done in java file:

```<code>HttpClient client = new HttpClient();
System.getProperties().put("http.proxyHost", "someProxyURL");
System.getProperties().put("http.proxyPort", "someProxyPort");
EntityEnclosingMethod method = new PostMethod(url);
method.setRequestEntity(new StringRequestEntity(requestXML, "text/xml", "utf-8"));
</code>```

With above code changes in my java file I am getting below error :

```<code>java.net.ConnectException: Connection refused (Connection refused)
</code>```

Which shows that I am not able to connect that URL with the proxy I am trying to use to connect the URL.

答:
System properties usually have to be set right upfront, which means either in the jvm startup with
-Dhttp.proxyHost=some.host.com
-Dhttp.proxyPort=8080, not forgetting the httpsProxyHost and ...Port)

Or which should work, too, in a static {} block.

I personally find the Jersey client implementation easier to work with, if you have the option to switch.

Body:
I want to set proxy before sending HttpClient request on a URL. As I am able to connect it curl command setting up the proxy but with Java code I am not able to do that.

Curl command:

**curl -I -x IP:80  URL**

Code change done in java file:

HttpClient client = new HttpClient();
System.getProperties().put("http.proxyHost", "someProxyURL");
System.getProperties().put("http.proxyPort", "someProxyPort");
EntityEnclosingMethod method = new PostMethod(url);
method.setRequestEntity(new StringRequestEntity(requestXML, "text/xml", "utf-8"));

With above code changes in my java file I am getting below error :

java.net.ConnectException: Connection refused (Connection refused)

Which shows that I am not able to connect that URL with the proxy I am trying to use to connect the URL.


问:
qsort not working properly with long long
I am sorting a two dimensional array a[n][2], with respect to a[i][0],a[i+1][0] breaking ties with non-decreasing a[i][1],a[i+1][1].
qsort is working fine with integer array but not with long long array.

Integer array code

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>

int cmpfunc(const void* a, const void* b)
{
    int x = ((int*)a)[0] - ((int*)b)[0];
    if (x != 0) {
        return x;
    }
    return ((int*)a)[1] - ((int*)b)[1];
}

int main(int argc, char const* argv[])
{
    int n, i, j;
    scanf("%d", &n);
    int a[n][2];
    for (i = 0; i < n; i = i + 1) {
        scanf("%d %d", &a[i][0], &a[i][1]);
    }
    qsort(a, n, sizeof(a[0]), cmpfunc);
    for (i = 0; i < n; i = i + 1) {
        printf("%d %d\n", a[i][0], a[i][1]);
    }
    return 0;
}
</code>```

long long array code

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>

int cmpfunc(const void* a, const void* b)
{
    int x = ((int*)a)[0] - ((int*)b)[0];
    if (x != 0) {
        return x;
    }
    return ((int*)a)[1] - ((int*)b)[1];
}

int main(int argc, char const* argv[])
{
    int n, i, j;
    scanf("%d", &n);
    long long a[n][2];
    for (i = 0; i < n; i = i + 1) {
        scanf("%I64d %I64d", &a[i][0], &a[i][1]);
    }
    qsort(a, n, sizeof(a[0]), cmpfunc);
    for (i = 0; i < n; i = i + 1) {
        printf("%I64d %I64d\n", a[i][0], a[i][1]);
    }
    return 0;
}
</code>```

Input:

```<code>5
4 3
4 2
4 1
4 1
4 1
</code>```

Output for first code:

```<code>4 1
4 1
4 1
4 2
4 3
</code>```

Output for second code:

```<code>4 2
4 1
4 1
4 1
4 3
</code>```

答:
You actually have two issues: The first is the one with the invalid casting. The second is also about the invalid casting but for another reason.

As stated in one of my comments the qsort function passes pointers to the elements to the comparison function. If you haven an array arr then qsort will use something like &arr[0] for the arguments. That means if the data of the array is itself arrays then the arguments will be pointers to arrays. In your specific case the argument types are really long long (*)[2], not only long long *.

So the comparison function should look something like this instead:

```<code>int cmpfunc(const void* a_, const void* b_)
{
    long long (*a)[2] = (long long (*)[2]) a_;
    long long (*b)[2] = (long long (*)[2]) b_;

    long long result;

    if ((*a)[0] - (*b)[0] != 0)
        result = (*a)[0] - (*b)[0];
    else
        result = (*a)[1] - (*b)[1];

    if (result < 0)
        return -1;
    else if (result > 0)
        return 1;
    else
        return 0;
}
</code>```

Body:
I am sorting a two dimensional array a[n][2], with respect to a[i][0],a[i+1][0] breaking ties with non-decreasing a[i][1],a[i+1][1].
qsort is working fine with integer array but not with long long array.

Integer array code

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>

int cmpfunc(const void* a, const void* b)
{
    int x = ((int*)a)[0] - ((int*)b)[0];
    if (x != 0) {
        return x;
    }
    return ((int*)a)[1] - ((int*)b)[1];
}

int main(int argc, char const* argv[])
{
    int n, i, j;
    scanf("%d", &n);
    int a[n][2];
    for (i = 0; i < n; i = i + 1) {
        scanf("%d %d", &a[i][0], &a[i][1]);
    }
    qsort(a, n, sizeof(a[0]), cmpfunc);
    for (i = 0; i < n; i = i + 1) {
        printf("%d %d\n", a[i][0], a[i][1]);
    }
    return 0;
}

long long array code

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>

int cmpfunc(const void* a, const void* b)
{
    int x = ((int*)a)[0] - ((int*)b)[0];
    if (x != 0) {
        return x;
    }
    return ((int*)a)[1] - ((int*)b)[1];
}

int main(int argc, char const* argv[])
{
    int n, i, j;
    scanf("%d", &n);
    long long a[n][2];
    for (i = 0; i < n; i = i + 1) {
        scanf("%I64d %I64d", &a[i][0], &a[i][1]);
    }
    qsort(a, n, sizeof(a[0]), cmpfunc);
    for (i = 0; i < n; i = i + 1) {
        printf("%I64d %I64d\n", a[i][0], a[i][1]);
    }
    return 0;
}

Input:

5
4 3
4 2
4 1
4 1
4 1

Output for first code:

4 1
4 1
4 1
4 2
4 3

Output for second code:

4 2
4 1
4 1
4 1
4 3

Body:
You actually have two issues: The first is the one with the invalid casting. The second is also about the invalid casting but for another reason.

As stated in one of my comments the qsort function passes pointers to the elements to the comparison function. If you haven an array arr then qsort will use something like &arr[0] for the arguments. That means if the data of the array is itself arrays then the arguments will be pointers to arrays. In your specific case the argument types are really long long (*)[2], not only long long *.

So the comparison function should look something like this instead:

int cmpfunc(const void* a_, const void* b_)
{
    long long (*a)[2] = (long long (*)[2]) a_;
    long long (*b)[2] = (long long (*)[2]) b_;

    long long result;

    if ((*a)[0] - (*b)[0] != 0)
        result = (*a)[0] - (*b)[0];
    else
        result = (*a)[1] - (*b)[1];

    if (result < 0)
        return -1;
    else if (result > 0)
        return 1;
    else
        return 0;
}


问:
What is the compile-time type of the "throw" expression in C# 7?
In C# 7 it is possible to raise an exception inside an expression:

```<code>int n = list != null ? list.Count : throw new NullReferenceException("list");
</code>```

In this position, the throw expression can substitute an expression of any type.

Now I want to define a function that executes some action before raising an exception:

```<code>??? DoSomethingAndThrowException(Exception e)
{
    MessageBox.Show("Prepare for an exception!");
    throw e;
}
</code>```

What would be the return type of such function, so that it can be used in the same places as the original throw expression:

```<code>int n = list != null ? list.Count : DoSomethingAndThrowException(new NullReferenceException("list"));
</code>```

There's the option to declare it as a generic method:

```<code>T DoSomethingAndThrowException<T>(Exception e) {...}
</code>```

But this seems cumbersome, as the generic type doesn't occur anywhere in the function body. Is this the only way to do it, or is there some type I don't know of, and which is assignable to any type (an "anti-object" type, so to speak)?

答:
There is a solution that allows you to keep your pattern. The only change is that you throw your method, instead of throwing inside of the method. Don't overthink things!

```<code>private static Exception DoSomethingAndReturnException(Exception exception)
{
  // Do something

  // in the end, return the exception
  return exception;
}
</code>```

You can use it like this:

```<code>int n = (list != null) ? list.Count : throw DoSomethingAndReturnException(new NullReferenceException("list"));
</code>```

Body:
In C# 7 it is possible to raise an exception inside an expression:

int n = list != null ? list.Count : throw new NullReferenceException("list");

In this position, the throw expression can substitute an expression of any type.

Now I want to define a function that executes some action before raising an exception:

??? DoSomethingAndThrowException(Exception e)
{
    MessageBox.Show("Prepare for an exception!");
    throw e;
}

What would be the return type of such function, so that it can be used in the same places as the original throw expression:

int n = list != null ? list.Count : DoSomethingAndThrowException(new NullReferenceException("list"));

There's the option to declare it as a generic method:

T DoSomethingAndThrowException<T>(Exception e) {...}

But this seems cumbersome, as the generic type doesn't occur anywhere in the function body. Is this the only way to do it, or is there some type I don't know of, and which is assignable to any type (an "anti-object" type, so to speak)?

Body:
There is a solution that allows you to keep your pattern. The only change is that you throw your method, instead of throwing inside of the method. Don't overthink things!

private static Exception DoSomethingAndReturnException(Exception exception)
{
  // Do something

  // in the end, return the exception
  return exception;
}

You can use it like this:

int n = (list != null) ? list.Count : throw DoSomethingAndReturnException(new NullReferenceException("list"));


问:
Hidden checkout field Woocommerce for current user
I would like to collect and save Wordpress profile photo of the current user who submits checkout form in Woocommerce. I would achieve this with hidden checkout field. Here is what I have so far. Not sure how to get profile photo of the current user and output hidden photo :</p>

```<code>  add_action( 'woocommerce_after_order_notes', 'my_custom_checkout_hidden_field', 10, 1 );
    function my_custom_checkout_hidden_field( $checkout ) {

        // Get an instance of the current user object
        $user = wp_get_current_user();

       // Profile photo

       // Output hidden photo

}
</code>```

答:
All you need to do is pass the current users email address into the get_avatar() function.

```<code><?php

$current_user = wp_get_current_user();

if ( ($current_user instanceof WP_User) ) {
    echo get_avatar( $current_user->user_email, 32 );
}

?>
</code>```

Here are some links for specifics:

get_avatar();
wp_get_current_user();

To output the profile picture

```<code><?php

echo '<img src="'. get_the_author_meta( 'user_custom_avatar', $current_user->ID, 32 ) .'" />';

?>
</code>```

Body:
I would like to collect and save Wordpress profile photo of the current user who submits checkout form in Woocommerce. I would achieve this with hidden checkout field. Here is what I have so far. Not sure how to get profile photo of the current user and output hidden photo :

  add_action( 'woocommerce_after_order_notes', 'my_custom_checkout_hidden_field', 10, 1 );
    function my_custom_checkout_hidden_field( $checkout ) {

        // Get an instance of the current user object
        $user = wp_get_current_user();

       // Profile photo

       // Output hidden photo

}

Body:
All you need to do is pass the current users email address into the get_avatar() function.

<?php

$current_user = wp_get_current_user();

if ( ($current_user instanceof WP_User) ) {
    echo get_avatar( $current_user->user_email, 32 );
}

?>

Here are some links for specifics:

get_avatar();
wp_get_current_user();

To output the profile picture

<?php

echo '<img src="'. get_the_author_meta( 'user_custom_avatar', $current_user->ID, 32 ) .'" />';

?>