问:
Install RVM in a specific location
Installing RVM with command below gets installed to ${HOME}/.rvm. Instead, I'm looking for a way to specify the location where .rvm directory gets created so that I can control where RVM is installed.

```<code>curl -sSL https://get.rvm.io | bash
</code>```

Is there a way to specify this while installing RVM?

答:
Yes, by creating a symlink from ~/.rvm to $TARGET_DIR and before installing rvm. In this example I am using a directory called 'myrvm':

```<code>    ln -sf myrvm/ ~/.rvm
</code>```

Then when I check the contents of 'myrvm', I see rvm is installed there. RVM still works seemlessly

Title: Install RVM in a specific location

Body:
Installing RVM with command below gets installed to ${HOME}/.rvm. Instead, I'm looking for a way to specify the location where .rvm directory gets created so that I can control where RVM is installed.

curl -sSL https://get.rvm.io | bash

Is there a way to specify this while installing RVM?

Body:
Yes, by creating a symlink from ~/.rvm to $TARGET_DIR and before installing rvm. In this example I am using a directory called 'myrvm':

    ln -sf myrvm/ ~/.rvm

Then when I check the contents of 'myrvm', I see rvm is installed there. RVM still works seemlessly


来源: stackexchange

问:
stripe api: multiple plans / subscriptions, single invoice
I've been reading through the docs all day and am having a hard time understanding if this is possible.

What I want is to subscribe a user to multiple plans and have it charged on a single invoice, with recurring payments monthly from when the invoice was originally billed.

In the docs it says:

"Note that multiple subscriptions on a customer results in a separate billing cycle, invoice, and charge for each subscription, even if the plans have the same billing interval and the subscriptions are created at the same time."

Which is not promising

But then the api explicitly allows for creating invoices with multiple items through the InvoiceItems api. It seems this is mostly for custom/unique actions on the customer, like applying discounts or one off charges outside of the regular subscription cycle.

I suppose I could manually keep track of billing cycles and manually create multi-item invoices, but I would much rather have this automated through Stripe.

Is this possible?

答:
What you are describing is now supported in the Stripe API: https://stripe.com/docs/subscriptions/multiplan. The idea is to add multiple plans to a subscription, a restriction being that all plans must share the same interval.</p>

```<code>// Set your secret key: remember to change this to your live secret key in production
// See your keys here: https://dashboard.stripe.com/account/apikeys
var stripe = require("stripe")("xxxxxxxxxxxxxxx");

stripe.subscriptions.create({
  customer: "cus_91elFtZU3tt11g",
  items: [
    {
      plan: "basic-monthly",
    },
    {
      plan: "additional-license",
      quantity: 2,
    },
  ]
}, function(err, subscription) {
  // asynchronously called
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
What you are describing is now supported in the Stripe API: https://stripe.com/docs/subscriptions/multiplan. The idea is to add multiple plans to a subscription, a restriction being that all plans must share the same interval.

// Set your secret key: remember to change this to your live secret key in production
// See your keys here: https://dashboard.stripe.com/account/apikeys
var stripe = require("stripe")("xxxxxxxxxxxxxxx");

stripe.subscriptions.create({
  customer: "cus_91elFtZU3tt11g",
  items: [
    {
      plan: "basic-monthly",
    },
    {
      plan: "additional-license",
      quantity: 2,
    },
  ]
}, function(err, subscription) {
  // asynchronously called
});

ContentLicense: CC BY-SA 4.0


问:
separators of thousands in angular 2
i have tried this one in my proyect:

```<code><div padding *ngIf="TotalAPagar">
    $ {{TotalAPagar | number }}
</div>
</code>```

my variable is called TotalAPagar, and I'm using number pipe, but it shows the value like this 1,000,500.

I need that to change the numbering convention to dots. Eg. 1.000.000

I have been reading about in the docs in angular but doesn't have any example.

答:
I think that there are two ways to resolve this problem:

1. You can trying overwrite DecimalPipe from @angular/common library:

In this way:

point-replacer.pipe.ts

```<code>import { Pipe } from '@angular/core';
import {DecimalPipe} from "@angular/common";

@Pipe({
    name: 'pointReplacer'
})
export class PointReplacerPipe extends DecimalPipe {

  transform(value: any, digits?: string): string {
        return super.transform(value, digits).replace(',', '.');

    }
}
</code>```

and in your html code:

```<code><div padding *ngIf="TotalAPagar">
    $ {{TotalAPagar | pointReplacer }}
</div>
</code>```

2. You can write your own pipe, which replaces characters and use **double pipe in your html code**

Try in this way:

point-replacer.pipe.ts

```<code>import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'pointReplacer'
})

export class PointReplacerPipe implements PipeTransform {
    transform(value: string, args: any[]): string {
        if(value) {
          return value.replace(',', '.');
        }
        return '';
    }
}
</code>```

and in your html code:

```<code><div padding *ngIf="TotalAPagar">
    $ {{TotalAPagar | number | pointReplacer }}
