问:
Python: split a dict in a list
I want to convert a simple dict like so: d = {0:0, 1:1, 2:2, 3:3} to a list of dict with the same amount of elements in each of them (or so) as this one: [{0:0, 2:2}, {1:1, 3:3}]. I've tried with simple indexing like I use with lists but it throws me a TypeError: unhashable type: 'slice'. Here what i have right now:

```<code>def dico_chunks(dico, n):
    if len(dico) < n:
        n = len(dico)
    return [dico[i::n] for i in range(n)]
</code>```

Keep in mind that i don't need the list to be order in anyway. I just need to have my main dict splited in a list of n sub-dicts.

答:
You can do this using the pairwise function defined in Iterate through pairs of items in a Python list, passing it the items() of the dict:

```<code>from itertools import tee

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

d = {0:0, 1:1, 2:2, 3:3}

list(map(dict,pairwise(d.items())))
# [{0: 0, 1: 1}, {1: 1, 2: 2}, {2: 2, 3: 3}]
</code>```

If you want non-repeating pairs, then you can use zip:

```<code>items = list(d.items())

list(map(dict, zip(items[::2], items[1::2])))
# [{0: 0, 1: 1}, {2: 2, 3: 3}]
</code>```

Dictionaries are fundamentally unordered, so if you want a particular order you need to specify that using some other logic.

Title: Python: split a dict in a list

Body:
I want to convert a simple dict like so: d = {0:0, 1:1, 2:2, 3:3} to a list of dict with the same amount of elements in each of them (or so) as this one: [{0:0, 2:2}, {1:1, 3:3}]. I've tried with simple indexing like I use with lists but it throws me a TypeError: unhashable type: 'slice'. Here what i have right now:

def dico_chunks(dico, n):
    if len(dico) < n:
        n = len(dico)
    return [dico[i::n] for i in range(n)]

Keep in mind that i don't need the list to be order in anyway. I just need to have my main dict splited in a list of n sub-dicts.

Body:
You can do this using the pairwise function defined in Iterate through pairs of items in a Python list, passing it the items() of the dict:

from itertools import tee

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

d = {0:0, 1:1, 2:2, 3:3}

list(map(dict,pairwise(d.items())))
# [{0: 0, 1: 1}, {1: 1, 2: 2}, {2: 2, 3: 3}]

If you want non-repeating pairs, then you can use zip:

items = list(d.items())

list(map(dict, zip(items[::2], items[1::2])))
# [{0: 0, 1: 1}, {2: 2, 3: 3}]

Dictionaries are fundamentally unordered, so if you want a particular order you need to specify that using some other logic.


来源: stackexchange

问:
GCC compilation error, braces around scalar initializer [-Werror]
I'm new in C programming and I try to create a struct containing a char and a function pointer, and that is the problem.

I want to change that code:

```<code>switch (flag) {
    case 'd':
    case 'i':
    return (my_put_nbr(va_arg(ap, int)));
    case 'p':
    return (my_putstr("0x") + my_l_base_changer(va_arg(ap, char *),
    16));
    case 'u':
    return (my_put_unbr(va_arg(ap, unsigned int)));
    case 'b':
    return (my_u_base_changer(va_arg(ap, unsigned int), 2, 0));
    case 'o':
    return (my_u_base_changer(va_arg(ap, unsigned int), 8, 0));
    case 'x':
    return (my_u_base_changer(va_arg(ap, unsigned int), 16, 0));
    case 'X':
    return (my_u_base_changer(va_arg(ap, unsigned int), 16, 1));
    default:
    return (0);
}
</code>```

in that kind of code:

```<code>typedef struct fptr
{
   char op;
   int (*ptr)(va_list);
} fptr;

fptr  fptrs[]=
{
   { 's', ft_print_nb_spec },
   { 'S', ft_print_nb_up },
   { 0, NULL }
};
  int i = 0;
  while (fptrs[i++].op != flag && fptrs[i].op != 0);
  if (fptrs[i].op != 0)
  {
     fptrs[i].ptr();
  }
</code>```

And my struct contain a function pointer to functions who get differents prototypes

My struct is like that :

```<code>typedef struct action {
    char flag;
    void *function;
} action;
</code>```

And my code who bug like that :

```<code>action registers[] = {
    { 'd', (int *)(*my_put_nbr)(int) },
    { 'i', (int)(*my_put_nbr)(va_arg(ap, int)) },
    { 'p', (int)(*my_print_ptr)(va_list ap) },
    { 'u', (int)(*my_put_unbr)(va_arg(ap, unsigned int)) },
    { 'b', (int)(*my_u_base_changer)(va_arg(ap, unsigned int), 2, 0) },
    { 'o', (int)(*my_u_base_changer)(va_arg(ap, unsigned int), 8, 0) },
    { 'x', (int)(*my_u_base_changer)(va_arg(ap, unsigned int), 8, 0) },
    { 'X', (int)(*my_u_base_changer)(va_arg(ap, unsigned int), 8, 1) },
    { 0, NULL }
};
</code>```

And when I run gcc got that:

```<code>flag_nbr.c:13:28: error: expected expression before ‘int’
{ 'd', (int)(my_put_nbr)(int) },
                         ^~~
flag_nbr.c:13:28: error: missing initializer for field ‘function’ of ‘printf_action {aka struct <anonymous>}’ [-Werror=missing-field-initializers]
In file included from flag_nbr.c:8:0:
../include/my.h:21:8: note: ‘function’ declared here
void *function;
      ^~~~~~~~
flag_nbr.c:14:10: error: initialization makes pointer from integer without a cast [-Werror=int-conversion]
{ 'i', (int)(my_put_nbr)(va_arg(ap, int)) },
        ^
</code>```

And I don't understand that error...

答:
You're using typedef to give a name to structure which already has the same name,check that.
This may not be the main cause.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm new in C programming and I try to create a struct containing a char and a function pointer, and that is the problem.

I want to change that code:

switch (flag) {
    case 'd':
    case 'i':
    return (my_put_nbr(va_arg(ap, int)));
    case 'p':
    return (my_putstr("0x") + my_l_base_changer(va_arg(ap, char *),
    16));
    case 'u':
    return (my_put_unbr(va_arg(ap, unsigned int)));
    case 'b':
    return (my_u_base_changer(va_arg(ap, unsigned int), 2, 0));
    case 'o':
    return (my_u_base_changer(va_arg(ap, unsigned int), 8, 0));
    case 'x':
    return (my_u_base_changer(va_arg(ap, unsigned int), 16, 0));
    case 'X':
    return (my_u_base_changer(va_arg(ap, unsigned int), 16, 1));
    default:
    return (0);
}

in that kind of code:

typedef struct fptr
{
   char op;
   int (*ptr)(va_list);
} fptr;

fptr  fptrs[]=
{
   { 's', ft_print_nb_spec },
   { 'S', ft_print_nb_up },
   { 0, NULL }
};
  int i = 0;
  while (fptrs[i++].op != flag && fptrs[i].op != 0);
  if (fptrs[i].op != 0)
  {
     fptrs[i].ptr();
  }

And my struct contain a function pointer to functions who get differents prototypes

My struct is like that :

typedef struct action {
    char flag;
    void *function;
} action;

And my code who bug like that :

action registers[] = {
    { 'd', (int *)(*my_put_nbr)(int) },
    { 'i', (int)(*my_put_nbr)(va_arg(ap, int)) },
    { 'p', (int)(*my_print_ptr)(va_list ap) },
    { 'u', (int)(*my_put_unbr)(va_arg(ap, unsigned int)) },
    { 'b', (int)(*my_u_base_changer)(va_arg(ap, unsigned int), 2, 0) },
    { 'o', (int)(*my_u_base_changer)(va_arg(ap, unsigned int), 8, 0) },
    { 'x', (int)(*my_u_base_changer)(va_arg(ap, unsigned int), 8, 0) },
    { 'X', (int)(*my_u_base_changer)(va_arg(ap, unsigned int), 8, 1) },
    { 0, NULL }
};

And when I run gcc got that:

flag_nbr.c:13:28: error: expected expression before ‘int’
{ 'd', (int)(my_put_nbr)(int) },
                         ^~~
flag_nbr.c:13:28: error: missing initializer for field ‘function’ of ‘printf_action {aka struct <anonymous>}’ [-Werror=missing-field-initializers]
In file included from flag_nbr.c:8:0:
../include/my.h:21:8: note: ‘function’ declared here
void *function;
      ^~~~~~~~
flag_nbr.c:14:10: error: initialization makes pointer from integer without a cast [-Werror=int-conversion]
{ 'i', (int)(my_put_nbr)(va_arg(ap, int)) },
        ^

And I don't understand that error...


问:
SSAS Dax (creating measures)
hopefully someone can help with this.

I am building a cube in SQL Server Data Tools 2015 and have imported my tables. I want to create a measure that basically says if a date column is 30 days older than todays date and another column is null and another column is "yes" then 1, else 0. All these columns are on the same table.

I guess I am looking for the DAX equivalent of a case statement.

Can anyone help? I have tried google but can't find anything specific to what I need.

Appreciate any help

答:
This can be done with an IF() function:

```<code>Calculated Column = IF(Table1[Date] < TODAY() - 30 && Table1[Col2] = BLANK(), 1, 0)
</code>```

where Table1 is the table these columns live on and Col2 is the "another column" you mentioned.

Title: SSAS Dax (creating measures)

Body:
This can be done with an IF() function:

Calculated Column = IF(Table1[Date] < TODAY() - 30 && Table1[Col2] = BLANK(), 1, 0)

where Table1 is the table these columns live on and Col2 is the "another column" you mentioned.


问:
Hide/handle servlet exception stack trace output
From this post I have thought of another question I cannot seem to find the answer to on the interweb.

I have a servlet filter which detects session timeouts and redirects to an error page.  Due to my fledgling java I've used try catch blocks to catch exceptions and handle them gracefully, but in a session timeout situation, the context is invalid so I don't think I've got any code I can do that with which will stop the 'viewId could not be restored' stace trace appearing in my log even though I have a filter handling it.

How can I stop the exception trace from appearing in my log?  It will be monitored autoamtically in live and it will be a false positive call out to the support team for this sort of error.

Any help appreciated.

EDIT

To be more clear, my code clip is currently

```<code>public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    try {
        chain.doFilter(request, response);
    } catch (ServletException e) {
        logger.error("Caught Servlet Exception");
        Throwable rootCause = e.getRootCause();
        logger.error("Root cause is " + rootCause.toString());

        if (rootCause instanceof RuntimeException) { // This is true for any FacesException.
            logger.error("Rethrowing exception as RuntimeException" + rootCause.toString());
            throw (RuntimeException) rootCause; // Throw wrapped RuntimeException instead of ServletException.
        } else {
            throw e;
        }
    }
}
</code>```

The log says:

