问:
Eliminating IF statement from this code
I have this C function which basically takes the input from the user and saves it in a static char[]. Then it checks whether it is empty. If it is empty then it prints an error, else appends a file extension to it. Here's the piece of code I'm concerned about:

const char* text_entry(){
    char c;
    while((c=getchar())!='\n' && c!=EOF);
    static char input[20];
    fgets(input, sizeof(input),stdin);
    input[strcspn(input,"\n")]=0;
    if(strlen(input)>0){
        strncat(input, ".txt",4);
        return input;
    }
    printf("Error! no text entered!");
    return NULL;
}
```

My concern is that I want to remove the IF statement from it, making it more DRY. How can I do that?

答:
I did not shorten your code, but I think you might find this solution more resilient, using the libreadline -lreadline

Before your returned a buffer which was declared on the stack, which means that it is unallocated on return, but yet you return its address. This is a bug.

I fixed it and gave you the opportunity to take a buffer and buffer size in parameters, as well as the extension, so the caller manages the memory for you as well as his maximum string length needs.

The loop now handles maximum input size well. It might not be shorter, but it should prove resilient.

```<code>/*
** Args:
** input_buffer: a buffer that will be whiped then filled with the user input
** buffer_size: the total size of the input buffer (maximum result length)
** extension: a dotted file type extension
**
** Returns: 0 on error or the input_buffer
*/
const char* text_entry(char *buffer, size_t buffer_size, char *extension) {
  int maxsize = buffer_size - strlen(extension) - 1;
  char *user_input;
  int user_input_len;

  do {
    user_input = readline("Enter a file name: ");
    user_input_len = strlen(user_input);
    if (user_input_len > maxsize) {
      printf("The name is too long! %d characters maximum. Try again.\n", maxsize);
      free(user_input);
    }
  } while (!user_input_len || user_input_len > maxsize);
  strcpy(buffer, user_input);
  free(user_input);
  strcat(buffer, extension);
  printf("%s\n", buffer);
  return buffer;
}
</code>```

Title: Eliminating IF statement from this code

Body:
I have this C function which basically takes the input from the user and saves it in a static char[]. Then it checks whether it is empty. If it is empty then it prints an error, else appends a file extension to it. Here's the piece of code I'm concerned about:

const char* text_entry(){
    char c;
    while((c=getchar())!='\n' && c!=EOF);
    static char input[20];
    fgets(input, sizeof(input),stdin);
    input[strcspn(input,"\n")]=0;
    if(strlen(input)>0){
        strncat(input, ".txt",4);
        return input;
    }
    printf("Error! no text entered!");
    return NULL;
}

My concern is that I want to remove the IF statement from it, making it more DRY. How can I do that?

Body:
I did not shorten your code, but I think you might find this solution more resilient, using the libreadline -lreadline

Before your returned a buffer which was declared on the stack, which means that it is unallocated on return, but yet you return its address. This is a bug.

I fixed it and gave you the opportunity to take a buffer and buffer size in parameters, as well as the extension, so the caller manages the memory for you as well as his maximum string length needs.

The loop now handles maximum input size well. It might not be shorter, but it should prove resilient.

/*
** Args:
** input_buffer: a buffer that will be whiped then filled with the user input
** buffer_size: the total size of the input buffer (maximum result length)
** extension: a dotted file type extension
**
** Returns: 0 on error or the input_buffer
*/
const char* text_entry(char *buffer, size_t buffer_size, char *extension) {
  int maxsize = buffer_size - strlen(extension) - 1;
  char *user_input;
  int user_input_len;

  do {
    user_input = readline("Enter a file name: ");
    user_input_len = strlen(user_input);
    if (user_input_len > maxsize) {
      printf("The name is too long! %d characters maximum. Try again.\n", maxsize);
      free(user_input);
    }
  } while (!user_input_len || user_input_len > maxsize);
  strcpy(buffer, user_input);
  free(user_input);
  strcat(buffer, extension);
  printf("%s\n", buffer);
  return buffer;
}


来源: stackexchange

问:
python xlwt set custom background colour of a cell
I am using python 2.7 and xlwt module for excel export

I would like to set backgroung colour of a cell
i know i can use

```<code>style1 = xlwt.easyxf('pattern: pattern solid, fore_colour red;')
</code>```

but I would like to set custom color smth. like #8a8eef
or is there a palette of possible colors, because light blue is not working :)

thank you

答:
I recommend to use XlsxWriter, has awesome features too.
http://xlsxwriter.readthedocs.io/</p>

ContentLicense: CC BY-SA 3.0

Body:
I am using python 2.7 and xlwt module for excel export

I would like to set backgroung colour of a cell
i know i can use

style1 = xlwt.easyxf('pattern: pattern solid, fore_colour red;')

but I would like to set custom color smth. like #8a8eef
or is there a palette of possible colors, because light blue is not working :)

thank you


问:
Post to Form with XML Media Type in Spring
I'm trying to post form data with Spring. That form data is XML format. But every time I try posting, I get a 415 error.

```<code>public void setFormData(String name, Integer age){
  String url = "https://my.example.com/path/";

  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.APPLICATION_XML);

  Form form = new Form();

  form.set("name", name);
  form.set("age", age);

  HttpEntity<Object> request = new HttpEntity<Object>(form, headers);
  RestTemplate restTemplate = new RestTemplate();
  restTemplate.put(url, request);

}
</code>```

Since the above didn't work, I went and implemented this:

```<code>public void setFormData(String name, Integer age){
  String url = "https://my.example.com/";

  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.APPLICATION_XML);

  MultiValueMap<String, Object> params= new LinkedMultiValueMap<String, Object>();
  params.add("name", name);
  params.add("age", age);

  HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<MultiValueMap<String, Object>>(map, headers);
  RestTemplate restTemplate = new RestTemplate();

  List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
  Jaxb2RootElementHttpMessageConverter jaxbMessageConverter = new Jaxb2RootElementHttpMessageConverter();
  List<MediaType> mediaTypes = new ArrayList<MediaType>();
  mediaTypes.add(MediaType.APPLICATION_XML);
  jaxbMessageConverter.setSupportedMediaTypes(mediaTypes);
  messageConverters.add(jaxbMessageConverter);
  restTemplate.setMessageConverters(messageConverters);

}
</code>```

XML that accepts the request:

```<code><resource path="/path">
  <method name="POST">
   <request>
    <representation mediaType="application/x-www-form-urlencoded">
     <param name="name" style="query" type="xs:string">
     <param name="age" style="query" type="xs:int">
    </representation>
   </request>
  </method>
</resource>
</code>```

But I still got the 415 error. I've also tried setting the MediaType to     APPLICATION_FORM_URLENCODED in the Java code but I get the 415 error. How can I post to XML form using Spring? Any help would be appreciated.

答:
Change your ContentType to APPLICATION_FORM_URLENCODED in the first blob. The 2nd blob of code that messes with Http message converters is useless. I'm not sure what the Form is that you're populating - MultiValueMap should work as well.

Use POST method, not PUT. Either postForEntity or postForObject should do it.

Truth be told, I've never seen a Spring controller declared in XML like yours above, and I'm a Spring committer. Have you considered using annotations? The world stopped using XML Spring config in 2011.

Body:
I'm trying to post form data with Spring. That form data is XML format. But every time I try posting, I get a 415 error.

public void setFormData(String name, Integer age){
  String url = "https://my.example.com/path/";

  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.APPLICATION_XML);

  Form form = new Form();

  form.set("name", name);
  form.set("age", age);

  HttpEntity<Object> request = new HttpEntity<Object>(form, headers);
  RestTemplate restTemplate = new RestTemplate();
  restTemplate.put(url, request);

}

Since the above didn't work, I went and implemented this:

public void setFormData(String name, Integer age){
  String url = "https://my.example.com/";

  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.APPLICATION_XML);

  MultiValueMap<String, Object> params= new LinkedMultiValueMap<String, Object>();
  params.add("name", name);
  params.add("age", age);

  HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<MultiValueMap<String, Object>>(map, headers);
  RestTemplate restTemplate = new RestTemplate();

  List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
  Jaxb2RootElementHttpMessageConverter jaxbMessageConverter = new Jaxb2RootElementHttpMessageConverter();
  List<MediaType> mediaTypes = new ArrayList<MediaType>();
  mediaTypes.add(MediaType.APPLICATION_XML);
  jaxbMessageConverter.setSupportedMediaTypes(mediaTypes);
  messageConverters.add(jaxbMessageConverter);
  restTemplate.setMessageConverters(messageConverters);

}

XML that accepts the request:

<resource path="/path">
  <method name="POST">
   <request>
    <representation mediaType="application/x-www-form-urlencoded">
     <param name="name" style="query" type="xs:string">
     <param name="age" style="query" type="xs:int">
    </representation>
   </request>
  </method>
</resource>

But I still got the 415 error. I've also tried setting the MediaType to     APPLICATION_FORM_URLENCODED in the Java code but I get the 415 error. How can I post to XML form using Spring? Any help would be appreciated.


问:
AWS Step Functions history event limitation
I use step functions for a big loop, so far no problem, but the day when my loop exceeded 8000 executions I came across the error "Maximum execution history size" which is 25000.

There is there a solution for not having the history events?

Otherwise, where I can easily migrate my step functions (3 lambda) because aws batch will ask me a lot of code rewrite ..

Thanks a lot

答:
One approach to avoid the 25k history event limit is to add a choice state in your loop that takes in a counter or boolean and decides to exit the loop.

Outside of the loop you can put a lambda function that starts another execution (with a different id).  After this, your current execution completes normally and another execution will continue to do the work.

Please note that the "LoopProcessor" in the example below must return a variable "$.breakOutOfLoop" to break out of the loop, which must also be determined somewhere in your loop and passed through.

Depending on your use case, you may need to restructure the data you pass around.  For example, if you are processing a lot of data, you may want to consider using S3 objects and pass the ARN as input/output through the state machine execution. If you are trying to do a simple loop, one easy way would be to add a start offset (think of it as a global counter) that is passed into the execution as input, and each LoopProcessor Task will increment a counter (with the start offset as the initial value).  This is similar to pagination solutions.

Here is a basic example of the ASL structure to avoid the 25k history event limit:

```<code>{
  "Comment": "An example looping while avoiding the 25k event history limit.",
  "StartAt": "FirstState",
  "States": {

    "FirstState": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:REGION:ACCOUNT_ID:function:FUNCTION_NAME",
      "Next": "ChoiceState"
    },

    "ChoiceState": {
      "Type" : "Choice",
      "Choices": [
        {
          "Variable": "$.breakOutOfLoop",
          "BooleanEquals": true,
          "Next": "StartNewExecution"
        }
      ],
      "Default": "LoopProcessor"
    },

    "LoopProcessor": {
      "Type" : "Task",
      "Resource": "arn:aws:lambda:REGION:ACCOUNT_ID:function:ProcessWork",
      "Next": "ChoiceState"
    },

    "StartNewExecution": {
      "Type" : "Task",
      "Resource": "arn:aws:lambda:REGION:ACCOUNT_ID:function:StartNewLooperExecution",
      "Next": "FinalState"
    },

    "FinalState": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:REGION:ACCOUNT_ID:function:FUNCTION_NAME",
      "End": true
    }
  }
}
</code>```

Hope this helps!

Body:
One approach to avoid the 25k history event limit is to add a choice state in your loop that takes in a counter or boolean and decides to exit the loop.

Outside of the loop you can put a lambda function that starts another execution (with a different id).  After this, your current execution completes normally and another execution will continue to do the work.

Please note that the "LoopProcessor" in the example below must return a variable "$.breakOutOfLoop" to break out of the loop, which must also be determined somewhere in your loop and passed through.

Depending on your use case, you may need to restructure the data you pass around.  For example, if you are processing a lot of data, you may want to consider using S3 objects and pass the ARN as input/output through the state machine execution. If you are trying to do a simple loop, one easy way would be to add a start offset (think of it as a global counter) that is passed into the execution as input, and each LoopProcessor Task will increment a counter (with the start offset as the initial value).  This is similar to pagination solutions.

Here is a basic example of the ASL structure to avoid the 25k history event limit:

{
  "Comment": "An example looping while avoiding the 25k event history limit.",
  "StartAt": "FirstState",
  "States": {

    "FirstState": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:REGION:ACCOUNT_ID:function:FUNCTION_NAME",
      "Next": "ChoiceState"
    },

    "ChoiceState": {
      "Type" : "Choice",
      "Choices": [
        {
          "Variable": "$.breakOutOfLoop",
          "BooleanEquals": true,
          "Next": "StartNewExecution"
        }
      ],
      "Default": "LoopProcessor"
    },

    "LoopProcessor": {
      "Type" : "Task",
      "Resource": "arn:aws:lambda:REGION:ACCOUNT_ID:function:ProcessWork",
      "Next": "ChoiceState"
    },

    "StartNewExecution": {
      "Type" : "Task",
      "Resource": "arn:aws:lambda:REGION:ACCOUNT_ID:function:StartNewLooperExecution",
      "Next": "FinalState"
    },

    "FinalState": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:REGION:ACCOUNT_ID:function:FUNCTION_NAME",
      "End": true
    }
  }
}

Hope this helps!


问:
Insert data to a SQL Server database that contains apostrophes
I'm making this program on Vb.net 2012 that has a connection to SQL Server 2012.

One of the columns of this database table is Description, and in some cases the date may include apostrophes, for example... 'chainsaw 15'3" X 1 1/2 X .050 X 3/4'

When I run the query the apostrophe that is between the data causes an error at the syntax of the query, this is the query line in VB.net.

```<code>CMD.CommandText =
"INSERT INTO Table_ARTICLES
 (NUMPART, DESCRIPTION, LOCATION, MAX, ACTUAL, MIN, Unidad_de_medida)
 VALUES ('" & txtNumParte.Text & "', '" & txtDescripcion.Text & "',
  '" & txtLocaclizacion.Text & "', '" & txtMaximo.Text & "', '" & txtActual.Text & "',
  '" & txtMin.Text & "', '" & cmbUnidad.Text & "')"