</div>
</code>```

No matter which method you choose, don't forget to declare your own pipe in module, where you use it:

```<code>@NgModule({
  declarations: [PointReplacerPipe],
  providers: [PointReplacerPipe]
})
</code>```

Title: separators of thousands in angular 2

Body:
i have tried this one in my proyect:

    $ {{TotalAPagar | number }}

my variable is called TotalAPagar, and I'm using number pipe, but it shows the value like this 1,000,500.

I need that to change the numbering convention to dots. Eg. 1.000.000

I have been reading about in the docs in angular but doesn't have any example.

Body:
I think that there are two ways to resolve this problem:

1. You can trying overwrite DecimalPipe from @angular/common library:

In this way:

point-replacer.pipe.ts

import { Pipe } from '@angular/core';
import {DecimalPipe} from "@angular/common";

@Pipe({
    name: 'pointReplacer'
})
export class PointReplacerPipe extends DecimalPipe {

  transform(value: any, digits?: string): string {
        return super.transform(value, digits).replace(',', '.');

    }
}

and in your html code:

<div padding *ngIf="TotalAPagar">
    $ {{TotalAPagar | pointReplacer }}
</div>

2. You can write your own pipe, which replaces characters and use **double pipe in your html code**

Try in this way:

point-replacer.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'pointReplacer'
})

export class PointReplacerPipe implements PipeTransform {
    transform(value: string, args: any[]): string {
        if(value) {
          return value.replace(',', '.');
        }
        return '';
    }
}

and in your html code:

<div padding *ngIf="TotalAPagar">
    $ {{TotalAPagar | number | pointReplacer }}
</div>

No matter which method you choose, don't forget to declare your own pipe in module, where you use it:

@NgModule({
  declarations: [PointReplacerPipe],
  providers: [PointReplacerPipe]
})


问:
neo4j/Cypher toString() collection
I created a simple graph model for hospitals. I am playing around with hiearchical trees in neo4j, so I created a multilevel location tree in graph.

Now I want to get GPS using apoc.spatial functions. Lets say that first 3 levels of locations are good enough for retrieving latitude and longitude. My query looks like this.

```<code>MATCH (h:Hospital)-[:IS_IN*..3]->(location)
CALL apoc.spatial.geocodeOnce(toString(collect(location.name))) YIELD location
set h += location
</code>```

But this returns error since it does not support toString collections i guess.

Expected a String, Number or Boolean, got: Vector(550 OSBORNE ROAD,
  55432, FRIDLEY)

What is the simplest way to achieve this to work ?

答:
This should work</p>

```<code>RETURN substring(reduce(s="", name in collect(location.name) | s + "," + name),1)
</code>```

Title: neo4j/Cypher toString() collection

Body:
I created a simple graph model for hospitals. I am playing around with hiearchical trees in neo4j, so I created a multilevel location tree in graph.

Now I want to get GPS using apoc.spatial functions. Lets say that first 3 levels of locations are good enough for retrieving latitude and longitude. My query looks like this.

MATCH (h:Hospital)-[:IS_IN*..3]->(location)
CALL apoc.spatial.geocodeOnce(toString(collect(location.name))) YIELD location
set h += location

But this returns error since it does not support toString collections i guess.

Expected a String, Number or Boolean, got: Vector(550 OSBORNE ROAD,
  55432, FRIDLEY)

What is the simplest way to achieve this to work ?

Body:
This should work

RETURN substring(reduce(s="", name in collect(location.name) | s + "," + name),1)


问:
jQuery multiple target IDs for click function
This may be a little redundant but I was wondering if there's a way to improve the code by shortening it to avoid repetition.

```<code>$('a[href*="#about"]').click(function()
</code>```

I want to target #about #products #process #gallery #contact

I want to avoid:

```<code>$('a[href*="#about"]', 'a[href*="#process"]', a[href*="#etc"]' ).click(function()
</code>```

答:
Give them all a class and target that:

```<code>$(".the-class").click(function() {
    // ...
});
</code>```

If you can't do that, then what you want to avoid (but done correctly) is what you need to do:

```<code>$("[href=#about], [href=#products], [href=#process], [href=#gallery], [href=#contact]").click(function() {
    // ...
});
</code>```

Body:
This may be a little redundant but I was wondering if there's a way to improve the code by shortening it to avoid repetition.

$('a[href*="#about"]').click(function()

I want to target #about #products #process #gallery #contact

I want to avoid:

$('a[href*="#about"]', 'a[href*="#process"]', a[href*="#etc"]' ).click(function()

Body:
Give them all a class and target that:

$(".the-class").click(function() {
    // ...
});

If you can't do that, then what you want to avoid (but done correctly) is what you need to do:

$("[href=#about], [href=#products], [href=#process], [href=#gallery], [href=#contact]").click(function() {
    // ...
});


问:
How to open cd drive java
Is there a code, I can use that will (once I run it), physically open the cd/dvd drive? I know this is possible in some other languages, but is it possible in Java? Please point me in the correct direction. Thank you</p>

答:
The code to open a CD drive can be even simpler than meain's answer.
The .exe file does not need to be copied. It can be run from a command line inside the program :

Runtime.getRuntime().exec("nircmd cdrom open d:");

It should execute and find the nircmd.exe file automatically in the system bin.

Title: How to open cd drive java


问:
Ascensor.js Dynamically change movement direction (queued)
I'm using Ascensor.js.

I build with this queued option:

```<code>var ascensor = $('#ascensor').ascensor({
    direction: [[2, 2], [1, 1], [1, 2], [1, 3], [1, 4], [3, 1], [3, 2], [3, 3]],
    queued: "y"
});
</code>```

After arrive to a floor, I need to chage queued to "x", to go back the same way. This is possible?

thanks a lot

答:
I found the solution.

ascensorInstance.options.queued = "x";`
```

I hope this help.

Body:
I'm using Ascensor.js.

I build with this queued option:

var ascensor = $('#ascensor').ascensor({
    direction: [[2, 2], [1, 1], [1, 2], [1, 3], [1, 4], [3, 1], [3, 2], [3, 3]],
    queued: "y"
});

After arrive to a floor, I need to chage queued to "x", to go back the same way. This is possible?

thanks a lot

Body:
I found the solution.

ascensorInstance.options.queued = "x";`

I hope this help.


问:
add css to hover menu parent but not child
Im trying to do something similar to this: CSS Menu - Keep parent hovered while focus on submenu
im using !important to override bootstrap colors
it works for the parent but i dont want the child li>a to be effected

.hover-li:hover a{

```<code>color: blue !important;
}

.hover-li ul li  {
    color: white !important;
}
</code>```

the structure is like this:

```<code><li class = "hover-li">
<a></a>
<ul>
<li><a></a></li>
<li><a></a></li>
<li><a></a></li>
</ul>
</li>
</code>```

答:
Try this

```<code>.hover-li:hover > a {
  color: blue !important;
}
</code>```

it only affects direct children

Body:
Im trying to do something similar to this: CSS Menu - Keep parent hovered while focus on submenu
im using !important to override bootstrap colors
it works for the parent but i dont want the child li>a to be effected

.hover-li:hover a{

color: blue !important;
}

.hover-li ul li  {
    color: white !important;
}

the structure is like this:

Body:
Try this

.hover-li:hover > a {
  color: blue !important;
}

it only affects direct children


问:
compute sum of columns in a nested list in R
How do we do column sums on elements of nested lists. I have a nested list of 10  each containing a sublist of 50 elements which are matrices with 4 columns with differing number of rows. Here is a simpler example. I need to add the columns across the lists. I need a vector of colsums.ll<-c(26, 66, 106, 146). I tried to do do.call("rbind",ll) to collapse the list into 1 dataframe and then apply colSums but was not successful. </p>

```<code>    l1<-matrix(c(1:8),nrow=2)
    l2<-matrix(c(1:16),nrow=4)
    l<-list(l1,l2)
    ll<-list(l,l)
     ll
    [[1]]
   [[1]][[1]]
        [,1] [,2] [,3] [,4]
  [1,]    1    3    5    7
  [2,]    2    4    6    8

   [[1]][[2]]
         [,1] [,2] [,3] [,4]
    [1,]    1    5    9   13
    [2,]    2    6   10   14
    [3,]    3    7   11   15
    [4,]    4    8   12   16

    [[2]]
    [[2]][[1]]
         [,1] [,2] [,3] [,4]
    [1,]    1    3    5    7
    [2,]    2    4    6    8

    [[2]][[2]]
        [,1] [,2] [,3] [,4]
    [1,]    1    5    9   13
    [2,]    2    6   10   14
    [3,]    3    7   11   15
    [4,]    4    8   12   16
</code>```

答:
I like Reduce in base R, so you could do:

```<code>Reduce("+", lapply(Reduce(c, ll), colSums))
# [1]  26  66 106 146
</code>```

BENCHMARKING

```<code>set.seed(100)
l1 <- matrix(sample(100, 100000, replace = TRUE),ncol=1000)
l2 <- matrix(sample(100, 1000000, replace = TRUE),ncol=1000)
l <- list(l1,l2)
ll <- rep(list(l), 100)
str(ll)
# List of 100
 # $ :List of 2
  # ..$ : int [1:100, 1:1000] 31 26 56 6 47 49 82 38 55 18 ...
  # ..$ : int [1:1000, 1:1000] 45 22 77 7 85 32 80 71 52 38 ...
 # $ :List of 2
  # ..$ : int [1:100, 1:1000] 31 26 56 6 47 49 82 38 55 18 ...
  # ..$ : int [1:1000, 1:1000] 45 22 77 7 85 32 80 71 52 38 ...
 # $ :List of 2
  # ..$ : int [1:100, 1:1000] 31 26 56 6 47 49 82 38 55 18 ...
  # ..$ : int [1:1000, 1:1000] 45 22 77 7 85 32 80 71 52 38 ...
 # $ :List of 2
  # ..$ : int [1:100, 1:1000] 31 26 56 6 47 49 82 38 55 18 ...
  # ..$ : int [1:1000, 1:1000] 45 22 77 7 85 32 80 71 52 38 ...
</code>```

```<code>library(purrr)
library(microbenchmark)
library(magrittr)

f_G.Grothendieck1 <- function(ll) rowSums(sapply(do.call(c, ll), colSums))
f_G.Grothendieck2 <- function(ll) colSums(do.call(rbind, do.call(c, ll)))
f_G.Grothendieck3 <- function(ll)
    ll %>% do.call(what = c) %>% sapply(colSums) %>% rowSums
f_G.Grothendieck4 <- function(ll)
    ll %>% do.call(what = c) %>% do.call(what = rbind) %>% colSums
f_d.b <- function(ll)
  colSums(do.call(rbind, lapply(lapply(rapply(ll, enquote, how="unlist"), eval), colSums)))
f_alistaire1 <- function(ll) ll %>% flatten() %>%  map(colSums) %>%  reduce(`+`)
f_alistaire2 <- function(ll) ll %>% flatten() %>% invoke(rbind, .) %>% colSums()
f_989 <- function(ll) Reduce("+", lapply(Reduce(c, ll), colSums))

r <- f_G.Grothendieck1(ll)
# [1] TRUE
all(r == f_G.Grothendieck2(ll))
# [1] TRUE
all(r == f_G.Grothendieck3(ll))
# [1] TRUE
all(r == f_G.Grothendieck4(ll))
# [1] TRUE
all(r == f_d.b(ll))
# [1] TRUE
all(r == f_alistaire1(ll))
# [1] TRUE
all(r == f_alistaire2(ll))
# [1] TRUE
all(r == f_989(ll))
# [1] TRUE
res <- microbenchmark(
f_G.Grothendieck1(ll), f_G.Grothendieck2(ll), f_G.Grothendieck3(ll),
f_G.Grothendieck4(ll), f_d.b(ll), f_alistaire1(ll), f_alistaire2(ll), f_989(ll))
</code>```

```<code>print(res, order="mean")
    # Unit: milliseconds
                      # expr        min         lq       mean     median         uq        max neval
                 # f_989(ll)   84.67007   87.05084   87.50351   87.70766   88.25692   91.12715   100
          # f_alistaire1(ll)   85.00209   87.35116   87.83935   87.91318   88.32242   98.69927   100
                 # f_d.b(ll)   85.15563   87.74943   88.01660   88.23258   88.72280   89.89943   100
     # f_G.Grothendieck1(ll)   85.38729   87.77707   88.40864   88.45328   89.03604  100.78963   100
     # f_G.Grothendieck3(ll)   85.85933   87.85805   88.69445   88.68118   89.28618  104.93881   100
     # f_G.Grothendieck4(ll) 1150.27718 1200.80601 1205.76164 1206.48442 1211.72250 1310.64802   100
          # f_alistaire2(ll) 1178.14509 1202.61153 1207.05208 1205.89009 1211.49820 1325.72315   100
     # f_G.Grothendieck2(ll) 1177.02283 1204.55166 1210.40954 1208.95338 1213.82218 1278.82715   100
</code>```

Body:
How do we do column sums on elements of nested lists. I have a nested list of 10  each containing a sublist of 50 elements which are matrices with 4 columns with differing number of rows. Here is a simpler example. I need to add the columns across the lists. I need a vector of colsums.ll<-c(26, 66, 106, 146). I tried to do do.call("rbind",ll) to collapse the list into 1 dataframe and then apply colSums but was not successful.

    l1<-matrix(c(1:8),nrow=2)
    l2<-matrix(c(1:16),nrow=4)
    l<-list(l1,l2)
    ll<-list(l,l)
     ll
    [[1]]
   [[1]][[1]]
        [,1] [,2] [,3] [,4]
  [1,]    1    3    5    7
  [2,]    2    4    6    8

   [[1]][[2]]
         [,1] [,2] [,3] [,4]
    [1,]    1    5    9   13
    [2,]    2    6   10   14
    [3,]    3    7   11   15
    [4,]    4    8   12   16

    [[2]]
    [[2]][[1]]
         [,1] [,2] [,3] [,4]
    [1,]    1    3    5    7
    [2,]    2    4    6    8

    [[2]][[2]]
        [,1] [,2] [,3] [,4]
    [1,]    1    5    9   13
    [2,]    2    6   10   14
    [3,]    3    7   11   15
    [4,]    4    8   12   16

Body:
I like Reduce in base R, so you could do:

Reduce("+", lapply(Reduce(c, ll), colSums))
# [1]  26  66 106 146

BENCHMARKING

set.seed(100)
l1 <- matrix(sample(100, 100000, replace = TRUE),ncol=1000)
l2 <- matrix(sample(100, 1000000, replace = TRUE),ncol=1000)
l <- list(l1,l2)
ll <- rep(list(l), 100)
str(ll)
# List of 100
 # $ :List of 2
  # ..$ : int [1:100, 1:1000] 31 26 56 6 47 49 82 38 55 18 ...
  # ..$ : int [1:1000, 1:1000] 45 22 77 7 85 32 80 71 52 38 ...
 # $ :List of 2
  # ..$ : int [1:100, 1:1000] 31 26 56 6 47 49 82 38 55 18 ...
  # ..$ : int [1:1000, 1:1000] 45 22 77 7 85 32 80 71 52 38 ...
 # $ :List of 2
  # ..$ : int [1:100, 1:1000] 31 26 56 6 47 49 82 38 55 18 ...
  # ..$ : int [1:1000, 1:1000] 45 22 77 7 85 32 80 71 52 38 ...
 # $ :List of 2
  # ..$ : int [1:100, 1:1000] 31 26 56 6 47 49 82 38 55 18 ...
  # ..$ : int [1:1000, 1:1000] 45 22 77 7 85 32 80 71 52 38 ...

library(purrr)
library(microbenchmark)
library(magrittr)

f_G.Grothendieck1 <- function(ll) rowSums(sapply(do.call(c, ll), colSums))
f_G.Grothendieck2 <- function(ll) colSums(do.call(rbind, do.call(c, ll)))
f_G.Grothendieck3 <- function(ll)
    ll %>% do.call(what = c) %>% sapply(colSums) %>% rowSums
f_G.Grothendieck4 <- function(ll)
    ll %>% do.call(what = c) %>% do.call(what = rbind) %>% colSums
f_d.b <- function(ll)
  colSums(do.call(rbind, lapply(lapply(rapply(ll, enquote, how="unlist"), eval), colSums)))
f_alistaire1 <- function(ll) ll %>% flatten() %>%  map(colSums) %>%  reduce(`+`)
f_alistaire2 <- function(ll) ll %>% flatten() %>% invoke(rbind, .) %>% colSums()
f_989 <- function(ll) Reduce("+", lapply(Reduce(c, ll), colSums))

r <- f_G.Grothendieck1(ll)
# [1] TRUE
all(r == f_G.Grothendieck2(ll))
# [1] TRUE
all(r == f_G.Grothendieck3(ll))
# [1] TRUE
all(r == f_G.Grothendieck4(ll))
# [1] TRUE
all(r == f_d.b(ll))
# [1] TRUE
all(r == f_alistaire1(ll))
# [1] TRUE
all(r == f_alistaire2(ll))
# [1] TRUE
all(r == f_989(ll))
# [1] TRUE
res <- microbenchmark(
f_G.Grothendieck1(ll), f_G.Grothendieck2(ll), f_G.Grothendieck3(ll),
f_G.Grothendieck4(ll), f_d.b(ll), f_alistaire1(ll), f_alistaire2(ll), f_989(ll))

print(res, order="mean")
    # Unit: milliseconds
                      # expr        min         lq       mean     median         uq        max neval
                 # f_989(ll)   84.67007   87.05084   87.50351   87.70766   88.25692   91.12715   100
          # f_alistaire1(ll)   85.00209   87.35116   87.83935   87.91318   88.32242   98.69927   100
                 # f_d.b(ll)   85.15563   87.74943   88.01660   88.23258   88.72280   89.89943   100
     # f_G.Grothendieck1(ll)   85.38729   87.77707   88.40864   88.45328   89.03604  100.78963   100
     # f_G.Grothendieck3(ll)   85.85933   87.85805   88.69445   88.68118   89.28618  104.93881   100
     # f_G.Grothendieck4(ll) 1150.27718 1200.80601 1205.76164 1206.48442 1211.72250 1310.64802   100
          # f_alistaire2(ll) 1178.14509 1202.61153 1207.05208 1205.89009 1211.49820 1325.72315   100
     # f_G.Grothendieck2(ll) 1177.02283 1204.55166 1210.40954 1208.95338 1213.82218 1278.82715   100


问:
How to import user-defined python modules in cygwin?
This might be trivial, but I can't identify the reason for not being able to import user-defined python modules into my python environment. I use Ananconda installation of python in cygwin. I have made entries in bash_profile to append module directory path to PYTHONPATH in this format.

export PYTHONPATH=$PYTHONPATH:"<dirpath>"

dirpath starts with /cygdrive/c/Users/

I have an __init__.py file available in the module directory to identify it is a python package.

Kindly provide your inputs. Thanks.

答: Python at the startup builds the sys.path using site.py available in the PYTHONHOME directory. I appended to the file, addsitedir(). That worked for me. If there exists a space in the path, use double quotes around the path.</p>


问:
MFMailComposeViewController view does not dismiss 2nd time
I have what I believe is a unique problem. I am having trouble getting my email window to dismiss. I am using Xcode 8.

The email dismisses correctly the first time I open it, but if I open it again it won't. If I press "Cancel" it does not give me the option to "Delete Draft". If I press "Send" the email is sent, but the window does not dismiss.

My code is below. The mailComposeController gets called correctly the first time, but it never gets called a second time. Does anyone have any ideas about what I am missing?

```<code>let mail = MFMailComposeViewController()
func sendEmail(body: String, subject: String) {
    if MFMailComposeViewController.canSendMail() {
        mail.mailComposeDelegate = self

        mail.setSubject(subject)
        mail.setMessageBody("\(body)", isHTML: false)

        if let data = (body as NSString).data(using: String.Encoding.utf8.rawValue){
            //Attach File
            mail.addAttachmentData(data, mimeType: "text/plain", fileName: "data.txt")
        }

        present(mail, animated: true)
    } else {
        // show failure alert
    }
}

func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
    controller.dismiss(animated: true, completion: nil)
}
</code>```

答:
You need to create a new MFMailComposeViewController each time. Moving your mail declaration inside sendEmail works…

```<code>func sendEmail(body: String, subject: String) {
    if MFMailComposeViewController.canSendMail() {

       // Create a new MFMailComposeViewController…
       let mail = MFMailComposeViewController()

        mail.mailComposeDelegate = self

        mail.setSubject(subject)
        mail.setMessageBody("\(body)", isHTML: false)

        if let data = (body as NSString).data(using: String.Encoding.utf8.rawValue){
            //Attach File
            mail.addAttachmentData(data, mimeType: "text/plain", fileName: "data.txt")
        }

        present(mail, animated: true)
    } else {
        // show failure alert
    }
}
</code>```

As to why…?

Body:
I have what I believe is a unique problem. I am having trouble getting my email window to dismiss. I am using Xcode 8.

The email dismisses correctly the first time I open it, but if I open it again it won't. If I press "Cancel" it does not give me the option to "Delete Draft". If I press "Send" the email is sent, but the window does not dismiss.

My code is below. The mailComposeController gets called correctly the first time, but it never gets called a second time. Does anyone have any ideas about what I am missing?

let mail = MFMailComposeViewController()
func sendEmail(body: String, subject: String) {
    if MFMailComposeViewController.canSendMail() {
        mail.mailComposeDelegate = self

        mail.setSubject(subject)
        mail.setMessageBody("\(body)", isHTML: false)

        if let data = (body as NSString).data(using: String.Encoding.utf8.rawValue){
            //Attach File
            mail.addAttachmentData(data, mimeType: "text/plain", fileName: "data.txt")
        }

        present(mail, animated: true)
    } else {
        // show failure alert
    }
}

func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
    controller.dismiss(animated: true, completion: nil)
}

Body:
You need to create a new MFMailComposeViewController each time. Moving your mail declaration inside sendEmail works…

func sendEmail(body: String, subject: String) {
    if MFMailComposeViewController.canSendMail() {

       // Create a new MFMailComposeViewController…
       let mail = MFMailComposeViewController()

        mail.mailComposeDelegate = self

        mail.setSubject(subject)
        mail.setMessageBody("\(body)", isHTML: false)

        if let data = (body as NSString).data(using: String.Encoding.utf8.rawValue){
            //Attach File
            mail.addAttachmentData(data, mimeType: "text/plain", fileName: "data.txt")
        }

        present(mail, animated: true)
    } else {
        // show failure alert
    }
}

As to why…?


问:
piping the output to another command
The diff command works only if it has been provided with 2 files. Is it possible to replace one file with the output of another command? The second command mentioned below does not work.</p>

```<code>$ mysqldump -ushantanu -pPassWord test tbl --skip-extended-insert > to_backup.sql

$ diff  `mysqldump -uroot -pPassWord test some_other_tbl --skip-extended-insert` to_backup.sql
-bash: /usr/bin/diff: Argument list too long
</code>```

答:
You can use - as a special file name to represent standard input:

```<code>$ echo foo > bar
$ echo foo > baz
$ cat bar | diff - baz
</code>```

or

```<code>$ mysqldump -uroot -pPassWord test some_other_tbl --skip-extended-insert | diff - to_backup.sql
</code>```

ContentLicense: CC BY-SA 2.5

Title: piping the output to another command

Body:
The diff command works only if it has been provided with 2 files. Is it possible to replace one file with the output of another command? The second command mentioned below does not work.

$ mysqldump -ushantanu -pPassWord test tbl --skip-extended-insert > to_backup.sql

$ diff  `mysqldump -uroot -pPassWord test some_other_tbl --skip-extended-insert` to_backup.sql
-bash: /usr/bin/diff: Argument list too long

Body:
You can use - as a special file name to represent standard input:

$ echo foo > bar
$ echo foo > baz
$ cat bar | diff - baz

or

$ mysqldump -uroot -pPassWord test some_other_tbl --skip-extended-insert | diff - to_backup.sql


问:
Internal Server Error Django/apache
My Django app was working fine, but now I'm getting a server error, the last thing I did was a reboot to my Centos7 Server and now I'm getting this error:

and this are my logs I'm using apache:

```<code>[Thu Mar 30 14:04:10.571843 2017] [:error] [pid 11335] [remote 10.221.50.100:24] mod_wsgi (pid=11335): Target WSGI script '/opt/btsystem/BTSystem/wsgi.py' cannot be loaded as Python module.
    [Thu Mar 30 14:04:10.571991 2017] [:error] [pid 11335] [remote 10.221.50.100:24] mod_wsgi (pid=11335): Exception occurred processing WSGI script '/opt/btsystem/BTSystem/wsgi.py'.
    [Thu Mar 30 14:04:10.572263 2017] [:error] [pid 11335] [remote 10.221.50.100:24] Traceback (most recent call last):
    [Thu Mar 30 14:04:10.572544 2017] [:error] [pid 11335] [remote 10.221.50.100:24]   File "/opt/btsystem/BTSystem/wsgi.py", line 16, in <module>
    [Thu Mar 30 14:04:10.572795 2017] [:error] [pid 11335] [remote 10.221.50.100:24]     application = get_wsgi_application()
    [Thu Mar 30 14:04:10.572919 2017] [:error] [pid 11335] [remote 10.221.50.100:24]   File "/usr/lib64/python2.7/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application
    [Thu Mar 30 14:04:10.573054 2017] [:error] [pid 11335] [remote 10.221.50.100:24]     django.setup(set_prefix=False)
    [Thu Mar 30 14:04:10.573107 2017] [:error] [pid 11335] [remote 10.221.50.100:24]   File "/usr/lib64/python2.7/site-packages/django/__init__.py", line 22, in setup
    [Thu Mar 30 14:04:10.573170 2017] [:error] [pid 11335] [remote 10.221.50.100:24]     configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
    [Thu Mar 30 14:04:10.573261 2017] [:error] [pid 11335] [remote 10.221.50.100:24]   File "/usr/lib64/python2.7/site-packages/django/utils/log.py", line 75, in configure_logging
    [Thu Mar 30 14:04:10.573312 2017] [:error] [pid 11335] [remote 10.221.50.100:24]     logging_config_func(logging_settings)
    [Thu Mar 30 14:04:10.573369 2017] [:error] [pid 11335] [remote 10.221.50.100:24]   File "/usr/lib64/python2.7/logging/config.py", line 803, in dictConfig
    [Thu Mar 30 14:04:10.573409 2017] [:error] [pid 11335] [remote 10.221.50.100:24]     dictConfigClass(config).configure()
    [Thu Mar 30 14:04:10.573455 2017] [:error] [pid 11335] [remote 10.221.50.100:24]   File "/usr/lib64/python2.7/logging/config.py", line 585, in configure
    [Thu Mar 30 14:04:10.573501 2017] [:error] [pid 11335] [remote 10.221.50.100:24]     '%r: %s' % (name, e))
    [Thu Mar 30 14:04:10.573567 2017] [:error] [pid 11335] [remote 10.221.50.100:24] ValueError: Unable to configure handler 'file': [Errno 13] Permission denied: '/opt/btsystem-logs/btsystem-debug.log'
</code>```

Any idea?

答:
The main problem was that I needed to do the following to enable the virtual host from Apache:

```<code>firewall-cmd --get-active-zones
firewall-cmd --zone=public --add-port=80/tcp --permanent
firewall-cmd --reload
</code>```

Needed to open the ports.

Title: Internal Server Error Django/apache

Body:
My Django app was working fine, but now I'm getting a server error, the last thing I did was a reboot to my Centos7 Server and now I'm getting this error:

and this are my logs I'm using apache:

[Thu Mar 30 14:04:10.571843 2017] [:error] [pid 11335] [remote 10.221.50.100:24] mod_wsgi (pid=11335): Target WSGI script '/opt/btsystem/BTSystem/wsgi.py' cannot be loaded as Python module.
    [Thu Mar 30 14:04:10.571991 2017] [:error] [pid 11335] [remote 10.221.50.100:24] mod_wsgi (pid=11335): Exception occurred processing WSGI script '/opt/btsystem/BTSystem/wsgi.py'.
    [Thu Mar 30 14:04:10.572263 2017] [:error] [pid 11335] [remote 10.221.50.100:24] Traceback (most recent call last):
    [Thu Mar 30 14:04:10.572544 2017] [:error] [pid 11335] [remote 10.221.50.100:24]   File "/opt/btsystem/BTSystem/wsgi.py", line 16, in <module>
    [Thu Mar 30 14:04:10.572795 2017] [:error] [pid 11335] [remote 10.221.50.100:24]     application = get_wsgi_application()
    [Thu Mar 30 14:04:10.572919 2017] [:error] [pid 11335] [remote 10.221.50.100:24]   File "/usr/lib64/python2.7/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application
    [Thu Mar 30 14:04:10.573054 2017] [:error] [pid 11335] [remote 10.221.50.100:24]     django.setup(set_prefix=False)
    [Thu Mar 30 14:04:10.573107 2017] [:error] [pid 11335] [remote 10.221.50.100:24]   File "/usr/lib64/python2.7/site-packages/django/__init__.py", line 22, in setup
    [Thu Mar 30 14:04:10.573170 2017] [:error] [pid 11335] [remote 10.221.50.100:24]     configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
    [Thu Mar 30 14:04:10.573261 2017] [:error] [pid 11335] [remote 10.221.50.100:24]   File "/usr/lib64/python2.7/site-packages/django/utils/log.py", line 75, in configure_logging
    [Thu Mar 30 14:04:10.573312 2017] [:error] [pid 11335] [remote 10.221.50.100:24]     logging_config_func(logging_settings)
    [Thu Mar 30 14:04:10.573369 2017] [:error] [pid 11335] [remote 10.221.50.100:24]   File "/usr/lib64/python2.7/logging/config.py", line 803, in dictConfig
    [Thu Mar 30 14:04:10.573409 2017] [:error] [pid 11335] [remote 10.221.50.100:24]     dictConfigClass(config).configure()
    [Thu Mar 30 14:04:10.573455 2017] [:error] [pid 11335] [remote 10.221.50.100:24]   File "/usr/lib64/python2.7/logging/config.py", line 585, in configure
    [Thu Mar 30 14:04:10.573501 2017] [:error] [pid 11335] [remote 10.221.50.100:24]     '%r: %s' % (name, e))
    [Thu Mar 30 14:04:10.573567 2017] [:error] [pid 11335] [remote 10.221.50.100:24] ValueError: Unable to configure handler 'file': [Errno 13] Permission denied: '/opt/btsystem-logs/btsystem-debug.log'

Any idea?

Body:
The main problem was that I needed to do the following to enable the virtual host from Apache:

firewall-cmd --get-active-zones
firewall-cmd --zone=public --add-port=80/tcp --permanent
firewall-cmd --reload

Needed to open the ports.


问:
Execute a middleware one-time only at server startup in Koa v2
I created this middleware which executing only once when any route in the website gets the first hit from a visitor:

// pg-promise
const db = require('./db/pgp').db;
const pgp = require('./db/pgp').pgp;

app.use(async (ctx, next) => {
  try {
    ctx.db = db;
    ctx.pgp = pgp;
  } catch (err) {
    debugErr(`PGP ERROR: ${err.message}` || err);
  }
  await next();
});

// One-Time middleware
// https://github.com/expressjs/express/issues/2457
const oneTime = (fn) => {
  try {
    let done = false;
    const res = (ctx, next) => {
      if (done === false) {
        fn(ctx, next);
        done = true;
      }
      next();
    };
    return res;
  } catch (err) {
    debugErr(`oneTime ERROR: ${err.message}` || err);
  }
};

const oneTimeQuery = async (ctx) => {
  const result = await ctx.db.proc('version', [], a => a.version);
  debugLog(result);
};

app.use(oneTime(oneTimeQuery));
```

<p>This code executing on the first-time only when a user visiting the website, resulting:</p>

```app:log Listening on port 3000 +13ms
app:req GET / 200 - 24ms +2s
23:07:15 connect(postgres@postgres)
23:07:15 SELECT * FROM version()
23:07:15 disconnect(postgres@postgres)
app:log PostgreSQL 9.6.2, compiled by Visual C++ build 1800, 64-bit +125ms
```

<p>My problem is that I want to execute it at the server start, when there's no any visit on the site.</p>

<p>The future purpose of this code will be to check the existence of tables in the database.</p>

<p><strong>Solution:</strong></p>

<p>Placing this in <code>./bin/www</code> before the <code>const server = http.createServer(app.callback());</code> declaration helped:</p>

<pre class="lang-js prettyprint-override"><code>const query = async () => {
  const db = require('../db/pgp').db;
  const pgp = require('../db/pgp').pgp;
  const result = await db.proc('version', [], a => a.version);
  debugLog(`www: ${result}`);
  pgp.end(); // for immediate app exit, closing the connection pool (synchronous)
};
query();
</code>```

答:
You could start your application using a js script that requires your app and uses node's native http module to fire up the server. Exactly like in koa-generator (click).

This is in your app.js file:

```<code>const app = require('koa')();
...
module.exports = app;
</code>```

And then this is in your script to fire up the server:

```<code>const app = require('./app');
const http = require('http');

[this is the place where you should run your code before server starts]

const server = http.createServer(app.callback());
server.listen(port);
</code>```

Afterwards you start your application with:

```<code>node [script_name].js
</code>```

Of course keep in mind the async nature of node when doing it this way. What I mean by that - run the 'listen' method on 'server' variable in callback/promise.

Body:
I created this middleware which executing only once when any route in the website gets the first hit from a visitor:

// pg-promise
const db = require('./db/pgp').db;
const pgp = require('./db/pgp').pgp;

app.use(async (ctx, next) => {
  try {
    ctx.db = db;
    ctx.pgp = pgp;
  } catch (err) {
    debugErr(`PGP ERROR: ${err.message}` || err);
  }
  await next();
});

// One-Time middleware
// https://github.com/expressjs/express/issues/2457
const oneTime = (fn) => {
  try {
    let done = false;
    const res = (ctx, next) => {
      if (done === false) {
        fn(ctx, next);
        done = true;
      }
      next();
    };
    return res;
  } catch (err) {
    debugErr(`oneTime ERROR: ${err.message}` || err);
  }
};

const oneTimeQuery = async (ctx) => {
  const result = await ctx.db.proc('version', [], a => a.version);
  debugLog(result);
};

app.use(oneTime(oneTimeQuery));

This code executing on the first-time only when a user visiting the website, resulting:

app:log Listening on port 3000 +13ms
app:req GET / 200 - 24ms +2s
23:07:15 connect(postgres@postgres)
23:07:15 SELECT * FROM version()
23:07:15 disconnect(postgres@postgres)
app:log PostgreSQL 9.6.2, compiled by Visual C++ build 1800, 64-bit +125ms

My problem is that I want to execute it at the server start, when there's no any visit on the site.

The future purpose of this code will be to check the existence of tables in the database.

Solution:

Placing this in ./bin/www before the const server = http.createServer(app.callback()); declaration helped:

const query = async () => {
  const db = require('../db/pgp').db;
  const pgp = require('../db/pgp').pgp;
  const result = await db.proc('version', [], a => a.version);
  debugLog(`www: ${result}`);
  pgp.end(); // for immediate app exit, closing the connection pool (synchronous)
};
query();

Body:
You could start your application using a js script that requires your app and uses node's native http module to fire up the server. Exactly like in koa-generator (click).

This is in your app.js file:

const app = require('koa')();
...
module.exports = app;

And then this is in your script to fire up the server:

const app = require('./app');
const http = require('http');

[this is the place where you should run your code before server starts]

const server = http.createServer(app.callback());
server.listen(port);

Afterwards you start your application with:

node [script_name].js

Of course keep in mind the async nature of node when doing it this way. What I mean by that - run the 'listen' method on 'server' variable in callback/promise.


问:
What do you use for running scheduled tasks in Production for Python?
The thing is, I read this post stating best practices to set up a code to run at every specified interval over a period of time using the python library - APS Scheduler. Now, it obviously works perfectly fine if I do it on a test environment and run the application from the command prompt.

However, I come from a background where most my projects are university level and never ran in production but for this one, I would like to. I have access to AWS and can configure any kind of server on AWS and I am open to other options as well. It would be great if I could get a headstart on what to look if I have to run this application as a service from a server or a remote machine without having to constantly monitoring it and providing interrupts on command prompt.

I do not have any experience of running Python applications in production so any input would be appreciated. Also, I do not know how to execute this code in production (except for through aws cli) but that session expires once I close my CLI so that does not seem like the most appropriate way to do it so any help on that end would be appreciated too.

答:
The Answer was very simple and does not make a lot of sense and might not be applicable to all.

Now, what I had was a python flask application so I configured the app in a virtual environment using eb-virt on the aws server and then created an executable wsgi script which I then ran as a service using mod_wsgi plugin for the apache http server and then I was able to run my app.


问:
Count collisions in Corona SDK / Lua...?
I have a short question related to design patterns. During collisions, an event is dispatched multiple times, which is why you obviously have to count them, to make it stable. My question :

I always end up just incrementing a counter and reset it with a short delay in each collision, which leads to bulky event listeners. Does anybody have a more elegant and overseeable way? They can get quite hard to debug sometimes.

As always, thanks for your help in advance!

Greetings, Nils

答:
Idurniat, you asked for code. Here is an example of the common problem:

```<code>local physics = require("physics")
local object = display.newRect(display.contentCenterX, display.contentCenterY, 100, 100)
physics.start()
physics.addBody(object, "static", {isSensor = true})
function object.collision(self, event)
  if event.phase == "began" then
    print("log")
  end
end
</code>```

Now, when a dynamic physics object hits the rectangle, there will be printed several times "log". Because of this, for example transitions start multiple times and make a mess. And handling this with a counter and a timer is quite tricky.

Thanks in advance!

Greetings, Nils

Body:
Idurniat, you asked for code. Here is an example of the common problem:

local physics = require("physics")
local object = display.newRect(display.contentCenterX, display.contentCenterY, 100, 100)
physics.start()
physics.addBody(object, "static", {isSensor = true})
function object.collision(self, event)
  if event.phase == "began" then
    print("log")
  end
end

Now, when a dynamic physics object hits the rectangle, there will be printed several times "log". Because of this, for example transitions start multiple times and make a mess. And handling this with a counter and a timer is quite tricky.

Thanks in advance!

Greetings, Nils


问:
Custom Dialog filling the screen height
I am trying to create a custom Dialog, and is working just fine, but the Dialog is filling the whole screen height. I've done some unsuccessful research on the internet but I don't have a lot of time for this task, if anyone knows why is this happening I appreciate it hard.

here is the onCreateDialog():

```<code>public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder= new AlertDialog.Builder(getContext());
    LayoutInflater inflater= (LayoutInflater) builder.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.dialog__warning, mContainer, false);
    txtWarning = (TextView)view.findViewById(R.id.txtWarning);
    if(messageWarning.length()>0)
    {
        txtWarning.setText(messageWarning);
    }
    btnOkDialog = (Button) view.findViewById(R.id.btnOkDialog);
    btnOkDialog.setOnClickListener(MyListener);
    btnCancelDialog = (Button) view.findViewById(R.id.btnCancelDialog);
    btnCancelDialog.setOnClickListener(MyListener);
    builder.setView(view);
    return builder.create();
}
</code>```

and the xml of dialog_warning:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="300dp"
android:layout_height="300dp"
android:background="#b1b0b0"
tools:context="ipat.johanbayona.gca.ipat.NewEvidence.Dialog_Warning">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:textSize="25sp"
    android:id="@+id/txtWarning"
    android:text="Mensaje error" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="OK"
    android:id="@+id/btnOkDialog"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_marginBottom="10dp"
    />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Cancel"
    android:id="@+id/btnCancelDialog"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_marginBottom="10dp"
    />
</RelativeLayout>
</code>```

答:
try creating your own theme for the dialog, something like this

```<code><style name="AppDialog">
    <item name="android:windowFrame">@null</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:colorBackgroundCacheHint">@null</item>
</style>
</code>```

and set this theme passing to the dialog's super constructor with R.style.AppDialog

upd.
it's not the builder's constructor. you should create your own class that extends the AlertDialog, override it's onCreate and the super constructor and your class should be something like this

```<code>public class YourDialog extends Dialog {

    public YourDialog(@NonNull Context context) {
        super(context, R.style.AppDialog);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.dialog__warning);

        txtWarning = (TextView) findViewById(R.id.txtWarning);
        if(messageWarning.length()>0)
        {
            txtWarning.setText(messageWarning);
        }
        btnOkDialog = (Button) findViewById(R.id.btnOkDialog);
        btnOkDialog.setOnClickListener(MyListener);
        btnCancelDialog = (Button) findViewById(R.id.btnCancelDialog);
        btnCancelDialog.setOnClickListener(MyListener);
    }
}
</code>```

overriding the main constructor, and passing the  R.style.AppDialog should do the trick. all you need is to call where you want to show the dialog new YourDialog(context).show();

note that you don't need to call manually the layout inflater to pass your own contentview, just calling the setContentView with resId will automatically inflate the view beneath.

Title: Custom Dialog filling the screen height

Body:
I am trying to create a custom Dialog, and is working just fine, but the Dialog is filling the whole screen height. I've done some unsuccessful research on the internet but I don't have a lot of time for this task, if anyone knows why is this happening I appreciate it hard.

here is the onCreateDialog():

public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder= new AlertDialog.Builder(getContext());
    LayoutInflater inflater= (LayoutInflater) builder.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.dialog__warning, mContainer, false);
    txtWarning = (TextView)view.findViewById(R.id.txtWarning);
    if(messageWarning.length()>0)
    {
        txtWarning.setText(messageWarning);
    }
    btnOkDialog = (Button) view.findViewById(R.id.btnOkDialog);
    btnOkDialog.setOnClickListener(MyListener);
    btnCancelDialog = (Button) view.findViewById(R.id.btnCancelDialog);
    btnCancelDialog.setOnClickListener(MyListener);
    builder.setView(view);
    return builder.create();
}

and the xml of dialog_warning:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="300dp"
android:layout_height="300dp"
android:background="#b1b0b0"
tools:context="ipat.johanbayona.gca.ipat.NewEvidence.Dialog_Warning">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:textSize="25sp"
    android:id="@+id/txtWarning"
    android:text="Mensaje error" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="OK"
    android:id="@+id/btnOkDialog"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_marginBottom="10dp"
    />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Cancel"
    android:id="@+id/btnCancelDialog"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_marginBottom="10dp"
    />
</RelativeLayout>

Body:
try creating your own theme for the dialog, something like this

<style name="AppDialog">
    <item name="android:windowFrame">@null</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:colorBackgroundCacheHint">@null</item>
</style>

and set this theme passing to the dialog's super constructor with R.style.AppDialog

upd.
it's not the builder's constructor. you should create your own class that extends the AlertDialog, override it's onCreate and the super constructor and your class should be something like this

public class YourDialog extends Dialog {

    public YourDialog(@NonNull Context context) {
        super(context, R.style.AppDialog);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.dialog__warning);

        txtWarning = (TextView) findViewById(R.id.txtWarning);
        if(messageWarning.length()>0)
        {
            txtWarning.setText(messageWarning);
        }
        btnOkDialog = (Button) findViewById(R.id.btnOkDialog);
        btnOkDialog.setOnClickListener(MyListener);
        btnCancelDialog = (Button) findViewById(R.id.btnCancelDialog);
        btnCancelDialog.setOnClickListener(MyListener);
    }
}

overriding the main constructor, and passing the  R.style.AppDialog should do the trick. all you need is to call where you want to show the dialog new YourDialog(context).show();

note that you don't need to call manually the layout inflater to pass your own contentview, just calling the setContentView with resId will automatically inflate the view beneath.


问:
Tipsy Tooltip Direction Problem
I use Tipsy Tool time plugin I noticed that I cant use the same direction of the tooltip with another link.

Example:

javascript:

```<code>$('#south').tipsy({gravity: 's'});
</code>```

html:

```<code><a id='south' href='#' title='This is an example of south direction'>South</a>
<a id='south' href='#' title='This is an example of south direction2'>South</a>
</code>```

Explain the example:

Link1 - link2

when I hover link1 the tooltip shows at the top,
I want also when I hover link2 the tooltip shows at the top,

But unfortunately did not work with me!

So can any one help me.

thank you

答:
You can't repeat IDs like this, they have to be unique in a page (otherwise you'll see side-effects, like $('#south') only returning the first match...your current issue).  Use a class instead in these cases, like this:

```<code>$('.south').tipsy({gravity: 's'});
</code>```

The same on the links;

```<code><a class='south' href='#' title='This is an example of south direction'>South</a>
<a class='south' href='#' title='This is an example of south direction2'>South</a>
</code>```

Title: Tipsy Tooltip Direction Problem

Body:
I use Tipsy Tool time plugin I noticed that I cant use the same direction of the tooltip with another link.

Example:

javascript:

$('#south').tipsy({gravity: 's'});

html:

South
South

Explain the example:

Link1 - link2

when I hover link1 the tooltip shows at the top,
I want also when I hover link2 the tooltip shows at the top,

But unfortunately did not work with me!

So can any one help me.

thank you

Body:
You can't repeat IDs like this, they have to be unique in a page (otherwise you'll see side-effects, like $('#south') only returning the first match...your current issue).  Use a class instead in these cases, like this:

$('.south').tipsy({gravity: 's'});

The same on the links;

<a class='south' href='#' title='This is an example of south direction'>South</a>
<a class='south' href='#' title='This is an example of south direction2'>South</a>


问:
Apache Camel - Getting xpath value from XML
I'm trying to make a program by using camel. This program should  be able to recieve xml files in a folder called inbox_xml_files.

Then the program should get the text value of the < Country > element node inside the xml file.

If the text value is "Denmark" the file should be moved to a folder called "outbox_Denmark".

If the text value is "Sweden" the file should be moved to a folder called "outbox_Sweden".

If the text value is something else the file should be moved to a folder called "outbox_Other".

This is the XML file i use for testing:

```<code>    <?xml version="1.0"?>
<Company>
  <Employee>
      <FirstName>Mike</FirstName>
      <LastName>James</LastName>
      <ContactNo>1234567890</ContactNo>
      <Email>oy@hotmail.com</Email>
      <Address>
            <Country>Denmark</Country>
            <City>Copenhagen</City>
            <Zip>1234</Zip>
      </Address>
  </Employee>