```<code>    |STDOUT| 2011-01-19 10:40:57,803 | ERROR | [http-8080-5]: Exception in the filter chain
    javax.servlet.ServletException: viewId:/index.jsf - View /index.jsf could not be restored.
        at javax.faces.webapp.FacesServlet.service(FacesServlet.java:270)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:178)
        at org.ajax4jsf.webapp.BaseFilter.handleRequest(BaseFilter.java:290)
<snip>
        at java.lang.Thread.run(Unknown Source)
    Caused by: javax.faces.application.ViewExpiredException: viewId:/index.jsf - View /index.jsf could not be restored.
<snip>
        at javax.faces.webapp.FacesServlet.service(FacesServlet.java:265)
        ... 21 more
    19-Jan-2011 10:40:57 org.apache.catalina.core.StandardWrapperValve invoke
    SEVERE: Servlet.service() for servlet Faces Servlet threw exception
    javax.faces.application.ViewExpiredException: viewId:/index.jsf - View /index.jsf could not be restored.
        at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:185)
<snip>
        at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
        at java.lang.Thread.run(Unknown Source)
    |STDOUT| 2011-01-19 10:40:57,803 | ERROR | [http-8080-5]: Caught Servlet Exception
    |STDOUT| 2011-01-19 10:40:57,803 | ERROR | [http-8080-5]: Root cause is javax.faces.application.ViewExpiredException: viewId:/index.jsf - View /index.jsf could not be restored.
    |STDOUT| 2011-01-19 10:40:57,803 | ERROR | [http-8080-5]: Rethrowing exception as RuntimeExceptionjavax.faces.application.ViewExpiredException: viewId:/index.jsf - View /index.jsf could not be restored.
</code>```

As you can see from the code, I've caught the servlet exception in the filter, but the stack is still appearing in the log.

NEXT EDIT
The complete list of filters in my web.xml is as follows:

```<code><filter>
    <filter-name>Error</filter-name>
    <filter-class>prismClient.ErrorFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>Error</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
    <display-name>RichFaces Filter</display-name>
    <filter-name>richfaces</filter-name>
    <filter-class>org.ajax4jsf.Filter</filter-class>
</filter>
<filter-mapping>
    <filter-name>richfaces</filter-name>
    <servlet-name>Faces Servlet</servlet-name>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
</filter-mapping>
</code>```

答:
Filters are executed in the order they are defined in the web.xml file. In your case, it looks like the jfaces filter is executed first and logging the stack trace before your custom filter has a chance to filter it out. Try making your filter entry in web.xml the first one.

EDIT

It's possible that some other filter in the chain is logging the ServletException before it throws it. In the stack trace you posted, it looks like there is a filter for ajax4jsf that may be logging the ServletException.  Do you have the source for this?  How may filters are in your web.xml?

EDIT 2

It looks like ajax4jsf is catching ServletException and logging an error message before throwing it back out.  I suggest you get the source for the version of ajax4jsf that you're using and look at the lines in the stack trace (BaseXMLFilter.java line 178 and BaseFilter.java line 290) and search for logging statements.  If you find them, you can either remove them from the source and rebuild ajax4jsf, or disable the category in your logging configuration file.  I don't recommend the latter, because you will miss other errors that may occur in the filter.

If that is not the source of the error message, then I'm afraid I've run out of ideas.

ContentLicense: CC BY-SA 2.5

Body:
From this post I have thought of another question I cannot seem to find the answer to on the interweb.

I have a servlet filter which detects session timeouts and redirects to an error page.  Due to my fledgling java I've used try catch blocks to catch exceptions and handle them gracefully, but in a session timeout situation, the context is invalid so I don't think I've got any code I can do that with which will stop the 'viewId could not be restored' stace trace appearing in my log even though I have a filter handling it.

How can I stop the exception trace from appearing in my log?  It will be monitored autoamtically in live and it will be a false positive call out to the support team for this sort of error.

Any help appreciated.

EDIT

To be more clear, my code clip is currently

public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    try {
        chain.doFilter(request, response);
    } catch (ServletException e) {
        logger.error("Caught Servlet Exception");
        Throwable rootCause = e.getRootCause();
        logger.error("Root cause is " + rootCause.toString());

        if (rootCause instanceof RuntimeException) { // This is true for any FacesException.
            logger.error("Rethrowing exception as RuntimeException" + rootCause.toString());
            throw (RuntimeException) rootCause; // Throw wrapped RuntimeException instead of ServletException.
        } else {
            throw e;
        }
    }
}

The log says:

    |STDOUT| 2011-01-19 10:40:57,803 | ERROR | [http-8080-5]: Exception in the filter chain
    javax.servlet.ServletException: viewId:/index.jsf - View /index.jsf could not be restored.
        at javax.faces.webapp.FacesServlet.service(FacesServlet.java:270)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:178)
        at org.ajax4jsf.webapp.BaseFilter.handleRequest(BaseFilter.java:290)
<snip>
        at java.lang.Thread.run(Unknown Source)
    Caused by: javax.faces.application.ViewExpiredException: viewId:/index.jsf - View /index.jsf could not be restored.
<snip>
        at javax.faces.webapp.FacesServlet.service(FacesServlet.java:265)
        ... 21 more
    19-Jan-2011 10:40:57 org.apache.catalina.core.StandardWrapperValve invoke
    SEVERE: Servlet.service() for servlet Faces Servlet threw exception
    javax.faces.application.ViewExpiredException: viewId:/index.jsf - View /index.jsf could not be restored.
        at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:185)
<snip>
        at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
        at java.lang.Thread.run(Unknown Source)
    |STDOUT| 2011-01-19 10:40:57,803 | ERROR | [http-8080-5]: Caught Servlet Exception
    |STDOUT| 2011-01-19 10:40:57,803 | ERROR | [http-8080-5]: Root cause is javax.faces.application.ViewExpiredException: viewId:/index.jsf - View /index.jsf could not be restored.
    |STDOUT| 2011-01-19 10:40:57,803 | ERROR | [http-8080-5]: Rethrowing exception as RuntimeExceptionjavax.faces.application.ViewExpiredException: viewId:/index.jsf - View /index.jsf could not be restored.

As you can see from the code, I've caught the servlet exception in the filter, but the stack is still appearing in the log.

NEXT EDIT
The complete list of filters in my web.xml is as follows:

<filter>
    <filter-name>Error</filter-name>
    <filter-class>prismClient.ErrorFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>Error</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
    <display-name>RichFaces Filter</display-name>
    <filter-name>richfaces</filter-name>
    <filter-class>org.ajax4jsf.Filter</filter-class>
</filter>
<filter-mapping>
    <filter-name>richfaces</filter-name>
    <servlet-name>Faces Servlet</servlet-name>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
</filter-mapping>


问:
Autodesk Forge: What is the difference between dbId, objectId, and nodeId?
What is the difference between dbId, objectId, and nodeId?

For example, the first argument of the following functions is the same kind of id or ids?

fitToView(objectIds,model)

objectIds: array of Ids, or null.

getProperties(dbId,onSuccessCallback,onErrorCallback)

dbId: ID of the node to return the properties for.

select(dbids,selectionType)

dbids: You can pass an array of IDs or just a single ID.

hideById(nodeId)

nodeId: (no description)

from Viewer API reference here

答: It's actually the same, just some discrepancies about the doc. </p>


问:
Exiting using :? in bash
I have the following at the top of my bash script:

```<code> "${PROJECT_DIR:?"Need to set PROJECT_DIR by sourcing <project dir>/setup.sh"}"
 echo "D'oh!"
</code>```

When I source this (using .) I get the following:

```<code>-bash: PROJECT_DIR: Need to set PROJECT_DIR by sourcing <project dir>/setup.sh
D'oh!
</code>```

I was hoping to exit when the variable is not set.  Am I missing something?

答:
Unfortunately, :? isn't the right tool for the job. Consider instead:

```<code>[ -n "$PROJECT_DIR" ] || {
  echo "Need to set PROJECT_DIR by sourcing <project dir>/setup.sh" >&2
  return 1 || exit 1
}
</code>```

return jumps out to the parent interpreter where it was before calling source. If it fails, presumably your script was executed rather than sourced, so we fall back to exit instead.

Title: Exiting using :? in bash

Body:
I have the following at the top of my bash script:

 "${PROJECT_DIR:?"Need to set PROJECT_DIR by sourcing <project dir>/setup.sh"}"
 echo "D'oh!"

When I source this (using .) I get the following:

-bash: PROJECT_DIR: Need to set PROJECT_DIR by sourcing <project dir>/setup.sh
D'oh!

I was hoping to exit when the variable is not set.  Am I missing something?

Body:
Unfortunately, :? isn't the right tool for the job. Consider instead:

[ -n "$PROJECT_DIR" ] || {
  echo "Need to set PROJECT_DIR by sourcing <project dir>/setup.sh" >&2
  return 1 || exit 1
}

return jumps out to the parent interpreter where it was before calling source. If it fails, presumably your script was executed rather than sourced, so we fall back to exit instead.


问:
How to show an elements value in a vue modal?
I have several elements that are displayed as
 elements in a loop. For each element I want behavior such that when the element is clicked a modal box opens up. Inside the modal box I want contents that are specific to the element that was clicked.

The data below shows all the elements:

```<code>              {value: 10, name: "foo"},
              {value: 12, name: "bar"},
              {value: 14, name: "foobar"},
              {value: 22, name: "test"},
              {value: 1, name: "testtooo"},
              {value: 8, name: "something"}
</code>```

When I click on an element, I want to see the value property for it inside the modal box.

I've created a fiddle for this: https://jsfiddle.net/hvb9hvog/14/

Question

I've gotten the modal working, however, how can I show each elements value property inside the modal?

答:
I'm not sure if you are asking this using Vue.js or just JS. So, here are my answers (basic examples). I recommend you to read about event delegation + events on vuejs.

Vue Js

```<code><template>
  <div class="content">
    <ul>
      <li v-for="item in items" @click.prevent="showModal(item)">{{ item }}</li>
    </ul>

    <div class="modal" v-show="isModalVisible">
      {{ JSON.stringify(selectedItem) }}
      <a href="#" @click.prevent="selectedItem = null">close modal</a>
    </div>
  </div>
</template>
<script>
  export default {
    name: 'something',
    data () {
      return {
        selectedItem: item,
        items: [{
          id: 1,
          name: 'something'
        }, {
          id: 2,
          name: 'something #2'
        }]
      }
    },
    computed: {
      isModalVisible () {
        return this.selectedItem !== null
      }
    }
    methods: {
      showModal (item) {
        this.selectedItem = item
      }
    }
  }
</script>
</code>```

Plain javascript