</code>```

Does anybody know how to make this query accept those characters on the query?

答:
Please use parameterized SQL (i.e. stored procedures) to prevent SQL injection and the like.

As for your question, you would want to replace the single quote (apostrophe) with two single quotes before you add it as a parameter. This way the first one acts as an escape character which will allow for the apostrophe to be inserted into the database.

Example:
txtNumParte.Text.Replace("'", "''")

Body:
I'm making this program on Vb.net 2012 that has a connection to SQL Server 2012.

One of the columns of this database table is Description, and in some cases the date may include apostrophes, for example... 'chainsaw 15'3" X 1 1/2 X .050 X 3/4'

When I run the query the apostrophe that is between the data causes an error at the syntax of the query, this is the query line in VB.net.

CMD.CommandText =
"INSERT INTO Table_ARTICLES
 (NUMPART, DESCRIPTION, LOCATION, MAX, ACTUAL, MIN, Unidad_de_medida)
 VALUES ('" & txtNumParte.Text & "', '" & txtDescripcion.Text & "',
  '" & txtLocaclizacion.Text & "', '" & txtMaximo.Text & "', '" & txtActual.Text & "',
  '" & txtMin.Text & "', '" & cmbUnidad.Text & "')"

Does anybody know how to make this query accept those characters on the query?


问:
Tracking SQL Calls From MS Access to MySQL
I'm trying to 'see' the SQL statements that are sent from MS Access 2003 to MySQL via ODBC.

I've tried ODBC Tracing, but it's painfully slow, producing very large log files which are very difficult to read.

For example, and insert looked like this:

```<code>"INSERT INTO  `tracking`  (`contract_id`,`bp_id`,`csi_1`,`csi_2a`,`csi_2b`,`csi_code`,`item_number`,`csi_code_display`,`csi_name`)
VALUES (?,?,?,?,?,?,?,?,?)\ 0"
</code>```

It doesn't show the values, I think they are coded separately as SQLBindParameters, but I can't make out the values in those either.

Is there an alternate/better method that I can use to simply see the full SQL statements?

MTIA

答:
I don't know why this question popped up today in the "new questions" list, but it did, and I just Googled "sql profiler for mysql" and came up with this:

http://dev.mysql.com/tech-resources/articles/using-new-query-profiler.html

I don't know if it is better, or if it works with the version of MySQL used by the original question, but I thought it might be useful to others who came to the question.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to 'see' the SQL statements that are sent from MS Access 2003 to MySQL via ODBC.

I've tried ODBC Tracing, but it's painfully slow, producing very large log files which are very difficult to read.

For example, and insert looked like this:

"INSERT INTO  `tracking`  (`contract_id`,`bp_id`,`csi_1`,`csi_2a`,`csi_2b`,`csi_code`,`item_number`,`csi_code_display`,`csi_name`)
VALUES (?,?,?,?,?,?,?,?,?)\ 0"

It doesn't show the values, I think they are coded separately as SQLBindParameters, but I can't make out the values in those either.

Is there an alternate/better method that I can use to simply see the full SQL statements?

MTIA


问:
Detect Private Browsing - Safari Issue
I am trying to detect if a user is viewing a website in a private browser. I have the below code/fiddle that works in Chrome and Firefox but not Safari. Can anyone see what the issue is for Safari? Thank you in advance.

```<code>new Promise(resolve => {
let db,
on = () => alert('yes'),
off = () => alert('no'),
tryls = () => {
    try {
        localStorage.length ? off() : (localStorage.x = 1, localStorage.removeItem("x"), off())
    } catch (e) {
        on()
    }
}

// Blink
window.webkitRequestFileSystem ?
    webkitRequestFileSystem(window.TEMPORARY, 1, off, on)

// FF
: "MozAppearance" in document.documentElement.style ?
    (db = indexedDB.open("test"), db.onerror = on, db.onsuccess = off)

// Safari
: /constructor/i.test(window.HTMLElement) ?
    tryls()

// IE10+ & edge
: !window.indexedDB && (window.PointerEvent || window.MSPointerEvent) ?
    on()

// Rest
: off()
 }).then(enabled => {
document.body.innerHTML = enabled
})
</code>```

https://jsfiddle.net/ndyL5mxf/

答:
I found a solution for anyone that may come across. Safari in private mode doesn't handle local storage so the below codes tests to see if there is local storage and if it doesn't, do something. Worked for my issue.</p>

```<code>var storageTestKey = 'test';
var storage = window.sessionStorage;
try {
     storage.setItem(storageTestKey, 'test');
     storage.removeItem(storageTestKey);
    } catch (e) {
    if (e.code === DOMException.QUOTA_EXCEEDED_ERR && storage.length === 0) {
        console.log('private widow')
    } else {
        console.log('not private')
    }
}
</code>```

Title: Detect Private Browsing - Safari Issue

Body:
I am trying to detect if a user is viewing a website in a private browser. I have the below code/fiddle that works in Chrome and Firefox but not Safari. Can anyone see what the issue is for Safari? Thank you in advance.

new Promise(resolve => {
let db,
on = () => alert('yes'),
off = () => alert('no'),
tryls = () => {
    try {
        localStorage.length ? off() : (localStorage.x = 1, localStorage.removeItem("x"), off())
    } catch (e) {
        on()
    }
}

// Blink
window.webkitRequestFileSystem ?
    webkitRequestFileSystem(window.TEMPORARY, 1, off, on)

// FF
: "MozAppearance" in document.documentElement.style ?
    (db = indexedDB.open("test"), db.onerror = on, db.onsuccess = off)

// Safari
: /constructor/i.test(window.HTMLElement) ?
    tryls()

// IE10+ & edge
: !window.indexedDB && (window.PointerEvent || window.MSPointerEvent) ?
    on()

// Rest
: off()
 }).then(enabled => {
document.body.innerHTML = enabled
})

https://jsfiddle.net/ndyL5mxf/

Body:
I found a solution for anyone that may come across. Safari in private mode doesn't handle local storage so the below codes tests to see if there is local storage and if it doesn't, do something. Worked for my issue.

var storageTestKey = 'test';
var storage = window.sessionStorage;
try {
     storage.setItem(storageTestKey, 'test');
     storage.removeItem(storageTestKey);
    } catch (e) {
    if (e.code === DOMException.QUOTA_EXCEEDED_ERR && storage.length === 0) {
        console.log('private widow')
    } else {
        console.log('not private')
    }
}


问:
Removing ambiguity when using sqrt() function in a template class
I have a complex number class where I am trying to implement a function to work out the modulus (which requires the used of a sqrt).

My header file is as follows:

```<code>#ifndef MY_CLASS_H
#define MY_CLASS_H