</Company>
</code>```

The camel xml file (The one I'm troubled with):

```<code><camelContext id="camelId" xmlns="http://camel.apache.org/schema/spring">
        <camel:route id="_route1">
            <camel:from id="_from1" uri="file:C:/inbox_xml_files?noop=false"/>
            <camel:choice id="_choice1">
                <camel:when id="_when1">
                    <camel:xpath>
                            //Company/Employee/Address/Country = 'Denmark'
                        </camel:xpath>
                    <camel:to id="_to1" uri="file:C:/outbox_Denmark"/>
                </camel:when>
                <camel:when id="_when2">
                    <camel:xpath>
                            //Company/Employee/Address/Country = 'Sweden'
                        </camel:xpath>
                    <camel:to id="_to2" uri="file:C:/outbox_Sweden"/>
                </camel:when>
                <camel:otherwise id="_otherwise1">
                    <camel:to id="_to3" uri="file:C:/outbox_Other"/>
                </camel:otherwise>
            </camel:choice>
        </camel:route>
    </camelContext>
</code>```

I believe that the problem is inside the < camel:xpath >. I think i have defined it wrong and i'm trying but all this is something new for me so i'm struggling with it.

答:
Try this : </p>

```<code><camel:xpath>//Company/Employee/Address/Country='Sweden'</camel:xpath>
</code>```

<p>or </p>

```<code><camel:xpath>//*[local-name() = 'Country' and text()='Sweden']</camel:xpath>
</code>```

Body:
I'm trying to make a program by using camel. This program should  be able to recieve xml files in a folder called inbox_xml_files.

Then the program should get the text value of the < Country > element node inside the xml file.

If the text value is "Denmark" the file should be moved to a folder called "outbox_Denmark".

If the text value is "Sweden" the file should be moved to a folder called "outbox_Sweden".

If the text value is something else the file should be moved to a folder called "outbox_Other".

This is the XML file i use for testing:

    <?xml version="1.0"?>
<Company>
  <Employee>
      <FirstName>Mike</FirstName>
      <LastName>James</LastName>
      <ContactNo>1234567890</ContactNo>
      <Email>oy@hotmail.com</Email>
      <Address>
            <Country>Denmark</Country>
            <City>Copenhagen</City>
            <Zip>1234</Zip>
      </Address>
  </Employee>
</Company>

The camel xml file (The one I'm troubled with):

<camelContext id="camelId" xmlns="http://camel.apache.org/schema/spring">
        <camel:route id="_route1">
            <camel:from id="_from1" uri="file:C:/inbox_xml_files?noop=false"/>
            <camel:choice id="_choice1">
                <camel:when id="_when1">
                    <camel:xpath>
                            //Company/Employee/Address/Country = 'Denmark'
                        </camel:xpath>
                    <camel:to id="_to1" uri="file:C:/outbox_Denmark"/>
                </camel:when>
                <camel:when id="_when2">
                    <camel:xpath>
                            //Company/Employee/Address/Country = 'Sweden'
                        </camel:xpath>
                    <camel:to id="_to2" uri="file:C:/outbox_Sweden"/>
                </camel:when>
                <camel:otherwise id="_otherwise1">
                    <camel:to id="_to3" uri="file:C:/outbox_Other"/>
                </camel:otherwise>
            </camel:choice>
        </camel:route>
    </camelContext>

I believe that the problem is inside the < camel:xpath >. I think i have defined it wrong and i'm trying but all this is something new for me so i'm struggling with it.

Body:
Try this :

<camel:xpath>//Company/Employee/Address/Country='Sweden'</camel:xpath>

or

<camel:xpath>//*[local-name() = 'Country' and text()='Sweden']</camel:xpath>


问:
Typescript Typecast
I receive some JSON which can be a TextField object or a DateField object. Both inherit the Field superclass. The JSON I receive is converted to a Field object. I then need to cast this Field object into the corresponding type. To do this, I have an Id inside the JSON which lets me know if it's a TextField or DateField object. Everything works if I create a new TextField object and assign him the values of the JSON manually. However, I'd like to cast it directly to the corresponding class as it has the same attributes as the JSON. Something like newField = <TextareaField>field; but then, if I do newField instanceof TextField, it doesn't work. Any idea on how to cast an object to another type?

答:
It seems to work if I do:</p>

```<code>newField = Object.assign(new TextField(), field);
</code>```

Title: Typescript Typecast

Body:
It seems to work if I do:

newField = Object.assign(new TextField(), field);


问:
Am I on right path to simplifying php code block?
Fairly new to php and following e commerce tutorials. When exploring a way to resolve a problem I had with a php code block, I came upon a post another person had with the same code block.
https://forums.phpfreaks.com/topic/272404-help-problem-with-some-line-of-codes/
 The post suggested a way to simplify the code.

Original code block:

```<code>   <?php
if (isset($_POST ['pid'])) {
    $pid = $_POST ['pid'];
    $wasFound = false;
    $i = 0;
    if (!isset ($_SESSION["cart_array"]) || count($_SESSION ["cart_array"])<1){
        $_SESSION["cart_array"] = array (0=> array("item_id"=> $pid, "quantity" => 1));
    }  else {
        foreach ($_SESSION["cart_array"] as $each_item) {
            $i++;
            while(list($key,$value)=each($each_item)){
            if ($key== "item_id" && $value == $pid) {
                array_splice ($_SESSION["cart_array"], $i-1,1, array(array("item_id"=>$pid,"quantity"=> $each_item['quantity']+1)));
                $wasFound = true;
            }
        }
    }
    if($wasFound==false) {
        array_push ($_SESSION["cart_array"], array("item_id"=> $pid, "quantity" => 1));
        }
    }
    header("Location: cart.php");
    exit();
}
?>
</code>```

This was the suggested simplified code block and an explanation of what to do after changing code. I am unsure how to implement the the part suggested after the code block.

```<code>if (isset($_POST['pid'])) {
    // add (+1) item to cart
    $pid = (int)$_POST['pid']; // cast as integer
    // valid pids are > 0
    if($pid > 0){
    if(!isset($_SESSION['cart_array'][$pid])){
    // item is not in the cart, add it with quantity = 1
    $_SESSION['cart_array'][$pid] = array("item_id" => $pid, "quantity" => 1); // I left the array in the cart the same, but it could also be simplified so that it is only the quantity, since the item_id is now the cart array index
    } else {
    // item is in the cart, increment quantity
    $_SESSION['cart_array'][$pid]['quantity']++;
    }
    }
    header("location: cart.php");
    exit();
    }