```<code>const toggleModal = content => {
  const $body = document.querySelector('body')
  const $modal = $body.querySelector('.modal')
  $modal && $modal.remove()
  $body.insertAdjacentHTML('beforeend',`<div class="modal">${content}</div>`)
}

document.querySelector('ul').addEventListener('click', e => {
  if (! e.target.matches('li')) {
    return
  }

  toggleModal(e.target.innerText)
});
</code>```

About Event delegation.

About insertAdjacentHtml.

About Vuejs Event handling

Body:
I have several elements that are displayed as
 elements in a loop. For each element I want behavior such that when the element is clicked a modal box opens up. Inside the modal box I want contents that are specific to the element that was clicked.

The data below shows all the elements:

              {value: 10, name: "foo"},
              {value: 12, name: "bar"},
              {value: 14, name: "foobar"},
              {value: 22, name: "test"},
              {value: 1, name: "testtooo"},
              {value: 8, name: "something"}

When I click on an element, I want to see the value property for it inside the modal box.

I've created a fiddle for this: https://jsfiddle.net/hvb9hvog/14/

Question

I've gotten the modal working, however, how can I show each elements value property inside the modal?

Body:
I'm not sure if you are asking this using Vue.js or just JS. So, here are my answers (basic examples). I recommend you to read about event delegation + events on vuejs.

Vue Js

<template>
  <div class="content">
    <ul>
      <li v-for="item in items" @click.prevent="showModal(item)">{{ item }}</li>
    </ul>

    <div class="modal" v-show="isModalVisible">
      {{ JSON.stringify(selectedItem) }}
      <a href="#" @click.prevent="selectedItem = null">close modal</a>
    </div>
  </div>
</template>
<script>
  export default {
    name: 'something',
    data () {
      return {
        selectedItem: item,
        items: [{
          id: 1,
          name: 'something'
        }, {
          id: 2,
          name: 'something #2'
        }]
      }
    },
    computed: {
      isModalVisible () {
        return this.selectedItem !== null
      }
    }
    methods: {
      showModal (item) {
        this.selectedItem = item
      }
    }
  }
</script>

Plain javascript

const toggleModal = content => {
  const $body = document.querySelector('body')
  const $modal = $body.querySelector('.modal')
  $modal && $modal.remove()
  $body.insertAdjacentHTML('beforeend',`<div class="modal">${content}</div>`)
}

document.querySelector('ul').addEventListener('click', e => {
  if (! e.target.matches('li')) {
    return
  }

  toggleModal(e.target.innerText)
});

About Event delegation.

About insertAdjacentHtml.

About Vuejs Event handling

ContentLicense: CC BY-SA 4.0


问:
how to restrict input in UISearchBar?
i'm new in Objective C, i have search bar in my tableView. I need no restrict input in my searchBar text field, for example i don't need to input more then 20 symbols, how can i do these?

in

```<code>-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
</code>```

i try to write smth like

```<code>searchBar.text.lenght == 20;
</code>```

but it's no use

how can i do these? or maybe it easier to turn off keyboard when lenght>20. Thank you.

答:
For future reader, in Swift 4:</p>

```<code>func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    let totalCharacters = (searchBar.text?.appending(text).count ?? 0) - range.length
    return totalCharacters <= 20
}
</code>```

Title: how to restrict input in UISearchBar?

Body:
i'm new in Objective C, i have search bar in my tableView. I need no restrict input in my searchBar text field, for example i don't need to input more then 20 symbols, how can i do these?

in

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText

i try to write smth like

searchBar.text.lenght == 20;

but it's no use

how can i do these? or maybe it easier to turn off keyboard when lenght>20. Thank you.

Body:
For future reader, in Swift 4:

func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    let totalCharacters = (searchBar.text?.appending(text).count ?? 0) - range.length
    return totalCharacters <= 20
}


问:
Multitenant Rails model Inheritance
My multi-tenant "Customer" model represents data from multiple tables in a "org_#{current_user.org.id}_customers" pattern (i.e. org_1_customers, org_2_customers, etc). I'm using RequestStore gem to store current_user's ORG_ID.

So, the problem is that to access data of CURRENT organization, I have to explicitly call "Customer.org" (i.e. Customer.org.where(...).load). Which requires rewriting A LOT of code, and remembering to add "org" every time I access the data.

MY QUESTION IS: Is there a way to make it so that I could access "Customer.org" by calling "Customer", so I would use "Customer" for current tenant's/org's customers, and "Customer.select_org(7)" for other tenant's/org's customers?

```<code>class ApplicationController < ActionController::Base
    before_filter :find_organization

    private
    def find_organization
        RequestStore[:current_org] = current_user ? current_user.org : nil
    end
end

class SegregatedMultitenantModel < ActiveRecord::Base
    self.abstract_class = true

    def self.select_org(org_id)
        @subdomain_classes ||= {}
        unless @subdomain_classes[org_id]
            @subdomain_classes[org_id] ||= Class.new(self)
            @subdomain_classes[org_id].table_name = "org_#{org_id}_#{self.table_name}" # This needs sanitizing, of course
            @subdomain_classes[org_id].reset_column_information
        end

        @subdomain_classes[org_id]
    end

    def self.org
        if RequestStore[:current_org].nil?
            raise "No Organization Selected For #{self.table_name}"
        else
            self.select_org(RequestStore[:current_org].id)
        end
    end
end

class Customer < SegregatedMultitenantModel
end
</code>```

P.S. My application does require multiple Customer tables due to differences in table fields between tenants!

答:
I've come up with a solution! It scopes the rows by convention anywhere in the app and I'm satisfied with it:

```<code># Returns first row from "org_#{current_user.org.id}_customers" table
MT::Customer.first

# Returns first row from "org_3_customers" table
MT::Customer.select_org(3).first
</code>```

To Do this, first, I segregated the "scoping" into a class:

```<code>class MT

    @@segregated_organization_models = {}

    def self.init(organizations, current_org, *options)
        organizations.each do |org|
            options[0][:segregated_models].each do |class_object|
                # Create new model class
                @@segregated_organization_models[org.id] ||= {}

                a = Class.new(class_object)
                @@segregated_organization_models[org.id][class_object.to_s.to_sym] = a

                # Set correct table name
                @@segregated_organization_models[org.id][class_object.to_s.to_sym].table_name = "org_#{org.id}_#{class_object.table_name}"

                # Set default model class to current organization's model class
                if org.id === current_org.id
                    self.const_set(class_object.to_s.to_sym, @@segregated_organization_models[org.id][class_object.to_s.to_sym])
                end
            end
        end
    end
end
</code>```

while getting rid of the RequestStore gem and model logic in favor of the controller:

```<code>class ApplicationController < ActionController::Base
    before_filter :find_organization

    private
    # Multitenancy helpers

    def find_organization
        MT.init(Organization.all, current_user.org,
            segregated_models: [
                ArticleCategory, Article, CustomArticleField,
                Customer, CustomerChange, CustomerLedgerItem
            ]
        )
    end
end
</code>```

Model inheritance is still there:

```<code>class SegregatedMultitenantModel < ActiveRecord::Base
    self.abstract_class = true

    def self.select_org(org_id)
        MT.class_variable_get(:@@segregated_organization_models)[org_id][self.to_s.demodulize.to_sym]
    end
end

class Customer < SegregatedMultitenantModel
    self.abstract_class = true
    self.table_name = "customers"
end
</code>```

Thanks a lot to an anonymous commenter who since deleted his response. Please don't delete your good responses with useful information! I have nothing to upvote. Lol.

Title: Multitenant Rails model Inheritance

Body:
My multi-tenant "Customer" model represents data from multiple tables in a "org_#{current_user.org.id}_customers" pattern (i.e. org_1_customers, org_2_customers, etc). I'm using RequestStore gem to store current_user's ORG_ID.

So, the problem is that to access data of CURRENT organization, I have to explicitly call "Customer.org" (i.e. Customer.org.where(...).load). Which requires rewriting A LOT of code, and remembering to add "org" every time I access the data.

MY QUESTION IS: Is there a way to make it so that I could access "Customer.org" by calling "Customer", so I would use "Customer" for current tenant's/org's customers, and "Customer.select_org(7)" for other tenant's/org's customers?

class ApplicationController < ActionController::Base
    before_filter :find_organization

    private
    def find_organization
        RequestStore[:current_org] = current_user ? current_user.org : nil
    end
end

class SegregatedMultitenantModel < ActiveRecord::Base
    self.abstract_class = true

    def self.select_org(org_id)
        @subdomain_classes ||= {}
        unless @subdomain_classes[org_id]
            @subdomain_classes[org_id] ||= Class.new(self)
            @subdomain_classes[org_id].table_name = "org_#{org_id}_#{self.table_name}" # This needs sanitizing, of course
            @subdomain_classes[org_id].reset_column_information
        end

        @subdomain_classes[org_id]
    end

    def self.org
        if RequestStore[:current_org].nil?
            raise "No Organization Selected For #{self.table_name}"
        else
            self.select_org(RequestStore[:current_org].id)
        end
    end
end

class Customer < SegregatedMultitenantModel
end

P.S. My application does require multiple Customer tables due to differences in table fields between tenants!

Body:
I've come up with a solution! It scopes the rows by convention anywhere in the app and I'm satisfied with it:

# Returns first row from "org_#{current_user.org.id}_customers" table
MT::Customer.first

# Returns first row from "org_3_customers" table
MT::Customer.select_org(3).first

To Do this, first, I segregated the "scoping" into a class:

class MT

    @@segregated_organization_models = {}

    def self.init(organizations, current_org, *options)
        organizations.each do |org|
            options[0][:segregated_models].each do |class_object|
                # Create new model class
                @@segregated_organization_models[org.id] ||= {}

                a = Class.new(class_object)
                @@segregated_organization_models[org.id][class_object.to_s.to_sym] = a

                # Set correct table name
                @@segregated_organization_models[org.id][class_object.to_s.to_sym].table_name = "org_#{org.id}_#{class_object.table_name}"

                # Set default model class to current organization's model class
                if org.id === current_org.id
                    self.const_set(class_object.to_s.to_sym, @@segregated_organization_models[org.id][class_object.to_s.to_sym])
                end
            end
        end
    end
end

while getting rid of the RequestStore gem and model logic in favor of the controller:

class ApplicationController < ActionController::Base
    before_filter :find_organization

    private
    # Multitenancy helpers

    def find_organization
        MT.init(Organization.all, current_user.org,
            segregated_models: [
                ArticleCategory, Article, CustomArticleField,
                Customer, CustomerChange, CustomerLedgerItem
            ]
        )
    end
end

Model inheritance is still there:

class SegregatedMultitenantModel < ActiveRecord::Base
    self.abstract_class = true

    def self.select_org(org_id)
        MT.class_variable_get(:@@segregated_organization_models)[org_id][self.to_s.demodulize.to_sym]
    end
end

class Customer < SegregatedMultitenantModel
    self.abstract_class = true
    self.table_name = "customers"