template <class T> class complex
{
    // function to overload operator<< a friend
    template <class T>
    friend std::ostream& operator<< (std::ostream &os, const complex<T> &z);
private:
    T re,im;
public:

    // Constructors & destructor
    complex(){re=im=0;}
    complex( const T& r, const T& i ) : re(r), im(i) {}
    ~complex(){}

    // Return real component
    T realcomp() const {return re;}
    // Return imaginary component
    T imagcomp() const {return im;}
    // Return modulus
    double modulus() {return sqrt(im*im + re*re);}

etc....
</code>```

The compiler outputs the error:

```<code>error C2668: 'sqrt' : ambiguous call to overloaded function
 could be 'long double sqrt(long double)'
 or       'float sqrt(float)'
 or       'double sqrt(double)'
</code>```

which I know is telling me that the sqrt needs to know what type of data it is passing through it.

For my program, im and re will take either double or int values.

Am I right in saying sqrt will only take floating values? If so how do I force im and re to floating points without a 'loss of data' warning. Can I do this without converting them?

答:
My problem was similar: I'm expanding my old source to make it fit for an additional use of mpreal - an annoying job. One of the last problems: a little statement in a big template:

```<code>`T help = sqrt(g.eval(f.eval(a))());`
</code>```

I had to struggle .. whatever I tried was failing - very different error messages, some looking crazy, like illegal conversion from complex sqrt, but I used only float types; converting mpreal to long double throwing away precision.
 if(std::is_floating_point<T>::value) ..
and if(std::is_same<T,long double>::value) .. were giving misleading error messages, especially when T was long double,
using std:: and mpfr:: in then- respective else-part was leading to not resolvable type errors in then- or else-part depending on T.

I would have found a solution here - if I only had known the source of my problem ...

My solution:

```<code>inline long double wurz(long double x) { return std::sqrt(x); };
inline mpreal wurz(mpreal x) { return sqrt(x); };

template<class T>
  ....
  real_word helpa2 = wurz(g.eval(f.eval(a))());
</code>```

I found this page here when I wanted to ask, if there's a more natural, less stupid solution than mine ..

Body:
I have a complex number class where I am trying to implement a function to work out the modulus (which requires the used of a sqrt).

My header file is as follows:

#ifndef MY_CLASS_H
#define MY_CLASS_H

template <class T> class complex
{
    // function to overload operator<< a friend
    template <class T>
    friend std::ostream& operator<< (std::ostream &os, const complex<T> &z);
private:
    T re,im;
public:

    // Constructors & destructor
    complex(){re=im=0;}
    complex( const T& r, const T& i ) : re(r), im(i) {}
    ~complex(){}

    // Return real component
    T realcomp() const {return re;}
    // Return imaginary component
    T imagcomp() const {return im;}
    // Return modulus
    double modulus() {return sqrt(im*im + re*re);}

etc....

The compiler outputs the error:

error C2668: 'sqrt' : ambiguous call to overloaded function
 could be 'long double sqrt(long double)'
 or       'float sqrt(float)'
 or       'double sqrt(double)'

which I know is telling me that the sqrt needs to know what type of data it is passing through it.

For my program, im and re will take either double or int values.

Am I right in saying sqrt will only take floating values? If so how do I force im and re to floating points without a 'loss of data' warning. Can I do this without converting them?

Body:
My problem was similar: I'm expanding my old source to make it fit for an additional use of mpreal - an annoying job. One of the last problems: a little statement in a big template:

`T help = sqrt(g.eval(f.eval(a))());`

I had to struggle .. whatever I tried was failing - very different error messages, some looking crazy, like illegal conversion from complex sqrt, but I used only float types; converting mpreal to long double throwing away precision.
 if(std::is_floating_point<T>::value) ..
and if(std::is_same<T,long double>::value) .. were giving misleading error messages, especially when T was long double,
using std:: and mpfr:: in then- respective else-part was leading to not resolvable type errors in then- or else-part depending on T.

I would have found a solution here - if I only had known the source of my problem ...

My solution:

inline long double wurz(long double x) { return std::sqrt(x); };
inline mpreal wurz(mpreal x) { return sqrt(x); };

template<class T>
  ....
  real_word helpa2 = wurz(g.eval(f.eval(a))());

I found this page here when I wanted to ask, if there's a more natural, less stupid solution than mine ..


问:
How to properly Redirect with React Router 4?
A little background. I am using Firebase Authentication (GitHub, Twitter and Facebook), when the user gets authenticated, the app should redirect to Updater component from the SocialButtonList component.

Now I am trying to use Redirect to: string when the user gets authenticated, but for some reason is not working, maybe I am misunderstanding the docs.

My top level container

```<code>const App = () => {
  return (
    <Router>
      <div>
        <Switch>
          <Route path='/updater' component={Updater} />
          <Route exact path='/' component={Login} />
          <Route component={NoMatch}/>
        </Switch>
      </div>
    </Router>
  );
}
</code>```

Login.js

```<code>const Home = () => {
  return (
    <Content align='center'>
      ...
      <SocialButtonList size={SOCIAL_BUTTON_SIZE_BIG} />
      ...
    </Content>
  );
}
</code>```

SocialButtonList.js
This component handles the authentication logic and upon authenticating I call authHandler and from here I am attempting to redirect to the 'Updater' component.

```<code>authHandler = authData => {
  if (authData) {
    <Redirect to='/updater' />
    console.log('AUTHENTICATED');
  } else {
    console.info('User is signed out!');
  }
}
</code>```

In console I can see AUTHENTICATED message, but the app does not redirect. How can I properly redirect to Updater component?

Update I found a way to redirect using withRouter. See my answer below in the answer section.

答:
Well, I found my answer using withRouter instead of Redirect

```<code>import { withRouter } from 'react-router-dom';
...
authHandler = authData => {
  if (authData) {
    //<Redirect to={Updater} />
    this.props.history.push('/updater');
    console.log('AUTHENTICATED');
  } else {
    console.info('User is signed out!');
  }
}
...
export default withRouter(SocialButtonList);
</code>```

This successfully redirects to Updater component.

Now I am wondering, is there a way to get Redirect to work?

Body:
A little background. I am using Firebase Authentication (GitHub, Twitter and Facebook), when the user gets authenticated, the app should redirect to Updater component from the SocialButtonList component.

Now I am trying to use Redirect to: string when the user gets authenticated, but for some reason is not working, maybe I am misunderstanding the docs.

My top level container

const App = () => {
  return (
    <Router>

        <Switch>
          <Route path='/updater' component={Updater} />
          <Route exact path='/' component={Login} />
          <Route component={NoMatch}/>
        </Switch>

    </Router>
  );
}

Login.js

const Home = () => {
  return (
    <Content align='center'>
      ...
      <SocialButtonList size={SOCIAL_BUTTON_SIZE_BIG} />
      ...
    </Content>
  );
}

SocialButtonList.js
This component handles the authentication logic and upon authenticating I call authHandler and from here I am attempting to redirect to the 'Updater' component.

authHandler = authData => {
  if (authData) {
    <Redirect to='/updater' />
    console.log('AUTHENTICATED');
  } else {
    console.info('User is signed out!');
  }
}

In console I can see AUTHENTICATED message, but the app does not redirect. How can I properly redirect to Updater component?

Update I found a way to redirect using withRouter. See my answer below in the answer section.

Body:
Well, I found my answer using withRouter instead of Redirect

import { withRouter } from 'react-router-dom';
...
authHandler = authData => {
  if (authData) {
    //<Redirect to={Updater} />
    this.props.history.push('/updater');
    console.log('AUTHENTICATED');
  } else {
    console.info('User is signed out!');
  }
}
...
export default withRouter(SocialButtonList);

This successfully redirects to Updater component.

Now I am wondering, is there a way to get Redirect to work?


问:
PHP Arrays. Get value from array with arrays
I have array in PHP:

```<code>Array
(
  [1] => Array
    (
        [DeviceName] => Device1
        [DeviceId] => 0x0000001530A1B380
        [state] => 0
        ...
         )
  [2] => Array
    (
        [DeviceName] => Device2
        [DeviceId] => 0x0000001530A10C80
        [state] => 1
        ...
    )
  [3] => Array
    (
        [DeviceName] => Device3
        [DeviceId] => 0x0000001531471600
        [state] => 0
        ...
    )
  ...
)
</code>```

How I can get values of state and DeviceId keys only from the array where DeviceName = Device2?

I have tried this, but it returns deviceID from another array:

```<code>foreach ($values as $B) {
    $B = preg_replace('~[\r\n]+~', '', $B);
    if ($B['DeviceName'] == $Device) {
        print "Device ID: ".$B['DeviceId']."\n";
    }
}
</code>```

答:
You can simply access it using for each loop

```<code>foreach ($array as $row) {
  if ($row['DeviceName'] == 'Device2') {
    echo $row['DeviceId'];
    echo $row['state'];
  }
}
</code>```

Here is the live link based on your array Link

Body:
I have array in PHP:

Array
(
  [1] => Array
    (
        [DeviceName] => Device1
        [DeviceId] => 0x0000001530A1B380
        [state] => 0
        ...
         )
  [2] => Array
    (
        [DeviceName] => Device2
        [DeviceId] => 0x0000001530A10C80
        [state] => 1
        ...
    )
  [3] => Array
    (
        [DeviceName] => Device3
        [DeviceId] => 0x0000001531471600
        [state] => 0
        ...
    )
  ...
)

How I can get values of state and DeviceId keys only from the array where DeviceName = Device2?

I have tried this, but it returns deviceID from another array:

foreach ($values as $B) {
    $B = preg_replace('~[\r\n]+~', '', $B);
    if ($B['DeviceName'] == $Device) {
        print "Device ID: ".$B['DeviceId']."\n";
    }
}

Body:
You can simply access it using for each loop

foreach ($array as $row) {
  if ($row['DeviceName'] == 'Device2') {
    echo $row['DeviceId'];
    echo $row['state'];
  }
}

Here is the live link based on your array Link


问:
Fluent NHibernate: How to have a one-to-many reference in both directions?
We have Users on our system and Persons.  There are many Persons for each User.  But when a user logs on, we need to look up his primary Person record to fill in his name, address, phone, etc.

```<code>public class Person
{
    /// <summary>Every Person belongs to a user.</summary>
    public virtual User User { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual string Address { get; set; }
    public virtual string Phone { get; set; }
    // More methods & Properties
}

public class User : Entity
{
    public virtual string Username { get; set; }
    public virtual string Password { get; set; }
    /// <summary>Every User has a primary person record.</summary>
    public virtual Person PrimaryPerson { get; set; }
    // More methods & Properties
}
</code>```

How does the class map look for this without a circular reference?

答:
Based on my comment on your question, I think the mapping would be something along the lines of:

```<code>public class PersonMap : ClassMap<Person>
{
    public PersonMap()
    {
        Id(x => x.Id)...
        ...
        References(x => x.User).Inverse(); // User references Person
    }
}

public class UserMap : ClassMap<User>
{
    public UserMap()
    {
        Id(x => x.Id)...
        ...
        References(x => x.PrimaryPerson).Column("PrimaryPersonId")...
        HasMany(x => x.People).KeyColumn("UserId").Inverse(); // UserId is on the Person
    }
}
</code>```

Edit: Added Table Structure.

```<code>
[User]
UserId
... -- Other Columns
PrimaryPersonId  -- FK to PersonId in Person table

[Person]
PersonId
... -- Other Columns
UserId -- FK to UserId in User Table for user has many Persons.
</code>```

Body:
We have Users on our system and Persons.  There are many Persons for each User.  But when a user logs on, we need to look up his primary Person record to fill in his name, address, phone, etc.

public class Person
{
    /// Every Person belongs to a user.
    public virtual User User { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual string Address { get; set; }
    public virtual string Phone { get; set; }
    // More methods & Properties
}

public class User : Entity
{
    public virtual string Username { get; set; }
    public virtual string Password { get; set; }
    /// Every User has a primary person record.
    public virtual Person PrimaryPerson { get; set; }
    // More methods & Properties
}

How does the class map look for this without a circular reference?

Body:
Based on my comment on your question, I think the mapping would be something along the lines of:

public class PersonMap : ClassMap<Person>
{
    public PersonMap()
    {
        Id(x => x.Id)...
        ...
        References(x => x.User).Inverse(); // User references Person
    }
}

public class UserMap : ClassMap<User>
{
    public UserMap()
    {
        Id(x => x.Id)...
        ...
        References(x => x.PrimaryPerson).Column("PrimaryPersonId")...
        HasMany(x => x.People).KeyColumn("UserId").Inverse(); // UserId is on the Person
    }
}

Edit: Added Table Structure.

[User]
UserId
... -- Other Columns
PrimaryPersonId  -- FK to PersonId in Person table

[Person]
PersonId
... -- Other Columns
UserId -- FK to UserId in User Table for user has many Persons.


问:
How to run two python application in docker
I want to run two python applicaiton in docker with different ports.

My shell script is below, the name is serverRun.sh

```<code>exec python __server_code.py &
exec python server_time_test.py &
</code>```

in dockerfile, I am trying to run these two python application

```<code>RUN ["chmod", "+x", "./serverRun.sh"]
</code>```

It did not work. Any idea?

答: Looks like your run command just sets the file permissions, it doesn't actually execute the script. Perhaps change the run command. </p>

Body:
I want to run two python applicaiton in docker with different ports.

My shell script is below, the name is serverRun.sh

exec python __server_code.py &
exec python server_time_test.py &

in dockerfile, I am trying to run these two python application

RUN ["chmod", "+x", "./serverRun.sh"]

It did not work. Any idea?


问:
react native failed to install firebase
I am trying to install firebase to my react native project. To do so I have tried several ways based on few sources. I open cmd, move to the project's directory, and tried these:

npm install --save firebase

npm install firebase --save

npm i react-native-firebase --save

But unfortunately, none of this is able to install the firebase to my react native project. For the no 1 and 2, it says:

```<code>npm ERR! Cannot read property 'find' of undefined
</code>```

For no 3 it says:

```<code>npm ERR! path C:\Users\User\AndroidStudioProjects\auth\node_modules\react-native-firebase
npm ERR! code ENOENT
npm ERR! errno -4058
npm ERR! syscall rename
npm ERR! enoent ENOENT: no such file or directory, rename 'C:\Users\User\AndroidStudioProjects\auth\node_modules\react-native-firebase' -> 'C:\Users\User\AndroidStudioProjects\auth\node_modules\.react-native-firebase.DELETE'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent
</code>```

And of course when I tried to import the firebase and run my apps, is shows error code 500 with failed to resolve firebase.

答:
Try removing cached .npm directory stored from the previous versions of npm. It is placed at ~/.npm

i.e.

```<code>rm -rf ~/.npm
</code>```

Look at this issue for further help.

Title: react native failed to install firebase

Body:
I am trying to install firebase to my react native project. To do so I have tried several ways based on few sources. I open cmd, move to the project's directory, and tried these:

npm install --save firebase

npm install firebase --save

npm i react-native-firebase --save

But unfortunately, none of this is able to install the firebase to my react native project. For the no 1 and 2, it says:

npm ERR! Cannot read property 'find' of undefined

For no 3 it says:

npm ERR! path C:\Users\User\AndroidStudioProjects\auth\node_modules\react-native-firebase
npm ERR! code ENOENT
npm ERR! errno -4058
npm ERR! syscall rename
npm ERR! enoent ENOENT: no such file or directory, rename 'C:\Users\User\AndroidStudioProjects\auth\node_modules\react-native-firebase' -> 'C:\Users\User\AndroidStudioProjects\auth\node_modules\.react-native-firebase.DELETE'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

And of course when I tried to import the firebase and run my apps, is shows error code 500 with failed to resolve firebase.

Body:
Try removing cached .npm directory stored from the previous versions of npm. It is placed at ~/.npm

i.e.

rm -rf ~/.npm

Look at this issue for further help.


问:
Manual install of pyodbc
This is for a Windows machine.

Can I just copy over the pyodbc in my site-packages library to be able to use it?

pyodbc.cp36-win_amd64.pyd

pyodbc-4.0.16-py3.6.egg-info

Reason is the machine cannot connect to the internet. Thus, I cannot use pip to install directly.

Alternatively, I have a folder pyodbc-4.0.17 locally which has the setup.py. Will I be able to install it manually and how to skip any dependencies, if any, as it will also try to connect to the net if I'm correct.

Please let me know if there is any other way.

答:
Better download pyodbc-4.0.17-cp36-cp36m-win_amd64.whlfrom here, move to the machine and install with pip:

```<code>pip install pyodbc-4.0.17-cp36-cp36m-win_amd64.whl
</code>```

ContentLicense: CC BY-SA 4.0

Title: Manual install of pyodbc

Body:
Better download pyodbc-4.0.17-cp36-cp36m-win_amd64.whlfrom here, move to the machine and install with pip:

pip install pyodbc-4.0.17-cp36-cp36m-win_amd64.whl


问:
Remove duplicates from array, convert to array of objects and add duplicate count property
I have an array of strings:

```<code>var array = ['bob', 'charlie', 'bob', 'bob'];
</code>```

that I want to remove duplicates from, and then I'd like to convert it to an array of objects whilst adding a duplicate count property.

This is what I want to achieve:

```<code>var filteredData = [{ name: 'bob', count: 3}, { name: 'charlie', count: 1}];
</code>```

How can I do that?

答:
Here is some straightforward usage of Array.prototype.reduce:

const data = ['bob', 'charlie', 'bob', 'bob']

const result = data.reduce(function(prev, curr) {
  const index = prev.findIndex(el => el.name === curr)

  if (index !== -1) {
    prev[index].count += 1
  } else {
    prev.push({ name: curr, count: 1 })
  }

  return prev
}, [])

console.log(result)```

Body:
I have an array of strings:

var array = ['bob', 'charlie', 'bob', 'bob'];

that I want to remove duplicates from, and then I'd like to convert it to an array of objects whilst adding a duplicate count property.

This is what I want to achieve:

var filteredData = [{ name: 'bob', count: 3}, { name: 'charlie', count: 1}];

How can I do that?


问:
Consul constantly removes service
I had added a consul agent to the host in client mode and added a service.
And now, it constantly and silently removes the service and registers again

```<code>2017/01/27 08:25:23 [INFO] consul: member 'static' joined, marking health alive
2017/01/27 08:26:23 [INFO] consul: member 'static' joined, marking health alive
2017/01/27 08:28:23 [INFO] consul: member 'static' joined, marking health alive
2017/01/27 08:29:23 [INFO] consul: member 'static' joined, marking health alive
2017/01/27 08:30:23 [INFO] consul: member 'static' joined, marking health alive
2017/01/27 08:31:23 [INFO] consul: member 'static' joined, marking health alive
2017/01/27 08:33:23 [INFO] consul: member 'static' joined, marking health alive
2017/01/27 08:35:23 [INFO] consul: member 'static' joined, marking health alive
2017/01/27 08:37:23 [INFO] consul: member 'static' joined, marking health alive
</code>```

The service config is simple

```<code>{
  "service": {
    "tags": [
      "master"
    ],
    "address": "172.16.50.40",
    "port": 5432,
    "name": "staging-postgres"
  }
}
</code>```

Is it posible to register a service forever and deregister only manually?

答:
Consul services are usually registered to a specific node (member). When that member leaves the cluster, it is assumed that all its services are also unhealthy, therefore they are marked as unhealthy.

It would be helpful to know why "static" continues to join and leave the cluster. If that's a behavior that cannot be prevented, it might be best to register your service as an external service.

```<code>$ curl -X PUT -d '{"Datacenter": "dc1", "Node": "google",
   "Address": "www.google.com",
   "Service": {"Service": "search", "Port": 80}}'
   http://127.0.0.1:8500/v1/catalog/register
</code>```

Title: Consul constantly removes service

Body:
I had added a consul agent to the host in client mode and added a service.
And now, it constantly and silently removes the service and registers again

2017/01/27 08:25:23 [INFO] consul: member 'static' joined, marking health alive
2017/01/27 08:26:23 [INFO] consul: member 'static' joined, marking health alive
2017/01/27 08:28:23 [INFO] consul: member 'static' joined, marking health alive
2017/01/27 08:29:23 [INFO] consul: member 'static' joined, marking health alive
2017/01/27 08:30:23 [INFO] consul: member 'static' joined, marking health alive
2017/01/27 08:31:23 [INFO] consul: member 'static' joined, marking health alive
2017/01/27 08:33:23 [INFO] consul: member 'static' joined, marking health alive
2017/01/27 08:35:23 [INFO] consul: member 'static' joined, marking health alive
2017/01/27 08:37:23 [INFO] consul: member 'static' joined, marking health alive

The service config is simple

{
  "service": {
    "tags": [
      "master"
    ],
    "address": "172.16.50.40",
    "port": 5432,
    "name": "staging-postgres"
  }
}

Is it posible to register a service forever and deregister only manually?

Body:
Consul services are usually registered to a specific node (member). When that member leaves the cluster, it is assumed that all its services are also unhealthy, therefore they are marked as unhealthy.

It would be helpful to know why "static" continues to join and leave the cluster. If that's a behavior that cannot be prevented, it might be best to register your service as an external service.

$ curl -X PUT -d '{"Datacenter": "dc1", "Node": "google",
   "Address": "www.google.com",
   "Service": {"Service": "search", "Port": 80}}'
   http://127.0.0.1:8500/v1/catalog/register


问:
Grabbing specific sections of a txt file via Powershell
I am new to Powershell scripting, but I feel I am overlooking a simple answer, hopefully some of you can help.

My company exports files from all of our computers with a section around the middle of Mapped Network Printers. It looks like this:

```<code>-------------------------------------------------------------------------
Mapped Network Printers:
NetworkAddress\HP425DN    [DEFAULT PRINTER]
-------------------------------------------------------------------------
Local Printers:
</code>```

What I have been asked to do is copy just the Mapped Network Printers to a new text file.

I tried using Select-String with a context parameter, but I have no way of knowing how many network printers there are, so I can't guess.

I also tried using the following code which I found on this site, but it returns nothing:

```<code>$MapPrint  = gc C:\Users\User1\Documents\Config.txt

$from =  ($MapPrint | Select-String -pattern "Mapped Network Printers:" |
Select-Object LineNumber).LineNumber
$to =  ($MapPrint  | Select-String -pattern "-------------------------------
--------------------------------------------" | Select-Object
LineNumber).LineNumber

$i = 0
$array = @()
foreach ($line in $MapPrint)
{
foreach-object { $i++ }
    if (($i -gt $from) -and ($i -lt $to))
    {
    $array += $line
    }
}
$array
</code>```

I basically want to start the search at "Mapped Network Printers" and end it at the next row of "------"

Any help would be greatly appreciated.

答:
```<code>$Doc= "C:\temp\test.txt"
$Doc_end ="C:\temp\testfiltered.txt"
$reader = [System.IO.File]::OpenText($Doc)

$cdata=""
while($null -ne ($line = $reader.ReadLine()))
    {

        if ($line -like ('---*') )     {$Read = 0 }

        if ($Read -eq 1) {$cdata+= $line +  "`r`n"}

        if ($line -like ('Mapped Network Printers:*')) {$Read = 1}

    }

$cdata | Out-File $Doc_end -Force
</code>```

Body:
I am new to Powershell scripting, but I feel I am overlooking a simple answer, hopefully some of you can help.

My company exports files from all of our computers with a section around the middle of Mapped Network Printers. It looks like this:

-------------------------------------------------------------------------
Mapped Network Printers:
NetworkAddress\HP425DN    [DEFAULT PRINTER]
-------------------------------------------------------------------------
Local Printers:

What I have been asked to do is copy just the Mapped Network Printers to a new text file.

I tried using Select-String with a context parameter, but I have no way of knowing how many network printers there are, so I can't guess.

I also tried using the following code which I found on this site, but it returns nothing:

$MapPrint  = gc C:\Users\User1\Documents\Config.txt

$from =  ($MapPrint | Select-String -pattern "Mapped Network Printers:" |
Select-Object LineNumber).LineNumber
$to =  ($MapPrint  | Select-String -pattern "-------------------------------
--------------------------------------------" | Select-Object
LineNumber).LineNumber

$i = 0
$array = @()
foreach ($line in $MapPrint)
{
foreach-object { $i++ }
    if (($i -gt $from) -and ($i -lt $to))
    {
    $array += $line
    }
}
$array

I basically want to start the search at "Mapped Network Printers" and end it at the next row of "------"

Any help would be greatly appreciated.


问:
How can I use bash's select on a newline-separated list?
How can I use bash's select on a newline-separated list?

I'm actually trying to improve the following snippet in a working script:

```<code># for example
nwd=/media/$USER/some-drive

# This makes a newline-separated list. I'm open to options that make a
# list in a different fashion. I usually loop with find -print0 for this
# kind of thing, but I don't know an easy way to omit a particular
# element ($nwd) from a null-separated list.
volumes="$( ls /media/$USER | grep -v "$( basename -- "$nwd" )" )"

# If there's only one option, I don't need the user to choose.
if [ 1 -eq "$( echo "$volumes" | wc -l )" ]; then
  mount_point="/media/$USER/$volumes"
else
  # KNOWN BUG: It is impossible to select devices with spaces in their names.
  echo "Please select the appropriate device:"
  select mount_point in $volumes Quit; do
    case "$mount_point" in
    Quit ) exit $EXIT_USER_HALT;;
    '' ) echo "Invalid option. Try another one." >&2;continue;;
    * ) break;;
    esac
  done
  mount_point="/media/$USER/$mount_point"
fi
</code>```

答:
By setting IFS=$'\n', your list will be split on newlines, for example:

```<code>#!/bin/bash
list=$'one\ntwo\nthree'

IFS=$'\n'
select item in $list; do
    case "$item" in
        one) echo "1";;
        two) echo "2";;
        *) break;;
    esac
done
</code>```

Be sure to either do this in a function with local IFS, or to restore IFS later manually.

If you expect your filenames (in the list) to contain pathname expansion pattern characters *, ?, or [, you should wrap the select statement block above with set -f and set +f which will prevent those patterns to expand to pathnames. It'll also prevent the expansion of extended globs (if you enabled extglob).

Body:
How can I use bash's select on a newline-separated list?

I'm actually trying to improve the following snippet in a working script:

# for example
nwd=/media/$USER/some-drive

# This makes a newline-separated list. I'm open to options that make a
# list in a different fashion. I usually loop with find -print0 for this
# kind of thing, but I don't know an easy way to omit a particular
# element ($nwd) from a null-separated list.
volumes="$( ls /media/$USER | grep -v "$( basename -- "$nwd" )" )"

# If there's only one option, I don't need the user to choose.
if [ 1 -eq "$( echo "$volumes" | wc -l )" ]; then
  mount_point="/media/$USER/$volumes"
else
  # KNOWN BUG: It is impossible to select devices with spaces in their names.
  echo "Please select the appropriate device:"
  select mount_point in $volumes Quit; do
    case "$mount_point" in
    Quit ) exit $EXIT_USER_HALT;;
    '' ) echo "Invalid option. Try another one." >&2;continue;;
    * ) break;;
    esac
  done
  mount_point="/media/$USER/$mount_point"