</code>```

To get the details for the cart items, you need to run ONE query that gets all of them at the same time (putting a query inside of a loop is a resource killer.) For the definition of the cart that I have suggested, you can use array_keys to get all the item id's. You would then implode those into a comma separated list and put them into an IN() comparison in the WHERE clause in a query to get all the matching rows at once.
Edited by PFMaBiSmAd, 27 December 2012 - 02:05 PM.

This is what I am considering adding to the code block:

```<code>if  ($result = print_r(array_keys('cart_array',$pid))) {
$comma_seperated = implode("," $result);

// then use use $comma_seperated in query where needed later in annother code block?
}
</code>```

Am I on the right path?

答:
This was provided by Mike Brant in codereview.stackexchange. This is how I would extract the keys to be used in query.

$pidsInCart = array_keys($_SESSION['cart_array']);

Body:
Fairly new to php and following e commerce tutorials. When exploring a way to resolve a problem I had with a php code block, I came upon a post another person had with the same code block.
https://forums.phpfreaks.com/topic/272404-help-problem-with-some-line-of-codes/
 The post suggested a way to simplify the code.

Original code block:

   <?php
if (isset($_POST ['pid'])) {
    $pid = $_POST ['pid'];
    $wasFound = false;
    $i = 0;
    if (!isset ($_SESSION["cart_array"]) || count($_SESSION ["cart_array"])<1){
        $_SESSION["cart_array"] = array (0=> array("item_id"=> $pid, "quantity" => 1));
    }  else {
        foreach ($_SESSION["cart_array"] as $each_item) {
            $i++;
            while(list($key,$value)=each($each_item)){
            if ($key== "item_id" && $value == $pid) {
                array_splice ($_SESSION["cart_array"], $i-1,1, array(array("item_id"=>$pid,"quantity"=> $each_item['quantity']+1)));
                $wasFound = true;
            }
        }
    }
    if($wasFound==false) {
        array_push ($_SESSION["cart_array"], array("item_id"=> $pid, "quantity" => 1));
        }
    }
    header("Location: cart.php");
    exit();
}
?>

This was the suggested simplified code block and an explanation of what to do after changing code. I am unsure how to implement the the part suggested after the code block.

if (isset($_POST['pid'])) {
    // add (+1) item to cart
    $pid = (int)$_POST['pid']; // cast as integer
    // valid pids are > 0
    if($pid > 0){
    if(!isset($_SESSION['cart_array'][$pid])){
    // item is not in the cart, add it with quantity = 1
    $_SESSION['cart_array'][$pid] = array("item_id" => $pid, "quantity" => 1); // I left the array in the cart the same, but it could also be simplified so that it is only the quantity, since the item_id is now the cart array index
    } else {
    // item is in the cart, increment quantity
    $_SESSION['cart_array'][$pid]['quantity']++;
    }
    }
    header("location: cart.php");
    exit();
    }

To get the details for the cart items, you need to run ONE query that gets all of them at the same time (putting a query inside of a loop is a resource killer.) For the definition of the cart that I have suggested, you can use array_keys to get all the item id's. You would then implode those into a comma separated list and put them into an IN() comparison in the WHERE clause in a query to get all the matching rows at once.
Edited by PFMaBiSmAd, 27 December 2012 - 02:05 PM.

This is what I am considering adding to the code block:

if  ($result = print_r(array_keys('cart_array',$pid))) {
$comma_seperated = implode("," $result);

// then use use $comma_seperated in query where needed later in annother code block?
}

Am I on the right path?


问:
type() function doesn't return correct result for a boto3 sqs object?
I'm using Python 3's type hinting syntax, and I'm writing a small AWS application that uses SQS. I'm trying to hint the type of the Queue. This is how I obtain the type of the Queue:

```<code>>>> import boto3
>>> session = boto3.session.Session(
>>>     aws_access_key_id=AWS_ACCESS_KEY,
>>>     aws_secret_access_key=AWS_SECRET_KEY,
>>>     region_name='us-west-2'
>>> )
>>> sqs = session.resource('sqs')
>>> queue=sqs.Queue(AWS_QUEUE_URL)
>>>
>>> type(queue)
<class 'boto3.resources.factory.sqs.Queue'>
</code>```

And I write my type-hinted function like this:

```<code>def get_session() -> boto3.resources.factory.sqs.Queue:
    ...