end

Thanks a lot to an anonymous commenter who since deleted his response. Please don't delete your good responses with useful information! I have nothing to upvote. Lol.


问:
What may be the difficulties, if any, with the web applications developed in Java EE?
I have a few questions to understand better Java's usage in context of web applications:-

Is Java EE web development suitable for small start-up (with less human resource) looking to develop an web application ?

What kind of difficulties may arise in Java EE web development, deployment & maintenance ?

What kind of things should be kept in mind/ considerations to be made when moving from PHP background to Java ?

Why Java web applications are not so popular today?  ( or in case I perceived it wrongly, please list any major deployments beside linkedIn and ebay)

and Finally, What are some of the most important things to learn before starting web development in Java EE ?

Thank you

答: For a startup an interesting choice could be the Lift web framework, which is used for developing "Java Web Applications" (although in Scala).</p>


问:
Java while loop printing squared numbers can't use int?
In Java, create a do-while loop that starts at 2, and displays the number squared on each line while the number is less than 1,000,000. And this is what I have:

```<code>int k = 2;
do {
    System.out.println(k);
    k *= k;
} while(k < 1000000);
</code>```

The problem is the output, somehow it is getting stuck at 0 and infinitely looping through 0 to print those out? I don't believe it is due to the fact that the number is out of int range, since a 32 bit number's range is around +/- 2 billion... But when I switch up the data type of k to be long everything works fine... Why is this?

答:
It really is due to int. The sequence produced this way is

```<code>2
4
16
256
65536
0
</code>```

And then it remains zero. Note that it never rises above 1000000.

With a long, the number after 65536 would be 4294967296 (which does not fit in an int, but does fit in a long), so it stops.

This is perhaps more obvious in hexadecimal, the sequence then reads (with sufficiently long integers)

```<code>2
4
0x10
0x100
0x10000
0x100000000
</code>```

An int can only keep the lowest 8 hexadecimal digits, so 0x100000000 becomes 0.

Body:
In Java, create a do-while loop that starts at 2, and displays the number squared on each line while the number is less than 1,000,000. And this is what I have:

int k = 2;
do {
    System.out.println(k);
    k *= k;
} while(k < 1000000);

The problem is the output, somehow it is getting stuck at 0 and infinitely looping through 0 to print those out? I don't believe it is due to the fact that the number is out of int range, since a 32 bit number's range is around +/- 2 billion... But when I switch up the data type of k to be long everything works fine... Why is this?

Body:
It really is due to int. The sequence produced this way is

2
4
16
256
65536
0

And then it remains zero. Note that it never rises above 1000000.

With a long, the number after 65536 would be 4294967296 (which does not fit in an int, but does fit in a long), so it stops.

This is perhaps more obvious in hexadecimal, the sequence then reads (with sufficiently long integers)

2
4
0x10
0x100
0x10000
0x100000000

An int can only keep the lowest 8 hexadecimal digits, so 0x100000000 becomes 0.


问:
DPI of an image
I have a requirement where I have to check the DPI of a bunch of images stored in an oracle database as a blob and make sure they are above 300 dpi. I was planning on reading the field via a c# program and trying to determine their dpi, but i was unsure how to calculate this. Can anyone give me some guidance on how I can determine their DPI. </p>

答:
As the name says, DPI represents the number of pixels per inch. To calculate it you need the size of image in inchs and in pixels. The size in inchs is relative to the monitor screen dpi, best resolutions like printers use more points for inch.

So, if your image has 100px and 2in, your dpi is 100/2 = 50 dpi. Realize that the problem is how to determine the size in inchs of your image if basically you need to get an reference of inchs.

Then, would be easier to verify the dpi of image on upload and guarantee the required before the insertion.

Title: DPI of an image


问:
PHP mPDF with cut command - printing too much paper
I have a printer receipt called "Start STP 100" and my website creates a PDF with a receipt format using the mPDF library.

The following code is my class to generate a PDF:

```<code>class printdoc
{
    private $width;

    public function __construct()
    {
        require('mPDF/mpdf.php');

        $this->width = 80;

        // Default values
        $this->mPDF = new mPDF('utf-8', array($this->width, 1000), 9, 'Segoe UI', 5, 5, 0, 0, 5, 5, 'P');
        $this->mPDF->setAutoTopMargin = 'pad';
    }

    public function write($html, $url)
    {
        $this->mPDF->WriteHTML($html[0]);
        $this->mPDF->page   = 0;
        $this->mPDF->state  = 0;
        unset($this->mPDF->pages[0]);

        $p = 'P';
        // At this point the Y size is set according to the dimensions of the PDF
        // So the value '1000' set in the __construct() has no effect.
        $this->mPDF->_setPageSize(array($this->width, $this->mPDF->y), $p);

        foreach($html as $content)
        {
            $this->mPDF->addPage();
            $this->mPDF->WriteHTML($content);
        }

        $this->mPDF->Output($url);
    }

    public function create($data)
    {
        $html  = '<html>';
        $html .= '  <head></head>';
        $html .= '  <body>';
        $html .=        $this->header($data);
        $html .=        $this->body($data);
        $html .=        $this->footer($data);
        $html .= '  </body>';
        $html .= '</html>';

        return $html;
    }
}
</code>```

Now in order to create the receipt and save it, I have this function:

```<code>function printreceipt($data)
{
    require('printdoc.php');

    $file = 'test-receipt.pdf';
    $html = $this->printdoc->create($data);

    $this->printdoc->write($html, $file);
}
</code>```

What happens is that the file generated when seen with Chrome PDF Viewer has the correct dimensions (in terms of width and height), but when sent to the printer it prints too much paper.

Basically this is the size of the PDF (when viewed on a browser):

```<code> ---
|   |
|   |
|   |
 ---
</code>```

And this is the size of the paper when printed:

```<code> ---
|   |
|   |
|   |
|   |
|   |
|   |
|   |
|   |
|   |
|   |
 ---
</code>```

Is there any way to force mPDF to cut the file or write any command after my html in order to the printer interpret and cut?

答:
Seems that Start STP 100 has a bug with Google Chrome that created extra paper.
Using firefox solved the issue.

Please note that the preview for receipts from a Star printer is almost always wrong, showing an extremely long run of receipt paper. Please disregard this, you will be safe to print.

https://www.websitesupport.info/hc/en-us/articles/205959070-Setting-Up-Chrome-For-Windows-To-Print-From-The-Rain-Point-Of-Sale

Body:
I have a printer receipt called "Start STP 100" and my website creates a PDF with a receipt format using the mPDF library.

The following code is my class to generate a PDF:

class printdoc
{
    private $width;

    public function __construct()
    {
        require('mPDF/mpdf.php');

        $this->width = 80;

        // Default values
        $this->mPDF = new mPDF('utf-8', array($this->width, 1000), 9, 'Segoe UI', 5, 5, 0, 0, 5, 5, 'P');
        $this->mPDF->setAutoTopMargin = 'pad';
    }

    public function write($html, $url)
    {
        $this->mPDF->WriteHTML($html[0]);
        $this->mPDF->page   = 0;
        $this->mPDF->state  = 0;
        unset($this->mPDF->pages[0]);

        $p = 'P';
        // At this point the Y size is set according to the dimensions of the PDF
        // So the value '1000' set in the __construct() has no effect.
        $this->mPDF->_setPageSize(array($this->width, $this->mPDF->y), $p);

        foreach($html as $content)
        {
            $this->mPDF->addPage();
            $this->mPDF->WriteHTML($content);
        }

        $this->mPDF->Output($url);
    }

    public function create($data)
    {
        $html  = '';
        $html .= '  ';
        $html .= '  ';
        $html .=        $this->header($data);
        $html .=        $this->body($data);
        $html .=        $this->footer($data);
        $html .= '  ';
        $html .= '';

        return $html;
    }
}

Now in order to create the receipt and save it, I have this function:

function printreceipt($data)
{
    require('printdoc.php');

    $file = 'test-receipt.pdf';
    $html = $this->printdoc->create($data);

    $this->printdoc->write($html, $file);
}

What happens is that the file generated when seen with Chrome PDF Viewer has the correct dimensions (in terms of width and height), but when sent to the printer it prints too much paper.

Basically this is the size of the PDF (when viewed on a browser):

 ---
|   |
|   |
|   |
 ---

And this is the size of the paper when printed:

 ---
|   |
|   |
|   |
|   |
|   |
|   |
|   |
|   |
|   |
|   |
 ---

Is there any way to force mPDF to cut the file or write any command after my html in order to the printer interpret and cut?


问:
Test Template with Robot Framework
I am attempting to utilize the Robot Framework Test Template function and have been experiencing a little difficulty.

My current Test consist of opening 5 different websites (declared as variables)

Here is my code:

```<code>*** Settings ***
Library  Selenium2Library
Library  OperatingSystem
Library  String
Library  Collections
Test Template  Open URL

*** Variables ***
${URL1}     http://montrealgazette.com/
${URL2}     https://www.usatoday.com/
${URL3}     http://www.foxnews.com/
${URL4}     http://www.cnn.com/
${URL5}     https://ca.reuters.com/

*** Test Cases ***
Validate Availability
${URL1}
${URL2}
${URL3}
${URL4}
${URL5}

*** Keywords ***
Open URL
[Arguments]  ${URL}
Open Browser    $[URL]     Chrome
</code>```

When I run this code, 5 separate blank browser windows are opened.If there is a better way to do this, please let me know.
Thanks in advance for the help!

答:
You don't seem to have indented your test case's content, which could perhaps be the problem (after you've fixed the syntax error mentioned in Raj sattam's answer). That's pretty much the only mistake I can see. You'll want to do the same in your keyword's declaration as well.

```<code>*** Test Cases ***
Validate Availability
    ${URL1}
    ${URL2}
    ${URL3}
    ${URL4}
    ${URL5}
</code>```

If that still doesn't fix it, instead of using the ** Settings ** section, you may try to declare the test case itself as a templated test case, like this:

```<code>*** Settings ***
Library  Selenium2Library
Library  OperatingSystem
Library  String
Library  Collections

*** Variables ***
${URL1}     http://montrealgazette.com/
${URL2}     https://www.usatoday.com/
${URL3}     http://www.foxnews.com/
${URL4}     http://www.cnn.com/
${URL5}     https://ca.reuters.com/

*** Test Cases ***
Validate Availability
    [Template]    Open URL
    ${URL1}
    ${URL2}
    ${URL3}
    ${URL4}
    ${URL5}

*** Keywords ***
Open URL
    [Arguments]  ${URL}
    Open Browser    ${URL}     Chrome
</code>```

Title: Test Template with Robot Framework

Body:
I am attempting to utilize the Robot Framework Test Template function and have been experiencing a little difficulty.

My current Test consist of opening 5 different websites (declared as variables)

Here is my code:

*** Settings ***
Library  Selenium2Library
Library  OperatingSystem
Library  String
Library  Collections
Test Template  Open URL

*** Variables ***
${URL1}     http://montrealgazette.com/
${URL2}     https://www.usatoday.com/
${URL3}     http://www.foxnews.com/
${URL4}     http://www.cnn.com/
${URL5}     https://ca.reuters.com/

*** Test Cases ***
Validate Availability
${URL1}
${URL2}
${URL3}
${URL4}
${URL5}

*** Keywords ***
Open URL
[Arguments]  ${URL}
Open Browser    $[URL]     Chrome

When I run this code, 5 separate blank browser windows are opened.If there is a better way to do this, please let me know.
Thanks in advance for the help!

Body:
You don't seem to have indented your test case's content, which could perhaps be the problem (after you've fixed the syntax error mentioned in Raj sattam's answer). That's pretty much the only mistake I can see. You'll want to do the same in your keyword's declaration as well.

*** Test Cases ***
Validate Availability
    ${URL1}
    ${URL2}
    ${URL3}
    ${URL4}
    ${URL5}

If that still doesn't fix it, instead of using the ** Settings ** section, you may try to declare the test case itself as a templated test case, like this:

*** Settings ***
Library  Selenium2Library
Library  OperatingSystem
Library  String
Library  Collections

*** Variables ***
${URL1}     http://montrealgazette.com/
${URL2}     https://www.usatoday.com/
${URL3}     http://www.foxnews.com/
${URL4}     http://www.cnn.com/
${URL5}     https://ca.reuters.com/

*** Test Cases ***
Validate Availability
    [Template]    Open URL
    ${URL1}
    ${URL2}
    ${URL3}
    ${URL4}
    ${URL5}

*** Keywords ***
Open URL
    [Arguments]  ${URL}
    Open Browser    ${URL}     Chrome


问:
Word comparison algorithm
I am doing a CSV Import tool for the project I'm working on.
The client needs to be able to enter the data in excel, export them as CSV and upload them to the database.
For example I have this CSV record:

```<code>   1,   John Doe,     ACME Comapny   (the typo is on purpose)
</code>```

Of course, the companies are kept in a separate table and linked with a foreign key, so I need to discover the correct company ID before inserting.
I plan to do this by comparing the company names in the database with the company names in the CSV.
the comparison should return 0 if the strings are exactly the same, and return some value that gets bigger as the strings get more different, but strcmp doesn't cut it here because:

"Acme Company" and "Acme Comapny" should have a very small difference index, but
"Acme Company" and "Cmea Mpnyaco" should have a very big difference index
Or "Acme Company" and "Acme Comp." should also have a small difference index, even though the character count is different.
Also, "Acme Company" and "Company Acme" should return 0.

So if the client makes a type while entering data, i could prompt him to choose the name he most probably wanted to insert.

Is there a known algorithm to do this, or maybe we can invent one :)
?

答:
There's multiple algorithms to do just that, and most databases even include one by default. It is actually a quite common concern.

If its just about English words, SQL Server for example includes SOUNDEX which can be used to compare on the resulting sound of the word.

http://msdn.microsoft.com/en-us/library/aa259235%28SQL.80%29.aspx

OwnerDisplayName: Discodancer

Title: Word comparison algorithm

Body:
I am doing a CSV Import tool for the project I'm working on.
The client needs to be able to enter the data in excel, export them as CSV and upload them to the database.
For example I have this CSV record:

   1,   John Doe,     ACME Comapny   (the typo is on purpose)

Of course, the companies are kept in a separate table and linked with a foreign key, so I need to discover the correct company ID before inserting.
I plan to do this by comparing the company names in the database with the company names in the CSV.
the comparison should return 0 if the strings are exactly the same, and return some value that gets bigger as the strings get more different, but strcmp doesn't cut it here because:

"Acme Company" and "Acme Comapny" should have a very small difference index, but
"Acme Company" and "Cmea Mpnyaco" should have a very big difference index
Or "Acme Company" and "Acme Comp." should also have a small difference index, even though the character count is different.
Also, "Acme Company" and "Company Acme" should return 0.

So if the client makes a type while entering data, i could prompt him to choose the name he most probably wanted to insert.

Is there a known algorithm to do this, or maybe we can invent one :)
?

OwnerDisplayName: Loki


问:
Format a date (string) with XSLT
There are a lot of questions/answers on this particular subject, but none seem to address the specific issue I have. I'm also a complete noob, so there's that ;-). I have the following XML being sent from an application to a piece of middleware. In that middleware, I'm capturing the XML and pulling out data. My last remaining challenge is to re-format a piece of string data that represents a date, that sits inside the <now></now> tags.

```<code><?xml version="1.0" encoding="UTF-8"?>
    <Body>
        <send_message xmlns="urn:xyztech:agent">
            <user>
                <now>2017-11-15T13:38:11+00:00</now>
                <company>xyz.demo</company>
            </user>
        </send_message>
    </Body>
</code>```

I'm using Apigee for the middleware, and need an XSL script to manipulate the date (to make it a bit cleaner - something like 15/11/2017 or 15.11.2017, and I don't want the time). I've tried several examples that I've seen, but none seem to work for me. Unfortunately, being the noob, I'm not really able to debug the errors that occur with those examples (e.g. failing to find the function from the namespace reference), and I'd really appreciate some assistance/guidance.

It would be pretty slick if I could use the XPath that I already have in the XSL that extracts the data:

```<code><Variable name="now" type="date">
    <XPath>//Envelope/Body/send_message/user/now</XPath>
</Variable>
</code>```

I've seen a solution for that, but I have a feeling that Apigee doesn't support XPath 2.0, so format-date($d,"[D]-[M]-[Y]") doesn't apper to be a viable option, either. Any/all help gratefully received...

答:
The answer (full solution), taking some of what Christian Mosz & valdi_bo suggested above, and a final wonderfully helpful solution and explanation from @friedemann_bach (from a separate question I asked) is this, as the full XSL I needed:

```<code><?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:ms="urn:schemas-microsoft-com:xslt">

<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="now">
  <now>
    <xsl:variable name="srcDateTime" select="//Envelope/Body/send_message/user/now"/>
    <xsl:variable name="srcDate" select="substring-before($srcDateTime, 'T')" />
    <xsl:variable name="outDate" select="format-date(xs:date($srcDate),'[D01].[M01].[Y0001]')"/>
    <xsl:value-of select="$outDate" disable-output-escaping="yes"/>
  </now>
</xsl:template>
</xsl:stylesheet>
</code>```

Whilst the first two answers here provided the solution to the date format, the issue I then had to contend with was not understanding why all the other tags were being ripped out. The first (additional) template fixes that (it serves to change nothing, so that the second template overrides "no change" only on the node I select in the second template.
Many thanks to everyone that helped. Being a noob (learning through simply HAVING to do it & get it done), I needed the full solution AND the explanation. I know it's a little "please do it for me", but it all adds to the knowledge, and that's kinda the point. Thanks all again.

Title: Format a date (string) with XSLT

Body:
There are a lot of questions/answers on this particular subject, but none seem to address the specific issue I have. I'm also a complete noob, so there's that ;-). I have the following XML being sent from an application to a piece of middleware. In that middleware, I'm capturing the XML and pulling out data. My last remaining challenge is to re-format a piece of string data that represents a date, that sits inside the <now></now> tags.

<?xml version="1.0" encoding="UTF-8"?>

        <send_message xmlns="urn:xyztech:agent">
            <user>
                <now>2017-11-15T13:38:11+00:00</now>
                <company>xyz.demo</company>
            </user>
        </send_message>

I'm using Apigee for the middleware, and need an XSL script to manipulate the date (to make it a bit cleaner - something like 15/11/2017 or 15.11.2017, and I don't want the time). I've tried several examples that I've seen, but none seem to work for me. Unfortunately, being the noob, I'm not really able to debug the errors that occur with those examples (e.g. failing to find the function from the namespace reference), and I'd really appreciate some assistance/guidance.

It would be pretty slick if I could use the XPath that I already have in the XSL that extracts the data:

<Variable name="now" type="date">
    <XPath>//Envelope/Body/send_message/user/now</XPath>
</Variable>

I've seen a solution for that, but I have a feeling that Apigee doesn't support XPath 2.0, so format-date($d,"[D]-[M]-[Y]") doesn't apper to be a viable option, either. Any/all help gratefully received...

Body:
The answer (full solution), taking some of what Christian Mosz & valdi_bo suggested above, and a final wonderfully helpful solution and explanation from @friedemann_bach (from a separate question I asked) is this, as the full XSL I needed:

<?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:ms="urn:schemas-microsoft-com:xslt">

<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="now">
  <now>
    <xsl:variable name="srcDateTime" select="//Envelope/Body/send_message/user/now"/>
    <xsl:variable name="srcDate" select="substring-before($srcDateTime, 'T')" />
    <xsl:variable name="outDate" select="format-date(xs:date($srcDate),'[D01].[M01].[Y0001]')"/>
    <xsl:value-of select="$outDate" disable-output-escaping="yes"/>
  </now>
</xsl:template>
</xsl:stylesheet>