fi

Body:
By setting IFS=$'\n', your list will be split on newlines, for example:

#!/bin/bash
list=$'one\ntwo\nthree'

IFS=$'\n'
select item in $list; do
    case "$item" in
        one) echo "1";;
        two) echo "2";;
        *) break;;
    esac
done

Be sure to either do this in a function with local IFS, or to restore IFS later manually.

If you expect your filenames (in the list) to contain pathname expansion pattern characters *, ?, or [, you should wrap the select statement block above with set -f and set +f which will prevent those patterns to expand to pathnames. It'll also prevent the expansion of extended globs (if you enabled extglob).


问:
How to change background color of excel cell with python xlwt library?
I use xlwt Python library to write data in excel workbook.

And now I have some problems with adding background color to excel cell.

For example I have next color in RGB(10,20,30), what is the easiest way to do this?
Is there any way to set this color to cell?

I found only this post which similar with my problem.

答: I recommend to use XlsxWriter module, has awesome features too http://xlsxwriter.readthedocs.io/</p>


问:
Excel - rolling average across columns without zeros, no array
I am currently using this formula to calculate a rolling average score across 12 columns for either the last 3 or 6 months.

=SUM(SUMIFS($E$54:P54,$E$54:P54,LARGE(IF($E$54:P54>0,$E$54:P54),{1,2,3})))

This is an array formula and is entered via CTRL + SHIFT + ENTER.

The problem now is that I need to deploy my work book on older machines and those being ancient office computers (we are talking windows XP and Office 2003...), I find that the array is killing the entire workbook. Now, I have already taken steps to speed up the workbook via VBA (disabling events, manual formula calc, etc.), but I need a way to convert the above array formula into a non-array formula which is NOT counting zeros or empty cells as part of the average.

I tried this below but couldnt get it to work with the zeros / empty cells.
=SUM(OFFSET($E68,0,COUNT($E68:$P68)-IF(COUNT($E68:$P68)>3,3,COUNT($E68:$P68)),1,IF(COUNT($E68:$P68)>3,3,COUNT($E68:$P68))))

Picture of the sample data attached below.

答:
Since an Average is a "Sum" divided by a "Count", this can be accomplished using the simplicity of non-Array formulas.This formula avoids the inclusion of both zeros and blank cells:

=IF(SUM(A2:C2)>0,SUM(A2:C2)/(COUNT(A2:C2)-COUNTIF(A2:C2,0)),0).

If the row is filled with only zero values, then it shows the actual numerical average as zero, which is correct.If you want to avoid the display of zero averages in cells, then use this slightly different formula:

=IF(SUM(A3:C3)>0,SUM(A3:C3)/(COUNT(A3:C3)-COUNTIF(A3:C3,0)),"").

Of course, you will need to adjust the cell ranges for the 6 month and YTD  averages; these formulas deal with  3- month ranges.


问:
How to @import using chrome.tabs.insertCSS()?
```<code>chrome.tabs.insertCSS(tabId, { code : '@import url("custom.css");' });
</code>```

OR

```<code>chrome.tabs.insertCSS(tabId, { file : 'importer.css' });
</code>```

importer.css:

```<code>@import url("custom.css");
a { color:red!important; } /* this rule applied successfully though. */
</code>```

Doesn't seem to work as expected.

Why doesn't it work and how to make it work?

Edit:

Maybe I am looking at the wrong source code location, but the source code indicates that it uses the regular style sheet parser to parse the injected CSS. In other words, if the @import directive works in regular CSS documents, it should also work in injected CSS.

https://code.google.com/p/chromium/codesearch#chromium/src/extensions/renderer/script_injection.cc&q=script_injection.cc&sq=package:chromium&type=cs&l=312-320

```<code>void ScriptInjection::InjectCss(blink::WebLocalFrame* frame) {
  std::vector<std::string> css_sources =
      injector_->GetCssSources(run_location_);
  for (std::vector<std::string>::const_iterator iter = css_sources.begin();
       iter != css_sources.end();
       ++iter) {
    frame->document().insertStyleSheet(blink::WebString::fromUTF8(*iter));
  }
}
</code>```

Edit:

Sample code that's not working:

Directory structure:

```<code>ext.root
|-- custom.css
|-- custom.css.js
|-- importer.css
|-- manifest.json
</code>```

manifest.json:

```<code>{
   "background": {
      "scripts": [ "custom.css.js" ],
      "persistent": true
    },
   "manifest_version": 2,
   "name": "custom.css",
   "version": "1.0",
   "web_accessible_resources" : [ "*" ],
   "permissions" : [ "webNavigation", "http://*/", "https://*/" ]
}
</code>```

custom.css.js:

```<code>chrome.webNavigation.onCommitted.addListener(function(details) {

    console.log('inserting css');
    console.log(chrome.runtime.getURL("custom.css"));

    chrome.tabs.insertCSS(details.tabId, { file : 'importer.css' });

    chrome.tabs.insertCSS(details.tabId,  { code : '@import url("custom.css");' });
    chrome.tabs.insertCSS(details.tabId,  { code : '@import url(custom.css);' });

    chrome.tabs.insertCSS(details.tabId,  { code : '@import url("' + chrome.runtime.getURL("custom.css") + '");' });
    chrome.tabs.insertCSS(details.tabId,  { code : '@import url(' + chrome.runtime.getURL("custom.css") + ');' });

    chrome.tabs.insertCSS(details.tabId,  { code : '@import "custom.css";' });
    chrome.tabs.insertCSS(details.tabId,  { code : '@import custom.css;' });

    chrome.tabs.insertCSS(details.tabId,  { code : '@import "' + chrome.runtime.getURL("custom.css") + '";' });
    chrome.tabs.insertCSS(details.tabId,  { code : '@import ' + chrome.runtime.getURL("custom.css") + ';' });
});
</code>```

importer.css:

```<code>@import "custom.css";
@import "chrome-extension://__MSG_@@extension_id__/custom.css";

@import custom.css;
@import chrome-extension://__MSG_@@extension_id__/custom.css;

@import url("custom.css");
@import url("chrome-extension://__MSG_@@extension_id__/custom.css");

@import url(custom.css);
@import url(chrome-extension://__MSG_@@extension_id__/custom.css);

body { background-color: red!important; } /* change page background color to red */
</code>```

custom.css (Rules in this file are supposed to be applied but not):

```<code>body { border: 20px solid red!important; } /* add a 20px border around the body. */
a { background-color: blue!important; } /* change all link's background color to blue. */
</code>```

答: @important doesn't work with tabs.insertCSS(). insertCSS seem to be interpreted before injection in the page. How they are interpreted is not documented. For example !important do not works neither.</p>

Body:
chrome.tabs.insertCSS(tabId, { code : '@import url("custom.css");' });

OR

chrome.tabs.insertCSS(tabId, { file : 'importer.css' });

importer.css:

@import url("custom.css");
a { color:red!important; } /* this rule applied successfully though. */

Doesn't seem to work as expected.

Why doesn't it work and how to make it work?

Edit:

Maybe I am looking at the wrong source code location, but the source code indicates that it uses the regular style sheet parser to parse the injected CSS. In other words, if the @import directive works in regular CSS documents, it should also work in injected CSS.

https://code.google.com/p/chromium/codesearch#chromium/src/extensions/renderer/script_injection.cc&q=script_injection.cc&sq=package:chromium&type=cs&l=312-320

void ScriptInjection::InjectCss(blink::WebLocalFrame* frame) {
  std::vector<std::string> css_sources =
      injector_->GetCssSources(run_location_);
  for (std::vector<std::string>::const_iterator iter = css_sources.begin();
       iter != css_sources.end();
       ++iter) {
    frame->document().insertStyleSheet(blink::WebString::fromUTF8(*iter));
  }
}

Edit:

Sample code that's not working:

Directory structure:

ext.root
|-- custom.css
|-- custom.css.js
|-- importer.css
|-- manifest.json

manifest.json:

{
   "background": {
      "scripts": [ "custom.css.js" ],
      "persistent": true
    },
   "manifest_version": 2,
   "name": "custom.css",
   "version": "1.0",
   "web_accessible_resources" : [ "*" ],
   "permissions" : [ "webNavigation", "http://*/", "https://*/" ]
}

custom.css.js:

chrome.webNavigation.onCommitted.addListener(function(details) {

    console.log('inserting css');
    console.log(chrome.runtime.getURL("custom.css"));

    chrome.tabs.insertCSS(details.tabId, { file : 'importer.css' });

    chrome.tabs.insertCSS(details.tabId,  { code : '@import url("custom.css");' });
    chrome.tabs.insertCSS(details.tabId,  { code : '@import url(custom.css);' });

    chrome.tabs.insertCSS(details.tabId,  { code : '@import url("' + chrome.runtime.getURL("custom.css") + '");' });
    chrome.tabs.insertCSS(details.tabId,  { code : '@import url(' + chrome.runtime.getURL("custom.css") + ');' });

    chrome.tabs.insertCSS(details.tabId,  { code : '@import "custom.css";' });
    chrome.tabs.insertCSS(details.tabId,  { code : '@import custom.css;' });

    chrome.tabs.insertCSS(details.tabId,  { code : '@import "' + chrome.runtime.getURL("custom.css") + '";' });
    chrome.tabs.insertCSS(details.tabId,  { code : '@import ' + chrome.runtime.getURL("custom.css") + ';' });
});

importer.css:

@import "custom.css";
@import "chrome-extension://__MSG_@@extension_id__/custom.css";

@import custom.css;
@import chrome-extension://__MSG_@@extension_id__/custom.css;

@import url("custom.css");
@import url("chrome-extension://__MSG_@@extension_id__/custom.css");

@import url(custom.css);
@import url(chrome-extension://__MSG_@@extension_id__/custom.css);

body { background-color: red!important; } /* change page background color to red */

custom.css (Rules in this file are supposed to be applied but not):

body { border: 20px solid red!important; } /* add a 20px border around the body. */
a { background-color: blue!important; } /* change all link's background color to blue. */


问:
Set focus on an input with Ionic 2

SOLVED :

```<code>import { Component, ViewChild} from '@angular/core';
import { Keyboard } from 'ionic-native';

@Component({
  templateUrl: 'build/pages/home/home.html'
})
export class HomePage {
  @ViewChild('input') myInput ;

  constructor() {}

  ionViewDidLoad() {

    setTimeout(() => {
      Keyboard.show() // for android
      this.myInput.setFocus();
    },150);

 }

}
</code>```

1) import "ViewChild"

import {Component, ViewChild} from '@angular/core';

2) Create a reference to your input in your html template :