</code>```

But I get an error:

```<code>AttributeError: module 'boto3.resources.factory' has no attribute 'sqs'
</code>```

I've looked through the package myself using dir(...). It seems that factory does not contain sqs, indeed. Thus, I have two questions:

Why is type returning this nonexistent class?

How can I find the right type of this object?

答:
The class of sqs.Queue appears to be generated on the fly every time it's called:

```<code>>>> import boto3
>>> session = boto3.session.Session(aws_access_key_id='foo', aws_secret_access_key='bar', region_name='us-west-2')
>>> sqs = session.resource('sqs')
>>> sqs.Queue
<bound method sqs.ServiceResource.Queue of sqs.ServiceResource()>
>>> q = sqs.Queue('blah')
>>> type(q)
<class 'boto3.resources.factory.sqs.Queue'>
>>> q2 = sqs.Queue('bluh')
>>> type(q) == type(q2)
False
</code>```

So that's kind of a bad design choice on boto's end. I think it means it's not possible to reasonably type annotate it, even with forward references.

Your best bet is to give a type hint for the common base class of all these dynamic classes, boto3.resources.base.ServiceResource:

```<code>>>> type(q).__bases__
(<class 'boto3.resources.base.ServiceResource'>,)
</code>```

Body:
I'm using Python 3's type hinting syntax, and I'm writing a small AWS application that uses SQS. I'm trying to hint the type of the Queue. This is how I obtain the type of the Queue:

>>> import boto3
>>> session = boto3.session.Session(
>>>     aws_access_key_id=AWS_ACCESS_KEY,
>>>     aws_secret_access_key=AWS_SECRET_KEY,
>>>     region_name='us-west-2'
>>> )
>>> sqs = session.resource('sqs')
>>> queue=sqs.Queue(AWS_QUEUE_URL)
>>>
>>> type(queue)
<class 'boto3.resources.factory.sqs.Queue'>

And I write my type-hinted function like this:

def get_session() -> boto3.resources.factory.sqs.Queue:
    ...

But I get an error:

AttributeError: module 'boto3.resources.factory' has no attribute 'sqs'

I've looked through the package myself using dir(...). It seems that factory does not contain sqs, indeed. Thus, I have two questions:

Why is type returning this nonexistent class?

How can I find the right type of this object?

Body:
The class of sqs.Queue appears to be generated on the fly every time it's called:

>>> import boto3
>>> session = boto3.session.Session(aws_access_key_id='foo', aws_secret_access_key='bar', region_name='us-west-2')
>>> sqs = session.resource('sqs')
>>> sqs.Queue
<bound method sqs.ServiceResource.Queue of sqs.ServiceResource()>
>>> q = sqs.Queue('blah')
>>> type(q)
<class 'boto3.resources.factory.sqs.Queue'>
>>> q2 = sqs.Queue('bluh')
>>> type(q) == type(q2)
False

So that's kind of a bad design choice on boto's end. I think it means it's not possible to reasonably type annotate it, even with forward references.

Your best bet is to give a type hint for the common base class of all these dynamic classes, boto3.resources.base.ServiceResource:

>>> type(q).__bases__
(<class 'boto3.resources.base.ServiceResource'>,)


问:
Passing information to MySQL database to an HTML form using PHP
I am trying to connect to a MySQL database to save information passed via a registration form on my website. for some reason, it won't connect. I have searched in Stack Overflow but can't find the right answer.

Here is my PHP code:

```<code><?php
$con = mysqli_connect("mysite","my username","my password","My database");