Whilst the first two answers here provided the solution to the date format, the issue I then had to contend with was not understanding why all the other tags were being ripped out. The first (additional) template fixes that (it serves to change nothing, so that the second template overrides "no change" only on the node I select in the second template.
Many thanks to everyone that helped. Being a noob (learning through simply HAVING to do it & get it done), I needed the full solution AND the explanation. I know it's a little "please do it for me", but it all adds to the knowledge, and that's kinda the point. Thanks all again.


问:
I am getting an error while building grade file
I am trying to build my gradle after adding the following lines

```<code>implementation "com.android.support:appcompat-v7:${versions.supportLib}"

    implementation "com.android.support:recyclerview-v7:${versions.supportLib}"

    implementation "com.android.support:support-annotations:${versions.supportLib}"

    implementation "com.android.support:design:${versions.supportLib}"
</code>```

I get the following error

```<code>Error:(32, 0) Could not get unknown property 'versions' for object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
<a href="openFile:C:\Users\Sagar\Desktop\SickLab\app\build.gradle">Open File</a>
</code>```

My entire grade file is as follows

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.sagar.sicklab"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support:support-v4:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'

    implementation("com.mikepenz:materialdrawer:6.0.1@aar") {
        transitive = true
    }

    implementation "com.android.support:appcompat-v7:${versions.supportLib}"

    implementation "com.android.support:recyclerview-v7:${versions.supportLib}"

    implementation "com.android.support:support-annotations:${versions.supportLib}"

    implementation "com.android.support:design:${versions.supportLib}"

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support:support-v4:26.+'
    compile 'com.android.support:design:26.+'
    compile 'com.google.android.gms:play-services-ads:11.0.1'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'

    compile 'com.github.apl-devs:appintro:v4.2.2'
    compile 'eu.long1:spacetablayout:1.0.4'

}
</code>```

答:
Just add in your file:

```<code>ext {
    supportLibraryVersion = "25.3.1"
}
</code>```

And replace:

```<code>compile "com.android.support:appcompat-v7:$supportLibraryVersion"
compile "com.android.support:support-v4:$supportLibraryVersion"
compile "com.android.support:cardview-v7:$supportLibraryVersion"
compile "com.android.support:recyclerview-v7:$supportLibraryVersion"
compile "com.android.support:design:$supportLibraryVersion"
</code>```

Body:
I am trying to build my gradle after adding the following lines

implementation "com.android.support:appcompat-v7:${versions.supportLib}"

    implementation "com.android.support:recyclerview-v7:${versions.supportLib}"

    implementation "com.android.support:support-annotations:${versions.supportLib}"

    implementation "com.android.support:design:${versions.supportLib}"

I get the following error

Error:(32, 0) Could not get unknown property 'versions' for object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
Open File

My entire grade file is as follows

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.sagar.sicklab"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support:support-v4:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'

    implementation("com.mikepenz:materialdrawer:6.0.1@aar") {
        transitive = true
    }

    implementation "com.android.support:appcompat-v7:${versions.supportLib}"

    implementation "com.android.support:recyclerview-v7:${versions.supportLib}"

    implementation "com.android.support:support-annotations:${versions.supportLib}"

    implementation "com.android.support:design:${versions.supportLib}"

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support:support-v4:26.+'
    compile 'com.android.support:design:26.+'
    compile 'com.google.android.gms:play-services-ads:11.0.1'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'

    compile 'com.github.apl-devs:appintro:v4.2.2'
    compile 'eu.long1:spacetablayout:1.0.4'

}

Body:
Just add in your file:

ext {
    supportLibraryVersion = "25.3.1"
}

And replace:

compile "com.android.support:appcompat-v7:$supportLibraryVersion"
compile "com.android.support:support-v4:$supportLibraryVersion"
compile "com.android.support:cardview-v7:$supportLibraryVersion"
compile "com.android.support:recyclerview-v7:$supportLibraryVersion"
compile "com.android.support:design:$supportLibraryVersion"


问:
SQL - select muliple rows if search criteria matches one of the Values
Apologies if already asked but not too sure what to search for. I want to select muliple LocaleIds if search criterial matches one of the Values.

Currently I am doing simple search like this:

```<code>SELECT *
   FROM [dbo].[Localizations]
   WHERE Value like 'task switching' OR ResourceId like 'task switching'
   ORDER BY LocaleId, ResourceId
</code>```

This results in:

```<code>Id      ResourceId                      Value            LocaleId
53591   AssessmentType_Description_21   Task Switching
53247   Attribute_Description_1         Task Switching
53378   Attribute_Description_132       Task Switching
</code>```

However this is missing the associated rows for the Other LocaleIds (English LocaleId is blank ' '). For example, I require:

```<code>Id      ResourceId                      Value                  LocaleId
53591   AssessmentType_Description_21   Task Switching
53247   Attribute_Description_1         Task Switching
53378   Attribute_Description_132       Task Switching
42257   AssessmentType_Description_21   Aufgabenwechsel         de
42839   Attribute_Description_1         Aufgabenwechsel         de
42876   Attribute_Description_132       Aufgabenwechsel         de
45864   AssessmentType_Description_21   Changement de tâches    fr
46446   Attribute_Description_1         Changement de tâches    fr
46483   Attribute_Description_132       Changement de tâches    fr
</code>```

How can I get the full results set for all LocaleIds? Any help appreciated.

Edit:
Sorry I want all the records that match 'Task switching' and their corresponding values in other languages. Will only ever be searching in 1 language.

答:
Use AND to combine multiple operators.

```<code>SELECT *
FROM [dbo].[Localizations]
WHERE Value like 'task switching'
AND Value like 'aufgabenwechsel'
AND Value like 'changement de tâches'
ORDER BY LocaleId, ResourceId
</code>```

Keep in mind that special characters like 'â' sometimes aren't accepted in your SQL statements, therefore I would suggest you look into  Database normalization.

Body:
Apologies if already asked but not too sure what to search for. I want to select muliple LocaleIds if search criterial matches one of the Values.

Currently I am doing simple search like this:

SELECT *
   FROM [dbo].[Localizations]
   WHERE Value like 'task switching' OR ResourceId like 'task switching'
   ORDER BY LocaleId, ResourceId

This results in:

Id      ResourceId                      Value            LocaleId
53591   AssessmentType_Description_21   Task Switching
53247   Attribute_Description_1         Task Switching
53378   Attribute_Description_132       Task Switching

However this is missing the associated rows for the Other LocaleIds (English LocaleId is blank ' '). For example, I require:

Id      ResourceId                      Value                  LocaleId
53591   AssessmentType_Description_21   Task Switching
53247   Attribute_Description_1         Task Switching
53378   Attribute_Description_132       Task Switching
42257   AssessmentType_Description_21   Aufgabenwechsel         de
42839   Attribute_Description_1         Aufgabenwechsel         de
42876   Attribute_Description_132       Aufgabenwechsel         de
45864   AssessmentType_Description_21   Changement de tâches    fr
46446   Attribute_Description_1         Changement de tâches    fr
46483   Attribute_Description_132       Changement de tâches    fr

How can I get the full results set for all LocaleIds? Any help appreciated.

Edit:
Sorry I want all the records that match 'Task switching' and their corresponding values in other languages. Will only ever be searching in 1 language.

Body:
Use AND to combine multiple operators.

SELECT *
FROM [dbo].[Localizations]
WHERE Value like 'task switching'
AND Value like 'aufgabenwechsel'
AND Value like 'changement de tâches'
ORDER BY LocaleId, ResourceId

Keep in mind that special characters like 'â' sometimes aren't accepted in your SQL statements, therefore I would suggest you look into  Database normalization.


问:
using postgreSQL and jsondb in the same web app
My site is written in ruby (rails) and it's very easy to persist the results of an offsite json feed with using jsondb, so I have an app that would benefit from this, but I think I'd like to keep the rest of the site running on postgrs

Would I be better off moving everything to one database (jsondb?) or does rails easily allow me to use multiple ORM's in the same app

```<code># just notes, ignore if you like cos the answers are subjective
# Perhaps I should build two web apps?
</code>```

答:
It's really better to have only one database. If it's better to use postGresql use it or only jsondb.

Having more than one database can be complicated to understand where is really your data.

OwnerDisplayName: stephenmurdoch

Body:
My site is written in ruby (rails) and it's very easy to persist the results of an offsite json feed with using jsondb, so I have an app that would benefit from this, but I think I'd like to keep the rest of the site running on postgrs

Would I be better off moving everything to one database (jsondb?) or does rails easily allow me to use multiple ORM's in the same app

# just notes, ignore if you like cos the answers are subjective
# Perhaps I should build two web apps?

OwnerDisplayName: shingara


问:
Creating new column based on row values of multiple data subsetting conditions
I have a dataframe that looks more or less like follows (the original one has 12 years of data):

```<code>   Year   Quarter   Age_1   Age_2   Age_3   Age_4
   2005      1       158     120     665     32
   2005      2       257     145     121     14
   2005      3       68       69     336     65
   2005      4       112     458     370     101
   2006      1       75      457     741     26
   2006      2       365     134     223     45
   2006      3       257     121     654     341
   2006      4       175     124     454     12
   2007      1       697     554     217     47
   2007      2       954     987     118     54
   2007      4       498     235     112     65
</code>```

Where the numbers in the age columns represents the amount of individuals in each age class for a specific quarter within a specific year. It is noteworthy that sometimes not all quarters in a specific year have data (e.g., third quarter is not represented in 2007). Also, each row represents a sampling event. Although not shown in this example, in the original dataset I always have more than one sampling event for a specific quarter within a specific year. For example, for the first quarter in 2005 I have 47 sampling events, leading therefore to 47 rows.

What I´d like to have now is a dataframe structured in a way like:

```<code>       Year   Quarter   Age_1   Age_2   Age_3   Age_4    Cohort
       2005      1       158     120     665     32        158
       2005      2       257     145     121     14        257
       2005      3       68       69     336     65         68
       2005      4       112     458     370     101       112
       2006      1       75      457     741     26        457
       2006      2       365     134     223     45        134
       2006      3       257     121     654     341       121
       2006      4       175     124     454     12        124
       2007      1       697     554     217     47         47
       2007      2       954     987     118     54         54
       2007      4       498     235     112     65         65