```<code><ion-input #focusInput></ion-input>
</code>```

3) Use @ViewChild to get access to the input component you just referenced previously.

@ViewChild('focusInput') myInput ;

4) Trigger the focus

Use the ionViewLoaded() method to trigger it each time the view/page is loaded.

setTimeout is needed

```<code>  ionViewLoaded() {

    setTimeout(() => {
      Keyboard.show() // for android
      this.myInput.setFocus();
    },150); //a least 150ms.

 }
</code>```

4) Show the keyboard on Android

import { Keyboard } from 'ionic-native';

Call Keyboard.show() to call the keyboard on Android.

5) Show the keyboard on iOS

add this line to your config.xml to make it work on iOS :

<preference name="KeyboardDisplayRequiresUserAction" value="false" />

With the help from the great article of mhartington : http://mhartington.io/post/setting-input-focus/

答:
```<code>import {Component,ViewChild} from '@angular/core';
import {NavController} from 'ionic-angular';

@Component({
  templateUrl: 'build/pages/home/home.html'
})
export class HomePage {
  @ViewChild('myInput') myInput ;

  constructor(private navCtrl: NavController) { }

  ionViewDidLoad() {

    window.setTimeout(() => {
      this.myInput.setFocus();
    }, 600); //SET A LONG TIME IF YOU ARE IN A MODAL/ALERT

  }

}
</code>```