if($con === false){
    die("ERROR: Could not connect. ". mysqli_connect_error());
}

$sql = "CREATE TABLE clients(client_id INT(4) NOT NULL PRIMARY KEY AUTO_INCREMENT, username CHAR(30) NOT NULL, password CHAR(30) NOT NULL)";

if (mysqli_query($con, $sql)){
    echo "Table clients created successfully";
}
else {
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($con);
}

$user_info = “INSERT INTO clients(username, password) VALUES ( '$_POST["username"]','$_POST["password"]')”;
mysqli_query($con,$user_info);

if (!mysqli_query($con, $user_info)){
    die('Error: ' . mysql_error());
}

echo “Your information was added to the database.”;
mysqli_close($con);
?>
</code>```

And here is my HTML code:

```<code><!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>

<div class="register">
  <h1>Register Here</h1>
  <form action="register.php" method="post">
    <input type="text" id="username" placeholder="Username" required="required" /><br><br>
    <input type="password" id="password" placeholder="Password" required="required" /><br>
    <button id="btnreg" type="submit">Let Me In</button>
  </form>
</div>

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

When I press the submit button, it just shows me a black page, with no errors, and in phpMyAdmin, the table has not been created and of course the information has not been passed.
I'm using GoDaddy hosting if it has any signification for this issue, and i have checked like 25 times that I'm using the correct hostname and database information.

Thanks.

答: I think it is an empty index problem. I have a solution for you to try:if(isset('$_POST["btnreg"]')){$query = "your query;mysqli_query($con,$query);"}