</code>```

In this case, I want to create a new column (Cohort) in my original dataset which basically follows my cohorts along my dataset. In other words, when I´m in my first year of data (2005 with all quarters), I take the row values of Age_1 and paste it into the new column. When I move to the next year (2006), then I take all my row values related to my Age_2 and paste it to the new column, and so on and so forth.

I have tried to use the following function, but somehow it only works for the first couple of years:

```<code>extract_cohort_quarter <- function(d, yearclass=2005, quarterclass=1) {

 ny <- 1:nlevels(d$Year) #no. of Year levels in the dataset
 nq <- 1:nlevels(d$Quarter)
 age0 <- (paste("age", ny, sep="_"))
 year0 <- as.character(yearclass + ny - 1)

quarter <- as.character(rep(1:4, length(age0)))
age <- rep(age0,each=4)
year <- rep(year0,each=4)

df <- data.frame(year,age,quarter,stringsAsFactors=FALSE)

n <- nrow(df)
dnew <- NULL
for(i in 1:n) {
    tmp <- subset(d, Year==df$year[i] & Quarter==df$quarter[i])
    tmp$Cohort <- tmp[[age[i]]]
    dnew <- rbind(dnew, tmp)
}
levels(dnew$Year) <- paste("Yearclass_", yearclass, ":",
year,":",quarter,":", age, sep="")
dnew
}
</code>```

I have plenty of data from age_1 to age_12 for all the years and quarters, so I don´t think that it´s something related to the data structure itself.

Is there an easier solution to solve this problem? Or is there a way to improve my extract_cohort_quarter() function? Any help will be much appreciated.

-M

Body:
I have a dataframe that looks more or less like follows (the original one has 12 years of data):

   Year   Quarter   Age_1   Age_2   Age_3   Age_4
   2005      1       158     120     665     32
   2005      2       257     145     121     14
   2005      3       68       69     336     65
   2005      4       112     458     370     101
   2006      1       75      457     741     26
   2006      2       365     134     223     45
   2006      3       257     121     654     341
   2006      4       175     124     454     12
   2007      1       697     554     217     47
   2007      2       954     987     118     54
   2007      4       498     235     112     65

Where the numbers in the age columns represents the amount of individuals in each age class for a specific quarter within a specific year. It is noteworthy that sometimes not all quarters in a specific year have data (e.g., third quarter is not represented in 2007). Also, each row represents a sampling event. Although not shown in this example, in the original dataset I always have more than one sampling event for a specific quarter within a specific year. For example, for the first quarter in 2005 I have 47 sampling events, leading therefore to 47 rows.

What I´d like to have now is a dataframe structured in a way like:

       Year   Quarter   Age_1   Age_2   Age_3   Age_4    Cohort
       2005      1       158     120     665     32        158
       2005      2       257     145     121     14        257
       2005      3       68       69     336     65         68
       2005      4       112     458     370     101       112
       2006      1       75      457     741     26        457
       2006      2       365     134     223     45        134
       2006      3       257     121     654     341       121
       2006      4       175     124     454     12        124
       2007      1       697     554     217     47         47
       2007      2       954     987     118     54         54
       2007      4       498     235     112     65         65

In this case, I want to create a new column (Cohort) in my original dataset which basically follows my cohorts along my dataset. In other words, when I´m in my first year of data (2005 with all quarters), I take the row values of Age_1 and paste it into the new column. When I move to the next year (2006), then I take all my row values related to my Age_2 and paste it to the new column, and so on and so forth.

I have tried to use the following function, but somehow it only works for the first couple of years:

extract_cohort_quarter <- function(d, yearclass=2005, quarterclass=1) {

 ny <- 1:nlevels(d$Year) #no. of Year levels in the dataset
 nq <- 1:nlevels(d$Quarter)
 age0 <- (paste("age", ny, sep="_"))
 year0 <- as.character(yearclass + ny - 1)

quarter <- as.character(rep(1:4, length(age0)))
age <- rep(age0,each=4)
year <- rep(year0,each=4)

df <- data.frame(year,age,quarter,stringsAsFactors=FALSE)

n <- nrow(df)
dnew <- NULL
for(i in 1:n) {
    tmp <- subset(d, Year==df$year[i] & Quarter==df$quarter[i])
    tmp$Cohort <- tmp[[age[i]]]
    dnew <- rbind(dnew, tmp)
}
levels(dnew$Year) <- paste("Yearclass_", yearclass, ":",
year,":",quarter,":", age, sep="")
dnew
}

I have plenty of data from age_1 to age_12 for all the years and quarters, so I don´t think that it´s something related to the data structure itself.

Is there an easier solution to solve this problem? Or is there a way to improve my extract_cohort_quarter() function? Any help will be much appreciated.

-M

Body:
I have a simple solution but that demands  bit of knowledge of the data.table library. I think you can easily adapt it to your further needs.
Here is the data:

DT <- as.data.table(list(Year   = c(2005,   2005,   2005,   2005,   2006,   2006    ,2006   ,2006,  2007,   2007,   2007),
                         Quarter= c(1,  2,  3,  4   ,1  ,2  ,3  ,4  ,1  ,2  ,4),
                         Age_1  = c(158,    257,    68, 112 ,75,    365,    257,    175,    697 ,954,   498),
                         Age_2= c(120   ,145    ,69 ,458    ,457,   134 ,121    ,124    ,554    ,987,   235),
                         Age_3= c(665   ,121    ,336    ,370    ,741    ,223    ,654    ,454,217,118,112),
                         Age_4= c(32,14,65,101,26,45,341,12,47,54,65)

))

Here is th code :

DT[,index := .GRP, by = Year]
DT[,cohort := get(paste0("Age_",index)),by = Year]

and the output:

> DT
    Year Quarter Age_1 Age_2 Age_3 Age_4 index cohort
 1: 2005       1   158   120   665    32     1    158
 2: 2005       2   257   145   121    14     1    257
 3: 2005       3    68    69   336    65     1     68
 4: 2005       4   112   458   370   101     1    112
 5: 2006       1    75   457   741    26     2    457
 6: 2006       2   365   134   223    45     2    134
 7: 2006       3   257   121   654   341     2    121
 8: 2006       4   175   124   454    12     2    124
 9: 2007       1   697   554   217    47     3    217
10: 2007       2   954   987   118    54     3    118
11: 2007       4   498   235   112    65     3    112

What it does:

DT[,index := .GRP, by = Year]

creates an index for all different year in your table (by = Year makes an operation for group of year, .GRP create an index following the grouping sequence).
I use it to call the column that you named Age_ with the number created

DT[,cohort := get(paste0("Age_",index)),by = Year]

You can even do everything in the single line

DT[,cohort := get(paste0("Age_",.GRP)),by = Year]

I hope it helps


问:
Find user ID from comment on a post in Facebook Page?
https://developers.facebook.com/docs/graph-api/reference/v2.11/comment

In this, there is no field to find the user who is made the comment. However, this is publicily available on facebook but graph API doesn't allow it.

For example, if get the comment id 124125235235_124242353254, there what can I do to find the user who commented it?

graph.facebook.com/5550296508_10157585378836509?fields=comments&access_token=XXX

答:
Starting from Graph API v2.11, you need a page access token to get the (scoped) user_id from any endpoint (comments and reactions, for a start).

(See v2.11 90 Days Breaking Changes)

/page/* — User information will not be included in GET responses for
  any objects owned by (on) a Page unless the request is made with a
  Page access token. This affects all nodes and edges that return data
  for objects owned by a Page.

This is already happening to API calls made with 2.11 prefix. E.G.

```<code>https://graph.facebook.com/v2.11/5550296508_10157585378836509?fields=comments&access_token=XXX
</code>```

You can still go to the Graph API Explorer and taylor your request to be made against an older endpoint or build your own request as

```<code>https://graph.facebook.com/v2.10/5550296508_10157585378836509?fields=comments&access_token=XXX
</code>```

However, IIRC, 90 Days Breaking Changes means that in 90 days this policy will affect all API versions, so older apps will no longer return the user ids.

How do you get a page token?

In the Graph API Explorer you can generate tokens for the pages you have access to.

And to get access to a page, you need to be authorized by a page admin. He can authorize you by going to his page, then click on
 settings -> page roles.

I guess you need the least privilege to actually get scoped user_ids.

Body:
Starting from Graph API v2.11, you need a page access token to get the (scoped) user_id from any endpoint (comments and reactions, for a start).

(See v2.11 90 Days Breaking Changes)

/page/* — User information will not be included in GET responses for
  any objects owned by (on) a Page unless the request is made with a
  Page access token. This affects all nodes and edges that return data
  for objects owned by a Page.

This is already happening to API calls made with 2.11 prefix. E.G.

https://graph.facebook.com/v2.11/5550296508_10157585378836509?fields=comments&access_token=XXX

You can still go to the Graph API Explorer and taylor your request to be made against an older endpoint or build your own request as

https://graph.facebook.com/v2.10/5550296508_10157585378836509?fields=comments&access_token=XXX

However, IIRC, 90 Days Breaking Changes means that in 90 days this policy will affect all API versions, so older apps will no longer return the user ids.

How do you get a page token?

In the Graph API Explorer you can generate tokens for the pages you have access to.

And to get access to a page, you need to be authorized by a page admin. He can authorize you by going to his page, then click on
 settings -> page roles.

I guess you need the least privilege to actually get scoped user_ids.


问:
Ubuntu 16 doesn't recognize ng commands

The program 'ng' is currently not installed. You can install it by
  typing: sudo apt install ng-common

I got no erros during installation, how can i fix this?

Edit: this happens when i try to run ng new PROJECT_NAME

答:
I had the same problem because I downloaded and installed nodejs from the tar.gz package. I did the following to solve the problem:

Deleted the nodejs folder (mine was in Downloads)

Deleted npm and node from my path by removing then from ~/.profile

Install nvm as explained here

Install npm using sudo apt install npm. then upgrae using npm install -g npm@latest

Updgrade node to lates using nvm install --lts

Run npm install -g @angular/cli.

This should fix the problem. If you are still unable to use ng, then check your environmental variables to make sure it has been correctly set.

Title: Ubuntu 16 doesn't recognize ng commands


问:
How do list command on one ssh command?
I try connect with ssh2 and run script in one line command.

/usr/bin/ssh2 --password ${password} -l root ${address} cd ${dir} ;
  python script.py

But directory isn't changed. Why ? I want write with two command.
It does only first command (cd)

答:
Hello you should use && instead of ; and put command in "
example:

/usr/bin/ssh2 --password ${password} -l root ${address} "cd ${dir} && python script.py"

Title: How do list command on one ssh command?


问:
Angular, how to switch between production and development environments?
I have a big Angular application which is still needed in development, but already ready for use in production, I want to be switch between the states with simple change of

```<code>isProduction: boolean = false
</code>```

to true,
I did it by making apiHelperService which is just usual service, it works fine for most application:

```<code>import {Injectable} from "@angular/core";
import {Response, Http, Headers, RequestOptions} from "@angular/http";
import {Observable} from "rxjs/Observable";

@Injectable()
export class ApiHelperService {
  productionURL: string = 'http://35.203.121.40';
  developmentURL: string = 'http://10.25.37.523';
  serverUrl: string;
  apiPort: string = ':3000/';
  socketPort: string = ':2000/';
  isProductionMode: boolean = false;

  constructor() {
    this.serverUrl = this.isProductionMode ? this.productionURL : this.developmentURL;
  }

  getApiURL(): string {
    return this.serverUrl + this.apiPort;
  }

  getSocketUrl(): string {
    return this.serverUrl + this.socketPort;
  }
  getApiIp(): string {
    const serverIp = this.isProductionMode ? this.productionURL.split(':')[0] : this.developmentURL.split(':')[0];
    console.log('string url is:', serverIp);
    return serverIp;

  }
  serialize(obj) {
    var str = [];
    for (var p in obj) {
      if (obj.hasOwnProperty(p) && ((obj[p] != null && obj[p] != '') || (typeof obj[p] == "boolean"))) {
        if (obj[p].length == 0) {
          continue;
        }
        else if (obj[p].length > 1 && typeof obj[p] == 'object') { // reformats arrays
          for (let i = 0; i < obj[p].length; i++) {
            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p][i]));
          }
        }
        else {
          str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        }
      }
    }

    return '?' + str.join("&");
  }

  extractData(res: Response) {
    let body = res.json();
    // console.log("body", body)
    return body || {};
  }

  handleError(error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }

}
</code>```

BUT i have socket library that configures the socket URL in the

app.module.ts

so when I try to use dynamic URL(in the app.module.ts) like this:

```<code>const apiHelper = new ApiHelperService(); //fails here
const url: string = apiHelper.getSocketUrl();
const config: SocketIoConfig = { url: url, options: {
  "force new connection" : true,
  "reconnectionAttempts": "Infinity",
  "timeout" : 10000,
  "transports" : ["websocket"]} };