<ion-input #myInput ></ion-input>
```

Title: Set focus on an input with Ionic 2

Body:
SOLVED :

import { Component, ViewChild} from '@angular/core';
import { Keyboard } from 'ionic-native';

@Component({
  templateUrl: 'build/pages/home/home.html'
})
export class HomePage {
  @ViewChild('input') myInput ;

  constructor() {}

  ionViewDidLoad() {

    setTimeout(() => {
      Keyboard.show() // for android
      this.myInput.setFocus();
    },150);

 }

}

1) import "ViewChild"

import {Component, ViewChild} from '@angular/core';

2) Create a reference to your input in your html template :

<ion-input #focusInput></ion-input>

3) Use @ViewChild to get access to the input component you just referenced previously.

@ViewChild('focusInput') myInput ;

4) Trigger the focus

Use the ionViewLoaded() method to trigger it each time the view/page is loaded.

setTimeout is needed

  ionViewLoaded() {

    setTimeout(() => {
      Keyboard.show() // for android
      this.myInput.setFocus();
    },150); //a least 150ms.

 }

4) Show the keyboard on Android

import { Keyboard } from 'ionic-native';

Call Keyboard.show() to call the keyboard on Android.

5) Show the keyboard on iOS

add this line to your config.xml to make it work on iOS :

<preference name="KeyboardDisplayRequiresUserAction" value="false" />

With the help from the great article of mhartington : http://mhartington.io/post/setting-input-focus/

Body:
import {Component,ViewChild} from '@angular/core';
import {NavController} from 'ionic-angular';

@Component({
  templateUrl: 'build/pages/home/home.html'
})
export class HomePage {
  @ViewChild('myInput') myInput ;

  constructor(private navCtrl: NavController) { }

  ionViewDidLoad() {

    window.setTimeout(() => {
      this.myInput.setFocus();
    }, 600); //SET A LONG TIME IF YOU ARE IN A MODAL/ALERT

  }

}

<ion-input #myInput ></ion-input>


答:
Assuming that DeviceName is unique, you can extract the array values and index them by DeviceName:

```<code>$result = array_column($values, null, 'DeviceName');
echo $result['Device2']['state'];
</code>```

Title: PHP Arrays. Get value from array with arrays

Body:
I have array in PHP:

Array
(
  [1] => Array
    (
        [DeviceName] => Device1
        [DeviceId] => 0x0000001530A1B380
        [state] => 0
        ...
         )
  [2] => Array
    (
        [DeviceName] => Device2
        [DeviceId] => 0x0000001530A10C80
        [state] => 1
        ...
    )
  [3] => Array
    (
        [DeviceName] => Device3
        [DeviceId] => 0x0000001531471600
        [state] => 0
        ...
    )
  ...
)

How I can get values of state and DeviceId keys only from the array where DeviceName = Device2?

I have tried this, but it returns deviceID from another array:

foreach ($values as $B) {
    $B = preg_replace('~[\r\n]+~', '', $B);
    if ($B['DeviceName'] == $Device) {
        print "Device ID: ".$B['DeviceId']."\n";
    }
}

Body:
Assuming that DeviceName is unique, you can extract the array values and index them by DeviceName:

$result = array_column($values, null, 'DeviceName');
echo $result['Device2']['state'];


问:
what some ways to mask a mysqldump?
anybody knows efficiency in masking(anonymization) of some tables in a mysqldump? I have already finished my parser but unfortunately it doesn't work that good on big dumps (let say a dump of 1GB++) because it really increases the dump time due to the parsing.

what I did was parse the table columns first (which shouldn't take long) and parse the whole insert string for a specific table.

I am using ruby and would like to use it if possible.

I also looked into the idea of exporting the dump, dumping it, updating (masking) it through internal ruby code then exporting the dump again. Although I haven't tried how long this is going to take.

The current workflow for this would be:
get dump from a server, uncompress, then dump into mysql

the new one would be
get dump from a server, uncompress, masked confidential data and dump into mysql

the current workflow would take at most 2 hours for a 1-2GB++ dump but unfortunately i already spent 4hrs on the new one but it is still not finished on the parsing/masking part.

I was also advised to improvise the code by taking out variables and things that consumes more memory since the ruby gc is said to be not on a 1:1 ratio. I believe this is optimized on REE(ruby enterprise edition) but I am currently using REE also now.

Has anybody done this and maybe share their thoughts? Thanks.

答: You can specify tables that you don't want to dump: http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_ignore-table</p>

Title: what some ways to mask a mysqldump?


答:
Since you're assigning $B, you should pass it by reference:

```<code> foreach($values as &$B)
</code>```

Body:
Since you're assigning $B, you should pass it by reference:

 foreach($values as &$B)


问:
Can't retrieve Id from the database
I can't retrieve the ID from my database when I try to access it :

This is my database:

This is my event controller class:

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Event3;
class EventsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = Event3::get(['title','start','end','color']);

       return Response()->json($data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
       $event = new Event3();
        $event->id = $request->id;
       $event->title = $request->title;
       $event->start = $request->date_start .' '. $request->time_start;
        $event->end = $request->date_end;
       $event->color = $request->color;
        $event->save();

        return redirect('/');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
</code>```

I have tried adding the following:

$event->id= $request->id; into the above class but that didn't help .

Event3

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class Event3 extends Model
{
    /**
     * @var string
     * [$table description]
     * @var string
     */

    protected $table = 'event3s';

    public $timestamps = false;

    /**
     * @var string
     * [$table description]
     * @var string
     */
    protected $filltable =[
        'title','start','end','color'

    ];
}
</code>```

答:
You have to modify your index@EventsController

```<code>public function index()
{
    $data = Event3::get(['id', 'title','start','end','color']);

   return Response()->json($data);
}
</code>```

or simply call

```<code>Event3::all();
</code>```

Note that the store() method in your controller is for creating a new element, the id will be filled automatically.

Title: Can't retrieve Id from the database

Body:
I can't retrieve the ID from my database when I try to access it :

This is my database:

This is my event controller class:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Event3;
class EventsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = Event3::get(['title','start','end','color']);

       return Response()->json($data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
       $event = new Event3();
        $event->id = $request->id;
       $event->title = $request->title;
       $event->start = $request->date_start .' '. $request->time_start;
        $event->end = $request->date_end;
       $event->color = $request->color;
        $event->save();

        return redirect('/');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

I have tried adding the following:

$event->id= $request->id; into the above class but that didn't help .

Event3

namespace App;

use Illuminate\Database\Eloquent\Model;

class Event3 extends Model
{
    /**
     * @var string
     * [$table description]
     * @var string
     */

    protected $table = 'event3s';

    public $timestamps = false;

    /**
     * @var string
     * [$table description]
     * @var string
     */
    protected $filltable =[
        'title','start','end','color'

    ];
}

Body:
You have to modify your index@EventsController

public function index()
{
    $data = Event3::get(['id', 'title','start','end','color']);

   return Response()->json($data);
}

or simply call

Event3::all();

Note that the store() method in your controller is for creating a new element, the id will be filled automatically.


问:
get 8 digit after comma in python
I wouldlike to get 8 digit after comma but I tried everything, no one solution actually resolve my problem:

```<code>tab_freq=(result[1]/1e6)
value_freq=str(tab_freq)[1:-1]
print value_freq
</code>```

I tried this :

```<code> value_freq2=format(value_freq,".8f")
</code>```

and I get always the same error :

```<code>Unknown format code 'f' for object of type 'str'
</code>```

Thanks for your help !

答:
".8f" will work on numbers, not strings.

Try converting it to a float first:

```<code>value_freq2=format(float(value_freq),".8f")
</code>```

Edit:

In response to your comments below, you first need to split all the values in value_freq2 and apply the format to each one, then rejoin them.

```<code>value_freq = "100. 100.98 105.344444 104."
value_list = [format(float(v), ".8f") for v in value_freq.split()]
value_freq2 = "\n".join(value_list)
</code>```

Title: get 8 digit after comma in python

Body:
I wouldlike to get 8 digit after comma but I tried everything, no one solution actually resolve my problem:

tab_freq=(result[1]/1e6)
value_freq=str(tab_freq)[1:-1]
print value_freq

I tried this :

 value_freq2=format(value_freq,".8f")

and I get always the same error :

Unknown format code 'f' for object of type 'str'

Thanks for your help !

Body:
".8f" will work on numbers, not strings.

Try converting it to a float first:

value_freq2=format(float(value_freq),".8f")

Edit:

In response to your comments below, you first need to split all the values in value_freq2 and apply the format to each one, then rejoin them.

value_freq = "100. 100.98 105.344444 104."
value_list = [format(float(v), ".8f") for v in value_freq.split()]
value_freq2 = "\n".join(value_list)


问:
SQL custom unit conversion
I am looking for a solution for a custom unit conversion in SQL, the database my company used is Microsoft SQL server, I need to write a SQL to return a conversion factor based on a "unit conversion table"

say:

```<code>Item: chicken wings (itemid 1001)
vendor: food wholesale ltd (vendorid 5000)
unitid: gram (id=10)
unitid: kilogram (id=500)
unitid: boxes (id=305)
Quantity: 1000 grams = 1kgs = 5 boxs
</code>```

Unit conversion table:

```<code>itemid | vendorid | unit1id | unit2id | quantity1 | quantity2