Body:
I am trying to connect to a MySQL database to save information passed via a registration form on my website. for some reason, it won't connect. I have searched in Stack Overflow but can't find the right answer.

Here is my PHP code:

<?php
$con = mysqli_connect("mysite","my username","my password","My database");

if($con === false){
    die("ERROR: Could not connect. ". mysqli_connect_error());
}

$sql = "CREATE TABLE clients(client_id INT(4) NOT NULL PRIMARY KEY AUTO_INCREMENT, username CHAR(30) NOT NULL, password CHAR(30) NOT NULL)";

if (mysqli_query($con, $sql)){
    echo "Table clients created successfully";
}
else {
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($con);
}

$user_info = “INSERT INTO clients(username, password) VALUES ( '$_POST["username"]','$_POST["password"]')”;
mysqli_query($con,$user_info);

if (!mysqli_query($con, $user_info)){
    die('Error: ' . mysql_error());
}

echo “Your information was added to the database.”;
mysqli_close($con);
?>

And here is my HTML code:

<!DOCTYPE html>

<link rel="stylesheet" type="text/css" href="style.css"/>

Register Here

  <form action="register.php" method="post">
    <input type="text" id="username" placeholder="Username" required="required" />

    <input type="password" id="password" placeholder="Password" required="required" />

    <button id="btnreg" type="submit">Let Me In</button>
  </form>

When I press the submit button, it just shows me a black page, with no errors, and in phpMyAdmin, the table has not been created and of course the information has not been passed.
I'm using GoDaddy hosting if it has any signification for this issue, and i have checked like 25 times that I'm using the correct hostname and database information.

Thanks.


问:
Where is Spring 3 MVC in REST web-app example download?
I saw springsource.org had not spring 3 in rest web-app sample,where is download?</p>

答: I haven't found any rest example with spring MVC 3. The @SessionAttributes annotation breaks REST idea. </p>


问:
modify a regex with another regex from code
I have a string 'out' which I need to change for another string 'into', in a text called 'text'.

```<code>out = 'hello $ world'
into = '###'
text = 'this hello \n$ world text'
</code>```

And I also want to know if there was any change.

As I see it, I should first, escape 'out' text (to allow chars like '$' to be modified). Then, I should replace all ur'\s+' with '\s+', and this resulting string should contain the regex to be replaced with '###'.

To sum up: I have text like this:

```<code>text = 'this hello \n$ world text'
</code>```

And I want this as a result:

```<code>result: 'this ### text'
</code>```

I tried this:

```<code>re.sub(re.sub(ur'\s+', '\s+', re.escape(out)), into, text)
</code>```

and get this as a result:

```<code>'this hello \n$ world text'
</code>```

And also this:

```<code>re.sub(re.sub(ur'\s+', ur'\s+', re.escape(out)), into, text)
</code>```

with the same result.

I think there are some problems with '\' char, but it's a bit confusing, how can I fix it? I'm running python 2.7

答:
Well the main problem looks here that re.escape(..) escapes whitespace as well. Indeed:

```<code>>>> re.escape('hello $ world')
'hello\\ \\$\\ world'
</code>```

It is however easy to alter that by substitute r'\ ' by r'\s+':

```<code>re.sub(<b>r'\\\s+'</b>,r'\s+',re.escape(out))</code>```

Or the fill code:

```<code>>>> re.sub(re.sub(ur'\\\s+', ur'\s+', re.escape(out)), into, text)
'this ### text'
</code>```

You can furthermore improve efficiency a bit of the resulting regex by replacing r\(\\\s+)+' instead, since two spaces in the original string now map to the same 'r'\s+'':

```<code>>>> re.sub(re.sub(ur'(\\\s+)+', ur'\s+', re.escape(out)), into, text)
'this ### text'
</code>```

You can detect whether there is change by simply comparing the old text with the new one`. For instance:

```<code>new_text = re.sub(re.sub(ur'(\\\s+)+', ur'\s+', re.escape(out)), into, text)
change = text != new_text # change is a bool that is True if there is change
</code>```

Body:
I have a string 'out' which I need to change for another string 'into', in a text called 'text'.

out = 'hello $ world'
into = '###'
text = 'this hello \n$ world text'

And I also want to know if there was any change.

As I see it, I should first, escape 'out' text (to allow chars like '$' to be modified). Then, I should replace all ur'\s+' with '\s+', and this resulting string should contain the regex to be replaced with '###'.

To sum up: I have text like this:

text = 'this hello \n$ world text'

And I want this as a result:

result: 'this ### text'

I tried this:

re.sub(re.sub(ur'\s+', '\s+', re.escape(out)), into, text)

and get this as a result:

'this hello \n$ world text'

And also this:

re.sub(re.sub(ur'\s+', ur'\s+', re.escape(out)), into, text)

with the same result.

I think there are some problems with '\' char, but it's a bit confusing, how can I fix it? I'm running python 2.7

Body:
Well the main problem looks here that re.escape(..) escapes whitespace as well. Indeed:

>>> re.escape('hello $ world')
'hello\\ \\$\\ world'

It is however easy to alter that by substitute r'\ ' by r'\s+':

re.sub(r'\\\s+',r'\s+',re.escape(out))

Or the fill code:

>>> re.sub(re.sub(ur'\\\s+', ur'\s+', re.escape(out)), into, text)
'this ### text'

You can furthermore improve efficiency a bit of the resulting regex by replacing r\(\\\s+)+' instead, since two spaces in the original string now map to the same 'r'\s+'':

>>> re.sub(re.sub(ur'(\\\s+)+', ur'\s+', re.escape(out)), into, text)
'this ### text'

You can detect whether there is change by simply comparing the old text with the new one`. For instance:

new_text = re.sub(re.sub(ur'(\\\s+)+', ur'\s+', re.escape(out)), into, text)
change = text != new_text # change is a bool that is True if there is change


问:
What does a underscore before a letter (_p) mean in python
I run into a function but not quite understand it. I am not sure it is a convention or has a meaning. what does the _p, where did the _p enter the function. It would be much appreciated if you can give me some explanation on the for loop here.

```<code>    def contraction_mapping(S, p, MF, params, beta=0.75, threshold=1e-6, suppr_output=False):
        '''
Initialization of the state-transition matrices:
        describe the state-transition probabilities if the maintenance cost is incurred,
        and regenerate the state to 0 if the replacement cost is incurred.
        '''
        ST_mat = np.zeros((S, S))
        p = np.array(p)
        for i in range(S):
            for j, _p in enumerate(p):
                if i + j < S-1:
                    ST_mat[i+j][i] = _p

                elif i + j == S-1:
                    ST_mat[S-1][i] = p[j:].sum()
                else:
                    pass

        R_mat = np.vstack((np.ones((1, S)),np.zeros((S-1, S))))
</code>```

答:
See PEP8 for details on many python style conventions.  In particular, you can find the description of a single leading underscore here:

https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles

_single_leading_underscore : weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an
  underscore.

In the loop above, this is somewhat of a misuse, as they are only using _p to avoid clashing with the existing name p.  These variable names are not great obviously.  The _p are items of the array provided by enumerate, while p is the entire array as well (locally overriding the original p parameter passed in).

As a side note, the loop itself is somewhat awkward, and could be simplified and optimized (mostly fallout from using better ranges instead of pass, and avoiding recalculating the sum repeatedly).

Body:
I run into a function but not quite understand it. I am not sure it is a convention or has a meaning. what does the _p, where did the _p enter the function. It would be much appreciated if you can give me some explanation on the for loop here.

    def contraction_mapping(S, p, MF, params, beta=0.75, threshold=1e-6, suppr_output=False):
        '''
Initialization of the state-transition matrices:
        describe the state-transition probabilities if the maintenance cost is incurred,
        and regenerate the state to 0 if the replacement cost is incurred.
        '''
        ST_mat = np.zeros((S, S))
        p = np.array(p)
        for i in range(S):
            for j, _p in enumerate(p):
                if i + j < S-1:
                    ST_mat[i+j][i] = _p

                elif i + j == S-1:
                    ST_mat[S-1][i] = p[j:].sum()
                else:
                    pass

        R_mat = np.vstack((np.ones((1, S)),np.zeros((S-1, S))))


问:
How to do change the value in the class with the help of method in C#

I want to call an object from a different class and change its properties.

I want to get into this object and make changes.

But when I type the dot, the properties do not open.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            SINIF3 sınıf3 = new SINIF3();

//I want to get into this object and make changes.
//But when I type the dot, the properties do not open.
//For example
//sınıf3.gonder(1).number=2;

            Console.ReadKey();
        }
    }
    class DEGER
    {
        public int number = 1;
    }
    class SINIF3
    {
        public object gonder(int a)
        {
            DEGER objem = new DEGER();
            DEGER objem2 = new DEGER();
            if (a == 1)
                return objem;
            else return objem2;
        }
    }
}
</code>```

答:
Change the the method.

from         public object gonder(int a)

to         public DEGER gonder(int a)

otherwise you need to cast the object
something like
sınıf3.((DEGER )gonder(1)).number=2;

But you should try not to return object if you can.

Body:
I want to call an object from a different class and change its properties.

I want to get into this object and make changes.

But when I type the dot, the properties do not open.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            SINIF3 sınıf3 = new SINIF3();

//I want to get into this object and make changes.
//But when I type the dot, the properties do not open.
//For example
//sınıf3.gonder(1).number=2;

            Console.ReadKey();
        }
    }
    class DEGER
    {
        public int number = 1;
    }
    class SINIF3
    {
        public object gonder(int a)
        {
            DEGER objem = new DEGER();
            DEGER objem2 = new DEGER();
            if (a == 1)
                return objem;
            else return objem2;
        }
    }
}


问:
Get next URL using flask redirect
I am following this information here, all seems good, but I need to know how to load the originally requested url from the new login page on the second to last line.</p>

```<code>@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        if not models.check_auth(username, password):
            error = 'Please try again.'
        else:
            return redirect(url_for(**next**))
    return render_template('login.html', error=error)
</code>```

答:
Try this out:</p>

```<code>@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        if not models.check_auth(username, password):
            error = 'Please try again.'
        else:
            return redirect(request.args.get("next") or url_for("admin"))
            #               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    return render_template('login.html', error=error)
</code>```

Title: Get next URL using flask redirect

Body:
I am following this information here, all seems good, but I need to know how to load the originally requested url from the new login page on the second to last line.

@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        if not models.check_auth(username, password):
            error = 'Please try again.'
        else:
            return redirect(url_for(**next**))
    return render_template('login.html', error=error)

Body:
Try this out:

@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        if not models.check_auth(username, password):
            error = 'Please try again.'
        else:
            return redirect(request.args.get("next") or url_for("admin"))
            #               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    return render_template('login.html', error=error)


问:
ArdunioJoystickLibrary ButtonState Preference
Hello I am currently using MHeironimus's ArduinoJoystickLibrary, I have a 3 button game pad  for which I am having issues with.  My button on pin 2 is normally on, how do I reverse this in the code so that the state is normally off.

I really have no clue, I just modified the the keyboard + button joystick code to get it to work properly, I basically just need to be able to control each of the buttons initial state, because sometimes the switches/buttons might be reversed.

At first I thought it could be done with this part:

// Last state of the button
int lastButtonState[3] = {0,0,0};
```