</code>```

it fails with this error:

```<code>ERROR in Error: Error encountered resolving symbol values statically. Calling
function 'ApiHelperService', function calls are not supported. Consider replacing the function or lambda with a
reference to an exported function, resolving symbol AppModule
</code>```

so my question is, is my approach wrong?
what is the right approach to handle this problem?

答:
it works in different way: alligator.io/angular/environment-variables

you must specify variables in environment.ts and environment.prod.ts

then import {environment} from '../../environments/environment';
environment object will contain proper variables

Body:
I have a big Angular application which is still needed in development, but already ready for use in production, I want to be switch between the states with simple change of

isProduction: boolean = false

to true,
I did it by making apiHelperService which is just usual service, it works fine for most application:

import {Injectable} from "@angular/core";
import {Response, Http, Headers, RequestOptions} from "@angular/http";
import {Observable} from "rxjs/Observable";

@Injectable()
export class ApiHelperService {
  productionURL: string = 'http://35.203.121.40';
  developmentURL: string = 'http://10.25.37.523';
  serverUrl: string;
  apiPort: string = ':3000/';
  socketPort: string = ':2000/';
  isProductionMode: boolean = false;

  constructor() {
    this.serverUrl = this.isProductionMode ? this.productionURL : this.developmentURL;
  }

  getApiURL(): string {
    return this.serverUrl + this.apiPort;
  }

  getSocketUrl(): string {
    return this.serverUrl + this.socketPort;
  }
  getApiIp(): string {
    const serverIp = this.isProductionMode ? this.productionURL.split(':')[0] : this.developmentURL.split(':')[0];
    console.log('string url is:', serverIp);
    return serverIp;

  }
  serialize(obj) {
    var str = [];
    for (var p in obj) {
      if (obj.hasOwnProperty(p) && ((obj[p] != null && obj[p] != '') || (typeof obj[p] == "boolean"))) {
        if (obj[p].length == 0) {
          continue;
        }
        else if (obj[p].length > 1 && typeof obj[p] == 'object') { // reformats arrays
          for (let i = 0; i < obj[p].length; i++) {
            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p][i]));
          }
        }
        else {
          str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        }
      }
    }

    return '?' + str.join("&");
  }

  extractData(res: Response) {
    let body = res.json();
    // console.log("body", body)
    return body || {};
  }

  handleError(error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }

}

BUT i have socket library that configures the socket URL in the

app.module.ts

so when I try to use dynamic URL(in the app.module.ts) like this:

const apiHelper = new ApiHelperService(); //fails here
const url: string = apiHelper.getSocketUrl();
const config: SocketIoConfig = { url: url, options: {
  "force new connection" : true,
  "reconnectionAttempts": "Infinity",
  "timeout" : 10000,
  "transports" : ["websocket"]} };

it fails with this error:

ERROR in Error: Error encountered resolving symbol values statically. Calling
function 'ApiHelperService', function calls are not supported. Consider replacing the function or lambda with a
reference to an exported function, resolving symbol AppModule

so my question is, is my approach wrong?
what is the right approach to handle this problem?


问:
Python: split a dict in a list
I want to convert a simple dict like so: d = {0:0, 1:1, 2:2, 3:3} to a list of dict with the same amount of elements in each of them (or so) as this one: [{0:0, 2:2}, {1:1, 3:3}]. I've tried with simple indexing like I use with lists but it throws me a TypeError: unhashable type: 'slice'. Here what i have right now:

```<code>def dico_chunks(dico, n):
    if len(dico) < n:
        n = len(dico)
    return [dico[i::n] for i in range(n)]
</code>```

Keep in mind that i don't need the list to be order in anyway. I just need to have my main dict splited in a list of n sub-dicts.

答:
Generator based approach:

```<code>def chunk_dict(d, chunk_size):
    r = {}
    for k, v in d.items():
        if len(r) == chunk_size:
            yield r
            r = {}
        r[k] = v
    if r:
        yield r

d = {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}
list(chunk_dict(d, 2))
# [{1: 1, 2: 2}, {3: 3, 4: 4}, {5: 5, 6: 6}]
</code>```

A shorter and more performant version of the same functionality (using itertools.islice)
can be found in this answer.

For a given number of as evenly as possible distributed chunks (e.g. sizes 4, 4, 3, 3 instead of 4, 4, 4, 2), you can do:

```<code>chunks = [{} for _ in range(num_chunks)]
for i, k in enumerate(d):
    chunks[i % num_chunks][k] = d[v]
</code>```

Title: Python: split a dict in a list

Body:
I want to convert a simple dict like so: d = {0:0, 1:1, 2:2, 3:3} to a list of dict with the same amount of elements in each of them (or so) as this one: [{0:0, 2:2}, {1:1, 3:3}]. I've tried with simple indexing like I use with lists but it throws me a TypeError: unhashable type: 'slice'. Here what i have right now:

def dico_chunks(dico, n):
    if len(dico) < n:
        n = len(dico)
    return [dico[i::n] for i in range(n)]

Keep in mind that i don't need the list to be order in anyway. I just need to have my main dict splited in a list of n sub-dicts.

Body:
Generator based approach:

def chunk_dict(d, chunk_size):
    r = {}
    for k, v in d.items():
        if len(r) == chunk_size:
            yield r
            r = {}
        r[k] = v
    if r:
        yield r

d = {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}
list(chunk_dict(d, 2))
# [{1: 1, 2: 2}, {3: 3, 4: 4}, {5: 5, 6: 6}]

A shorter and more performant version of the same functionality (using itertools.islice)
can be found in this answer.

For a given number of as evenly as possible distributed chunks (e.g. sizes 4, 4, 3, 3 instead of 4, 4, 4, 2), you can do:

chunks = [{} for _ in range(num_chunks)]
for i, k in enumerate(d):
    chunks[i % num_chunks][k] = d[v]


问:
Launch APK Installer Oreo
I have had this code working for some time now but with Android Orea it doesn't work.

```<code>        Context context = mContextRef.get();

        if (context == null) {
            return;
        }

        // Get the update
        String filepath = getDownloadLocation();
        File apkFile = new File(filepath);

        Uri fileLoc;
        Intent intent;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
            fileLoc = android.support.v4.content.FileProvider.getUriForFile(context, mFileProviderAuthority, apkFile);
        } else {
            intent = new Intent(Intent.ACTION_VIEW);
            fileLoc = Uri.fromFile(apkFile);
        }

        intent.setDataAndType(fileLoc, "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        context.startActivity(intent);
</code>```

This code works with all version of android except 8.0 and above.

Edit

Sorry for not explaining more. IT doesn't work meaning, it flashes a window for a fraction of a second and disappears (some times imperceptibly) and continues on in the old app. The file is successfully downloaded (I can navigate to it and install) but when I try to start the activity to install it programmatically it fails with no errors or logs at all.

答:
Apparently if your app targets later versions of android the android.permission.REQUEST_INSTALL_PACKAGES permission is required in the manifest otherwise nothing happens except a single line error in the LogCat.

So include the following in manifest.xml file:

<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>

Manifest API for REQUEST_INSTALL_PACKAGES

Title: Launch APK Installer Oreo

Body:
I have had this code working for some time now but with Android Orea it doesn't work.

        Context context = mContextRef.get();

        if (context == null) {
            return;
        }

        // Get the update
        String filepath = getDownloadLocation();
        File apkFile = new File(filepath);

        Uri fileLoc;
        Intent intent;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
            fileLoc = android.support.v4.content.FileProvider.getUriForFile(context, mFileProviderAuthority, apkFile);
        } else {
            intent = new Intent(Intent.ACTION_VIEW);
            fileLoc = Uri.fromFile(apkFile);
        }

        intent.setDataAndType(fileLoc, "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        context.startActivity(intent);

This code works with all version of android except 8.0 and above.

Edit

Sorry for not explaining more. IT doesn't work meaning, it flashes a window for a fraction of a second and disappears (some times imperceptibly) and continues on in the old app. The file is successfully downloaded (I can navigate to it and install) but when I try to start the activity to install it programmatically it fails with no errors or logs at all.


问:
Error with map and string conversion in c++
I'm familiar with Python's dictionary function, and I'm assuming based on my research that C++'s map function is relatively similar. However I'm running into a "conversion" issue: </p>

```<code>std::string dictionary(std::string inquiry){
    std::map<std::string, std::string> mapK;
        mapK["12th st. Oakland City Center"]="12th";
        mapK["16th st. Mission"]="16th";

    return mapK.find(inquiry);
}
</code>```

<p>This is a string function that should receive a string and then with the corresponding key return a string back to the main. Evidently there's an issue with the return statement. </p>

```<code>error: could not convert 'mapK.std::map<_Key, _Tp, _Compare, _Alloc>::find<std::basic_string<char>, std::basic_string<char>, std::less<std::basic_string<char> >, std::allocator<std::pair<const std::basic_string<char>, std::basic_string<char> > > >((*(const key_type*)(& inquiry)))' from 'std::map<std::basic_string<char>, std::basic_string<char> >::iterator {aka std::_Rb_tree_iterator<std::pair<const std::basic_string<char>, std::basic_string<char> > >}' to 'std::string {aka std::basic_string<char>}'
  return mapK.find(inquiry);
</code>```

答:
std::map::find() returns iterator, specifically std::map::iterator.

The only thing you need to fix is to put a dereference:

```<code>return *mapK.find(inquiry);
</code>```

Or even better, just use operator[]:

```<code>return mapK[inquiry];
</code>```

Do note though that if inquiry is not in the map, it will return empty string. In case of find, it is straight undefined behavior.

Body:
I'm familiar with Python's dictionary function, and I'm assuming based on my research that C++'s map function is relatively similar. However I'm running into a "conversion" issue:

std::string dictionary(std::string inquiry){
    std::map<std::string, std::string> mapK;
        mapK["12th st. Oakland City Center"]="12th";
        mapK["16th st. Mission"]="16th";

    return mapK.find(inquiry);
}

This is a string function that should receive a string and then with the corresponding key return a string back to the main. Evidently there's an issue with the return statement.

error: could not convert 'mapK.std::map<_Key, _Tp, _Compare, _Alloc>::find<std::basic_string<char>, std::basic_string<char>, std::less<std::basic_string<char> >, std::allocator<std::pair<const std::basic_string<char>, std::basic_string<char> > > >((*(const key_type*)(& inquiry)))' from 'std::map<std::basic_string<char>, std::basic_string<char> >::iterator {aka std::_Rb_tree_iterator<std::pair<const std::basic_string<char>, std::basic_string<char> > >}' to 'std::string {aka std::basic_string<char>}'
  return mapK.find(inquiry);

Body:
std::map::find() returns iterator, specifically std::map::iterator.

The only thing you need to fix is to put a dereference:

return *mapK.find(inquiry);

Or even better, just use operator[]:

return mapK[inquiry];

Do note though that if inquiry is not in the map, it will return empty string. In case of find, it is straight undefined behavior.