1001 5000 10 500 1000 1

1001 5000 500 305 1 5
</code>```

Question:
What is the closing stock for chicken wings in gram if I have 10 boxes

How to write this sql to return the "conversion factor"?

Thanks in advance

答:
Now that's a tricky one.  It looks like you are going to need a recursive-select, or a cursor to solve it.  Basically, what you want to do is select from the unit conversion table where itemid = @desiredId and vendorid = @desiredVendor and unit2id = @finalUnitId.  Then, you will want to run the same query, but where unit2id = unit1id from the query you just ran -- until unit1id = @originalUnitId.  All the while, keeping a running conversion-factor.

So, begin with something like this:

declare @factor float

set @factor = 0

select unit1id, quantity1, quantity2 from unitconversion where itemid = 1001 and vendorid = 5000 and unit2id = 305

set @factor = @factor + quantity1 / quantity 2

Then, you will want to check to see if unit1id selected from the above equals the unit you want to end up with (in you example, you are checking to see if unit1id = 10).  If not, run the same query again, but restrict for a unit2id of 10.

This is just a rough outline of how I would do it.  There are a few assumptions made here, mainly that if you follow the chain of units that the previous unit is always smaller than the unit you are testing for, but I think this may be enough to convey the gist of it.  This will probably work out best implemented as a UDF that returns the factor based on the product, vendor, start, and end units.  I would use a while statement.

Title: SQL custom unit conversion

Body:
I am looking for a solution for a custom unit conversion in SQL, the database my company used is Microsoft SQL server, I need to write a SQL to return a conversion factor based on a "unit conversion table"

say:

Item: chicken wings (itemid 1001)
vendor: food wholesale ltd (vendorid 5000)
unitid: gram (id=10)
unitid: kilogram (id=500)
unitid: boxes (id=305)
Quantity: 1000 grams = 1kgs = 5 boxs

Unit conversion table:

itemid | vendorid | unit1id | unit2id | quantity1 | quantity2

1001 5000 10 500 1000 1

1001 5000 500 305 1 5

Question:
What is the closing stock for chicken wings in gram if I have 10 boxes

How to write this sql to return the "conversion factor"?

Thanks in advance


问:
Is it possible to create an attribute that will break the build under a condition?
It seemed like this was possible, but I can't find a reference on how to accomplish it, though I've seen a few things that are closely related. I have a particular type of class that requires a public or private default ctor. The reason is stylistic; it is a domain aggregate and the only case where a default ctor should be used is during event store replay. There are obvious ways to work around this, but I'm trying to lock this particular type down. At any rate, what I'm hoping to do is create an attribute that can be applied at the class level that would enforce the existence of a default ctor. If one isn't found, it won't compile... or at the very least, give it the big nasty blue underline like [Obsolete()] does. I figured this was potentially doable with Roslyn. Any direction would help. The solution would ideally travel with the project rather than being something that needs to be installed on visual studio.</p>

答:
Just a simple idea, for a public default constructor you could make use of the where T : new() constraint - even though attributes cannot be generic you can supply typeof(HasDefaultConstructor<MyClass>) as an argument to an attribute:

```<code>public static class HasDefaultConstructor<T> where T : new() { }

public class CheckAttribute : Attribute
{
    public CheckAttribute(Type type) { }
}

[Check(typeof(HasDefaultConstructor<MyClass>))]
public class MyClass
{
    public MyClass() { }
}
</code>```

But it feels a bit hacky having to supply the type you're applying the attribute to, and doesn't work for the non-public constructors, but it does fail at compile-time without needing any addons.

Body:
Just a simple idea, for a public default constructor you could make use of the where T : new() constraint - even though attributes cannot be generic you can supply typeof(HasDefaultConstructor<MyClass>) as an argument to an attribute:

public static class HasDefaultConstructor<T> where T : new() { }

public class CheckAttribute : Attribute
{
    public CheckAttribute(Type type) { }
}

[Check(typeof(HasDefaultConstructor<MyClass>))]
public class MyClass
{
    public MyClass() { }
}

But it feels a bit hacky having to supply the type you're applying the attribute to, and doesn't work for the non-public constructors, but it does fail at compile-time without needing any addons.


问:
Prometheus Alertmanager HA config in config file
In the documentation I see you can provide flags to specify the high availability information: https://github.com/prometheus/alertmanager#high-availability

How do I specify these things in the config file instead of as CLI params?

答:
These can only be specified on the command line.

In general in Prometheus, a setting is either in the config or on the command line - never both.


问:
PHP Arrays. Get value from array with arrays
I have array in PHP:

```<code>Array
(
  [1] => Array
    (
        [DeviceName] => Device1
        [DeviceId] => 0x0000001530A1B380
        [state] => 0
        ...
         )
  [2] => Array
    (
        [DeviceName] => Device2
        [DeviceId] => 0x0000001530A10C80
        [state] => 1
        ...
    )
  [3] => Array
    (
        [DeviceName] => Device3
        [DeviceId] => 0x0000001531471600
        [state] => 0
        ...
    )
  ...
)
</code>```

How I can get values of state and DeviceId keys only from the array where DeviceName = Device2?

I have tried this, but it returns deviceID from another array:

```<code>foreach ($values as $B) {
    $B = preg_replace('~[\r\n]+~', '', $B);
    if ($B['DeviceName'] == $Device) {
        print "Device ID: ".$B['DeviceId']."\n";
    }
}
</code>```

答:
```<code>function findDeviceAndState($arr,$deviceName){
    foreach($arr as $sample){
        if($sample['DeviceName']==$deviceName){
            return array($sample['DeviceName'],$sample['state']);
         }
    }
    return null;
}
</code>```

in your code call function and assume your array name is $values and assume you have just one device with name Device2

```<code>if(($result=findDeviceAndState($values,'Device2'))!=null){
 echo 'DeviceName: '.$result[0];
 echo 'State : '.$result[1];
}else{
 die("Device not found!");
}
</code>```

Body:
function findDeviceAndState($arr,$deviceName){
    foreach($arr as $sample){
        if($sample['DeviceName']==$deviceName){
            return array($sample['DeviceName'],$sample['state']);
         }
    }
    return null;
}

in your code call function and assume your array name is $values and assume you have just one device with name Device2

if(($result=findDeviceAndState($values,'Device2'))!=null){
 echo 'DeviceName: '.$result[0];
 echo 'State : '.$result[1];
}else{
 die("Device not found!");
}


问:
How to check if two instances of the same java program are running?
Hi am making a program which will run through javaw.exe, so that it is not visible directly. Now my issue is sometime, (accidently) it can happen that the user runs multiple instances of the same application,

e.g entering javaw myProgram two times

Under such situation, is there any way i can prevent multiple instances of the same program to run if the program is already running.

答:
Although file lock is probably the simplest and easiest option, I'd like to mention one alternative: JIntellitype is a library which works only on Windows and has the utility method to check if the application window with the given title is already running.

If it just so happens that you're OK with having this functionality only on Windows and using file lock doesn't work for you... :)


问:
Chain/transform method calls with ByteBuddy
Using ByteBuddy, can I implement one instance method by calling another and transforming the result?

For instance (toy example):

```<code>public abstract class Foo {
  public String bar() {
    return "bar";
  }

  public abstract int baz();
}
</code>```

Given the above, can I implement baz such that it calls bar() and returns the length of the returned string? I.e., as if it were:

```<code>public int baz() {
  return bar().length();
}
</code>```

Naively, I tried the following:

```<code>Method bar = Foo.class.getDeclaredMethod("bar");
Method baz = Foo.class.getDeclaredMethod("baz");

Method length = String.class.getDeclaredMethod("length");

Foo foo = new ByteBuddy()
  .subclass(Foo.class)
  .method(ElementMatchers.is(baz))
  .intercept(
    MethodCall.invoke(bar)                 // call bar()...
      .andThen(MethodCall.invoke(length))  // ... .length()?
  ).make()
  .load(Foo.class.getClassLoader())
  .getLoaded()
  .newInstance();

System.out.println(foo.baz());
</code>```

However, it looks like I was wrong in thinking andThen() is invoked on the return value of the first invocation; it looks like it's invoked on the generated instance.

```<code>Exception in thread "main" java.lang.IllegalStateException:
  Cannot invoke public int java.lang.String.length() on class Foo$ByteBuddy$sVgjXXp9
    at net.bytebuddy.implementation.MethodCall$MethodInvoker$ForContextualInvocation
    .invoke(MethodCall.java:1667)
</code>```

I also tried an interceptor:

```<code>class BazInterceptor {
  public static int barLength(@This Foo foo) {
    String bar = foo.bar();
    return bar.length();
  }
}
</code>```

with:

```<code>Foo foo = new ByteBuddy()
  .subclass(Foo.class)
  .method(ElementMatchers.is(baz))
  .intercept(MethodDelegation.to(new BazInterceptor()))
  // ...etc.