<p>Where I would just change this <code>{0,0,0}</code> to like this <code>{0,1,0}</code> then my button on pin 3 would be normally on or in <code>HIGH</code>. But nope. Basically I just need to be able to control each of the 3 button states on the fly because I never know how a switch/button is going to react from my huge bucket of switches/buttons.</p>

<p>See code below:</p>

<pre class="lang-cpp prettyprint-override"><code>#include <Joystick.h>

Joystick_ Joystick(JOYSTICK_DEFAULT_REPORT_ID,JOYSTICK_TYPE_GAMEPAD,
  3, 0,                  // Button Count, Hat Switch Count
  false, false, false,   // X and Y, but no Z Axis
  false, false, false,   // No Rx, Ry, or Rz
  false, false,          // No rudder or throttle
  false, false, false);  // No accelerator, brake, or steering

void setup() {
  // Initialize Button Pins
  pinMode(2, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);
  pinMode(4, INPUT_PULLUP);

  // Initialize Joystick Library
  Joystick.begin();
}

// Constant that maps the phyical pin to the joystick button.
const int pinToButtonMap = 2;

// Last state of the button
int lastButtonState[3] = {0,0,0};

void loop() {

  // Read pin values
  for (int index = 0; index < 3; index++)
  {
    int currentButtonState = !digitalRead(index + pinToButtonMap);
    if (currentButtonState != lastButtonState[index])
    {
      if (index < 4) {
        Joystick.setButton(index, currentButtonState);
        lastButtonState[index] = currentButtonState;
      } else {
        if (currentButtonState) {
          Joystick.setButton(index, currentButtonState);
          lastButtonState[index] = currentButtonState;
        }
      }
    }
  }

  delay(10);
}
</code>```

答:
Define which buttons you want flipped:

bool flipButtons[3] = {false, true, false};
```

<p>and then use use it to flip it, when you read the button state:</p>

<pre class="lang-cpp prettyprint-override"><code>int currentButtonState = !digitalRead(index + pinToButtonMap) ^ flipButtons[index];
</code>```

Body:
Hello I am currently using MHeironimus's ArduinoJoystickLibrary, I have a 3 button game pad  for which I am having issues with.  My button on pin 2 is normally on, how do I reverse this in the code so that the state is normally off.

I really have no clue, I just modified the the keyboard + button joystick code to get it to work properly, I basically just need to be able to control each of the buttons initial state, because sometimes the switches/buttons might be reversed.

At first I thought it could be done with this part:

// Last state of the button
int lastButtonState[3] = {0,0,0};

Where I would just change this {0,0,0} to like this {0,1,0} then my button on pin 3 would be normally on or in HIGH. But nope. Basically I just need to be able to control each of the 3 button states on the fly because I never know how a switch/button is going to react from my huge bucket of switches/buttons.

See code below:

#include <Joystick.h>

Joystick_ Joystick(JOYSTICK_DEFAULT_REPORT_ID,JOYSTICK_TYPE_GAMEPAD,
  3, 0,                  // Button Count, Hat Switch Count
  false, false, false,   // X and Y, but no Z Axis
  false, false, false,   // No Rx, Ry, or Rz
  false, false,          // No rudder or throttle
  false, false, false);  // No accelerator, brake, or steering

void setup() {
  // Initialize Button Pins
  pinMode(2, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);
  pinMode(4, INPUT_PULLUP);

  // Initialize Joystick Library
  Joystick.begin();
}

// Constant that maps the phyical pin to the joystick button.
const int pinToButtonMap = 2;

// Last state of the button
int lastButtonState[3] = {0,0,0};

void loop() {

  // Read pin values
  for (int index = 0; index < 3; index++)
  {
    int currentButtonState = !digitalRead(index + pinToButtonMap);
    if (currentButtonState != lastButtonState[index])
    {
      if (index < 4) {
        Joystick.setButton(index, currentButtonState);
        lastButtonState[index] = currentButtonState;
      } else {
        if (currentButtonState) {
          Joystick.setButton(index, currentButtonState);
          lastButtonState[index] = currentButtonState;
        }
      }
    }
  }

  delay(10);
}

Body:
Define which buttons you want flipped:

bool flipButtons[3] = {false, true, false};

and then use use it to flip it, when you read the button state:

int currentButtonState = !digitalRead(index + pinToButtonMap) ^ flipButtons[index];


问:
Combine two rows of data using LINQ/SQL
I have a situation where my query returns the following two rows:

```<code>UserName  ID  Designation   RoleID

shd.1234   3        1          2

shd.1234   3        1          5
</code>```

I am able to display these results in a Jqgrid using LINQ.

However I want to display it as under in a single row:(if RoleID is 5, display it in another column in the same row.)

```<code>UserName  ID  Designation   RoleID    AdditionalRoleID

shd.1234   3        1          2            5
</code>```

My current query is something like this:

```<code>empDetails = (from u in ObjectContext.USERS
              join ed in ObjectContext.USERS_EMPLOYEE_DETAILS on u.UserID equals ed.UserID
              join r in ObjectContext.ROLES_FOR_USERS on u.UserID equals r.UserID
              join ro in ObjectContext.ROLES on r.RoleID equals ro.RoleID
              where (r.HospitalID == Context.CurrentUser.HIdentity.HospitalID)
              where(r.RoleID!= 4)
              select new Models.AdminModelSettings.EmployeeDetailsForGivenHospital
              {
                  UserName = u.UserName,
                  EmployeeId = ed.ID,
                  EmployeeDesignation = ed.Designation,
                  RoleID = r.RoleID,
                  RoleName = r.RoleID == 1 || r.RoleID == 2 || r.RoleID == 3 ? ro.RoleName : null,
                  AdditionalRole = r.RoleID == 5  ? ro.RoleName : null
              }).ToList();
</code>```

I would please like to know how this can be done in SQL/LINQ.

答:
UPDATE:  I've improved the code so it will do all of the work in SQL instead of returning the results and then performing the grouping.

This should do the trick!

The key part is where we order the rows by RoleID and then group the rows by ID.  It assumes that you only have a Role and an Additional Role, i.e. it won't select an AdditionalRole2 or AdditionalRole3, etc...

```<code>var empDetails = from u in ObjectContext.USERS
                 join ed in ObjectContext.USERS_EMPLOYEE_DETAILS on u.UserID equals ed.UserID
                 join r in ObjectContext.ROLES_FOR_USERS on u.UserID equals r.UserID
                 join ro in ObjectContext.ROLES on r.RoleID equals ro.RoleID
                 where (r.HospitalID == Context.CurrentUser.HIdentity.HospitalID)
                 where(r.RoleID!= 4)
                 select new Models.AdminModelSettings.EmployeeDetailsForGivenHospital
                 {
                     UserName = u.UserName,
                     EmployeeId = ed.ID,
                     EmployeeDesignation = ed.Designation,
                     RoleID = r.RoleID,
                     RoleName = r.RoleID == 1 || r.RoleID == 2 || r.RoleID == 3 ? ro.RoleName : null
                 });

var roleIDs = new List<int> { 1, 2, 3 };

//group our results and order the group by the role id
var temp = empDetails.GroupBy(row => row.ID).Select(g => new { First = g.FirstOrDefault(r => roleIDs.Contains(r.RoleID)), Last = g.FirstOrDefault(r => r.RoleID == 5) });

//select the data into the shape that we want
var query = temp.Select(result => new Models.AdminModelSettings.EmployeeDetailsForGivenHospital
{
    UserName = (result.First ?? result.Last).UserName,
    EmployeeId = (result.First ?? result.Last).ID,
    EmployeeDesignation = (result.First ?? result.Last).Designation,
    RoleID = (result.First == null) ? (int?)null : result.First.RoleID,
    AdditionalRoleID = (result.Last == null) ? (int?)null : result.Last.RoleID
});
</code>```

Title: Combine two rows of data using LINQ/SQL

Body:
I have a situation where my query returns the following two rows:

UserName  ID  Designation   RoleID

shd.1234   3        1          2

shd.1234   3        1          5

I am able to display these results in a Jqgrid using LINQ.

However I want to display it as under in a single row:(if RoleID is 5, display it in another column in the same row.)

UserName  ID  Designation   RoleID    AdditionalRoleID

shd.1234   3        1          2            5

My current query is something like this:

empDetails = (from u in ObjectContext.USERS
              join ed in ObjectContext.USERS_EMPLOYEE_DETAILS on u.UserID equals ed.UserID
              join r in ObjectContext.ROLES_FOR_USERS on u.UserID equals r.UserID
              join ro in ObjectContext.ROLES on r.RoleID equals ro.RoleID
              where (r.HospitalID == Context.CurrentUser.HIdentity.HospitalID)
              where(r.RoleID!= 4)
              select new Models.AdminModelSettings.EmployeeDetailsForGivenHospital
              {
                  UserName = u.UserName,
                  EmployeeId = ed.ID,
                  EmployeeDesignation = ed.Designation,
                  RoleID = r.RoleID,
                  RoleName = r.RoleID == 1 || r.RoleID == 2 || r.RoleID == 3 ? ro.RoleName : null,
                  AdditionalRole = r.RoleID == 5  ? ro.RoleName : null
              }).ToList();

I would please like to know how this can be done in SQL/LINQ.

Body:
UPDATE:  I've improved the code so it will do all of the work in SQL instead of returning the results and then performing the grouping.

This should do the trick!

The key part is where we order the rows by RoleID and then group the rows by ID.  It assumes that you only have a Role and an Additional Role, i.e. it won't select an AdditionalRole2 or AdditionalRole3, etc...

var empDetails = from u in ObjectContext.USERS
                 join ed in ObjectContext.USERS_EMPLOYEE_DETAILS on u.UserID equals ed.UserID
                 join r in ObjectContext.ROLES_FOR_USERS on u.UserID equals r.UserID
                 join ro in ObjectContext.ROLES on r.RoleID equals ro.RoleID
                 where (r.HospitalID == Context.CurrentUser.HIdentity.HospitalID)
                 where(r.RoleID!= 4)
                 select new Models.AdminModelSettings.EmployeeDetailsForGivenHospital
                 {
                     UserName = u.UserName,
                     EmployeeId = ed.ID,
                     EmployeeDesignation = ed.Designation,
                     RoleID = r.RoleID,
                     RoleName = r.RoleID == 1 || r.RoleID == 2 || r.RoleID == 3 ? ro.RoleName : null
                 });

var roleIDs = new List<int> { 1, 2, 3 };

//group our results and order the group by the role id
var temp = empDetails.GroupBy(row => row.ID).Select(g => new { First = g.FirstOrDefault(r => roleIDs.Contains(r.RoleID)), Last = g.FirstOrDefault(r => r.RoleID == 5) });

//select the data into the shape that we want
var query = temp.Select(result => new Models.AdminModelSettings.EmployeeDetailsForGivenHospital
{
    UserName = (result.First ?? result.Last).UserName,
    EmployeeId = (result.First ?? result.Last).ID,
    EmployeeDesignation = (result.First ?? result.Last).Designation,
    RoleID = (result.First == null) ? (int?)null : result.First.RoleID,
    AdditionalRoleID = (result.Last == null) ? (int?)null : result.Last.RoleID
});