</code>```

This ran, but produced the nonsensical result 870698190, and setting breakpoints and/or adding print statements in barLength() suggested it's never getting called; so clearly I'm not understanding interceptors or @This properly, either.

How can I get ByteBuddy to invoke one method and then invoke another on its return value?

Per k5_'s answer: BazInterceptor works if either:

we delegate to new BazInterceptor(), as above, but make barLength() an instance method, or:

we leave barLength() a class method, but delegate to BazInterceptor.class instead of to an instance.

I suspect the 870698190 was delegating to hashCode() of the BazInterceptor instance, though I didn't actually check.

答:
You use an instance as interceptor, that means instance methods are prefered (maybe static method are not accepted at all). There is an instance method that matches the signature of your int baz() method, it is int hashCode(). The number you are getting is the hashcode of the new BazInterceptor() instance.

Options i am aware of:

Remove static from barLength that way it will actually be used for interception.

Add the class as interceptor .intercept(MethodDelegation.to(BazInterceptor.class))

I would prefer the second option as you are not using any fields/state of the BazInterceptor instance.

Body:
Using ByteBuddy, can I implement one instance method by calling another and transforming the result?

For instance (toy example):

public abstract class Foo {
  public String bar() {
    return "bar";
  }

  public abstract int baz();
}

Given the above, can I implement baz such that it calls bar() and returns the length of the returned string? I.e., as if it were:

public int baz() {
  return bar().length();
}

Naively, I tried the following:

Method bar = Foo.class.getDeclaredMethod("bar");
Method baz = Foo.class.getDeclaredMethod("baz");

Method length = String.class.getDeclaredMethod("length");

Foo foo = new ByteBuddy()
  .subclass(Foo.class)
  .method(ElementMatchers.is(baz))
  .intercept(
    MethodCall.invoke(bar)                 // call bar()...
      .andThen(MethodCall.invoke(length))  // ... .length()?
  ).make()
  .load(Foo.class.getClassLoader())
  .getLoaded()
  .newInstance();

System.out.println(foo.baz());

However, it looks like I was wrong in thinking andThen() is invoked on the return value of the first invocation; it looks like it's invoked on the generated instance.

Exception in thread "main" java.lang.IllegalStateException:
  Cannot invoke public int java.lang.String.length() on class Foo$ByteBuddy$sVgjXXp9
    at net.bytebuddy.implementation.MethodCall$MethodInvoker$ForContextualInvocation
    .invoke(MethodCall.java:1667)

I also tried an interceptor:

class BazInterceptor {
  public static int barLength(@This Foo foo) {
    String bar = foo.bar();
    return bar.length();
  }
}

with:

Foo foo = new ByteBuddy()
  .subclass(Foo.class)
  .method(ElementMatchers.is(baz))
  .intercept(MethodDelegation.to(new BazInterceptor()))
  // ...etc.

This ran, but produced the nonsensical result 870698190, and setting breakpoints and/or adding print statements in barLength() suggested it's never getting called; so clearly I'm not understanding interceptors or @This properly, either.

How can I get ByteBuddy to invoke one method and then invoke another on its return value?

Per k5_'s answer: BazInterceptor works if either:

we delegate to new BazInterceptor(), as above, but make barLength() an instance method, or:

we leave barLength() a class method, but delegate to BazInterceptor.class instead of to an instance.

I suspect the 870698190 was delegating to hashCode() of the BazInterceptor instance, though I didn't actually check.


问:
pyspark - iterating through the file and substituting the value in dataframe
I need to read through the file and substitute the value while the s3 path.I am able to loop through the file but I am not able to substitute the value.

```<code>File ending with \n
/MTD_avg_cust_bal1
/MTDSumOfCustomerInitiatedTrxns1
/MTDCountOfCustomerInitiatedTrxns1
</code>```

Code:

```<code>metrics = open("Output.txt","r")
line = metrics.readline()

while line:
    print line
    line = metrics.readline()
    s3path = ("SELECT * FROM parquet.`s3n://bucket{}/loaddate=20170406/part-r-00000-d60b633d-ff49-4515-8cff-ace9faf1b267.csv`") .format(line).strip('\n')

    print s3path
    df1 = sqlContext.sql(s3path)
</code>```

Error:

```<code>pyspark.sql.utils.AnalysisException: u'Path does not exist: s3n://omniscience1/MTDSumOfCustomerInitiatedTrxns1\n/loaddate=20170406/part-r-00000-d60b633d-ff49-4515-8cff-ace9faf1b267.csv;; line 1 pos 14'
</code>```

The problem is it's including \n when the value is substituted and also I need to have separate data frame for each line.

答:
It would help if you can let us know how your output should look like.

I'm not a python expert. But below is what I've come up with based on my understanding. Let me know if this is what you are looking for.

```<code>with open("Output.txt", 'r') as file:

    for line in file:
        line = line.strip('\n')
        s3path = ("SELECT * FROM parquet.`s3n://bucket{}/loaddate=20170406/part-r-00000-d60b633d-ff49-4515-8cff-ace9faf1b267.csv`") .format(line)

        print (s3path)
</code>```

The output of the above script is below.

```<code>SELECT * FROM parquet.`s3n://bucket/MTD_avg_cust_bal1/loaddate=20170406/part-r-00000-d60b633d-ff49-4515-8cff-ace9faf1b267.csv`
SELECT * FROM parquet.`s3n://bucket/MTDSumOfCustomerInitiatedTrxns1/loaddate=20170406/part-r-00000-d60b633d-ff49-4515-8cff-ace9faf1b267.csv`
SELECT * FROM parquet.`s3n://bucket/MTDCountOfCustomerInitiatedTrxns1/loaddate=20170406/part-r-00000-d60b633d-ff49-4515-8cff-ace9faf1b267.csv`
</code>```

Body:
I need to read through the file and substitute the value while the s3 path.I am able to loop through the file but I am not able to substitute the value.

File ending with \n
/MTD_avg_cust_bal1
/MTDSumOfCustomerInitiatedTrxns1
/MTDCountOfCustomerInitiatedTrxns1

Code:

metrics = open("Output.txt","r")
line = metrics.readline()

while line:
    print line
    line = metrics.readline()
    s3path = ("SELECT * FROM parquet.`s3n://bucket{}/loaddate=20170406/part-r-00000-d60b633d-ff49-4515-8cff-ace9faf1b267.csv`") .format(line).strip('\n')

    print s3path
    df1 = sqlContext.sql(s3path)

Error:

pyspark.sql.utils.AnalysisException: u'Path does not exist: s3n://omniscience1/MTDSumOfCustomerInitiatedTrxns1\n/loaddate=20170406/part-r-00000-d60b633d-ff49-4515-8cff-ace9faf1b267.csv;; line 1 pos 14'

The problem is it's including \n when the value is substituted and also I need to have separate data frame for each line.

Body:
It would help if you can let us know how your output should look like.

I'm not a python expert. But below is what I've come up with based on my understanding. Let me know if this is what you are looking for.

with open("Output.txt", 'r') as file:

    for line in file:
        line = line.strip('\n')
        s3path = ("SELECT * FROM parquet.`s3n://bucket{}/loaddate=20170406/part-r-00000-d60b633d-ff49-4515-8cff-ace9faf1b267.csv`") .format(line)

        print (s3path)

The output of the above script is below.

SELECT * FROM parquet.`s3n://bucket/MTD_avg_cust_bal1/loaddate=20170406/part-r-00000-d60b633d-ff49-4515-8cff-ace9faf1b267.csv`
SELECT * FROM parquet.`s3n://bucket/MTDSumOfCustomerInitiatedTrxns1/loaddate=20170406/part-r-00000-d60b633d-ff49-4515-8cff-ace9faf1b267.csv`
SELECT * FROM parquet.`s3n://bucket/MTDCountOfCustomerInitiatedTrxns1/loaddate=20170406/part-r-00000-d60b633d-ff49-4515-8cff-ace9faf1b267.csv`


问:
How do I fix slow, clunky CSS transitions?
I apologize if this has already been asked. I'm having a hard time finding an answer on my own. My CSS transitions are not very smooth. I've noticed this is becoming a pattern for me. I'm trying to figure out how to fix that. Is it faster to add/remove a class? Is it the high res images I'm using? Would JQuery be faster? Here's the codepen

https://codepen.io/tyl-er/pen/OgZmQg?editors=0010

```<code>let sidePanelOpen = false;

let urls = [
    'https://images.unsplash.com/photo-1498898733745-c8c6df58e4ba',
    'https://images.unsplash.com/photo-1499006619764-59e5b0c0e7ca',
    'https://images.unsplash.com/photo-1498503603722-8de8df0beb96'
];

function openNav() {
    document.getElementById("accordion").style.width = "60vw";
    document.getElementById("splash").style.width = "40vw";
    document.getElementById("splash").style.marginRight = "60vw";
    document.getElementById("splash").style.opacity = ".5";
}

function closeNav() {
    document.getElementById("accordion").style.width = "0";
    document.getElementById("splash").style.width = "100vw";
    document.getElementById("splash").style.marginRight = "0";
    document.getElementById("splash").style.opacity = "1";
    let item = urls[Math.floor(Math.random()*urls.length)];
    document.getElementById("splash").style.backgroundImage = "url(" + item + ")";
}

document.querySelector("#nav-toggle").addEventListener("click", function() {
    this.classList.toggle("active");
    sidePanelOpen = !sidePanelOpen;
    sidePanelOpen ? openNav() : closeNav();
});
</code>```

答:
Check out this article: Smooth as Butter: Achieving 60 FPS Animations with CSS3

In short, changing elements so that the browser has to re-calculate it's document flow is most likely causing your performance issues.

Body:
I apologize if this has already been asked. I'm having a hard time finding an answer on my own. My CSS transitions are not very smooth. I've noticed this is becoming a pattern for me. I'm trying to figure out how to fix that. Is it faster to add/remove a class? Is it the high res images I'm using? Would JQuery be faster? Here's the codepen

https://codepen.io/tyl-er/pen/OgZmQg?editors=0010

let sidePanelOpen = false;

let urls = [
    'https://images.unsplash.com/photo-1498898733745-c8c6df58e4ba',
    'https://images.unsplash.com/photo-1499006619764-59e5b0c0e7ca',
    'https://images.unsplash.com/photo-1498503603722-8de8df0beb96'
];

function openNav() {
    document.getElementById("accordion").style.width = "60vw";
    document.getElementById("splash").style.width = "40vw";
    document.getElementById("splash").style.marginRight = "60vw";
    document.getElementById("splash").style.opacity = ".5";
}

function closeNav() {
    document.getElementById("accordion").style.width = "0";
    document.getElementById("splash").style.width = "100vw";
    document.getElementById("splash").style.marginRight = "0";
    document.getElementById("splash").style.opacity = "1";
    let item = urls[Math.floor(Math.random()*urls.length)];
    document.getElementById("splash").style.backgroundImage = "url(" + item + ")";
}

document.querySelector("#nav-toggle").addEventListener("click", function() {
    this.classList.toggle("active");
    sidePanelOpen = !sidePanelOpen;
    sidePanelOpen ? openNav() : closeNav();
});


问:
Stripping HTML but retaining block/inline structure
I would like to convert HTML to plain text but retain the minimum structure.

All sections which contain stuff only the browser needs to see such as

答:
The list of HTML 4 Block-level elements is here: http://htmlhelp.com/reference/html40/block.html

The most popular HTML parsing libraries for Perl are HTML::Parser which is a SAX-style parser and HTML::TreeBuilder which is more DOM-like.

Beyond that, you'll have to decide which elements are important and which are not based on what you're trying do to.