问:
Does an object of a subclass also allocate an object of the parent class?
```<code>Class A
{
    int X {get;set;}
}
Class B : A
{
    int Y {get;set;}
}

B myB;
</code>```

Say for the sake of argument that an object of type A is 4 bytes and an object of type B is 4 bytes.

B is allocated/initialized/constructed and its contents are stored on the heap.

Is the size of B 8 bytes with the pointers of both X and Y in tandem, or is it two objects of 4 bytes each?

Is it still resulting in two objects like the following situation?

```<code>Class A {}
Class B
{
    A myA;
}

B myB;
</code>```

Can I presume, if these situations result in different data, that inheritance uses less heap allocation than construction due to the additional contained object having its data allocated -- and that the heap allocates this data outside its containing object?

Can I conclude that construction is much less memory efficient than inheritance?

Clarification:
When initializing an object of subclass type, are the bytes of that object's parent class's properties stored alongside the bytes of the subclass's properties? Does B store a pointer to A or does it directly store the properties of A? If it stores a pointer to an instance of A, that would make it the same in memory as if it had a property of type A instead.

Addition:
It was said that the data of B contains the data of A also in the first example. Are there two allocations or one allocation when allocating the memory of a subclassed object?

In the second example, you're allocating memory twice: once for the contained property object of type A and once again for the object class B, so I'm presuming that you have two distinct memory allocations and two distinct objects with a pointer to A inside B.

If a subclass only allocates memory once for the entire size of all its properties and all its inherited properties, and stores all that information inline, then wouldn't that make it a superior memory allocation approach than allocating multiple objects for one object?

答:
When initializing an object of subclass type, are the bytes of that object's parent class's properties stored alongside the bytes of the subclass's properties?

Yes, probably.  C# itself doesn't specify much (if anything; I'm not super familiar with the spec) about the memory model.  I'm fairly certain that's implementation-defined.  However, an instance of Derived containing a reference to an entirely independent instance of its Base doesn't make sense for a couple reasons:

If Base is abstract the memory model then not just allows for but actually requires the creation of an instance of an abstract class.

At the IL level managed pointers (the actual references) to Derived can be dropped in anywhere a managed pointer to Base is expected.  Now, we can rule out the runtime performing some kind of conversion (e.g. referencing that Base instance) because that would lose the RTTI.  But we know that we can cast that Base reference to a Derived instance at runtime, so it must not be modifying the pointer.

This would introduce a wrinkle when trying to access and modify fields of Base through an instance of Derived, however.  In that case the CLR would have to tack on field information to the instance v-table.  Certainly not impossible, but at that point CLR implementors would just be going out of their way to make things more difficult for themselves.  And as far as I can see there'd be no real benefit to doing things this way (unless you wanted to be able to change the inheritance hierarchy at runtime, which neither C# nor the CLR allow).

It would also incur a lot of rather pointless performance penalties by adding another layer of indirection that could have been avoided by just including the fields of Base directly in an instance of Derived.

Body:
Class A
{
    int X {get;set;}
}
Class B : A
{
    int Y {get;set;}
}

B myB;

Say for the sake of argument that an object of type A is 4 bytes and an object of type B is 4 bytes.

B is allocated/initialized/constructed and its contents are stored on the heap.

Is the size of B 8 bytes with the pointers of both X and Y in tandem, or is it two objects of 4 bytes each?

Is it still resulting in two objects like the following situation?

Class A {}
Class B
{
    A myA;
}

B myB;

Can I presume, if these situations result in different data, that inheritance uses less heap allocation than construction due to the additional contained object having its data allocated -- and that the heap allocates this data outside its containing object?

Can I conclude that construction is much less memory efficient than inheritance?

Clarification:
When initializing an object of subclass type, are the bytes of that object's parent class's properties stored alongside the bytes of the subclass's properties? Does B store a pointer to A or does it directly store the properties of A? If it stores a pointer to an instance of A, that would make it the same in memory as if it had a property of type A instead.

Addition:
It was said that the data of B contains the data of A also in the first example. Are there two allocations or one allocation when allocating the memory of a subclassed object?

In the second example, you're allocating memory twice: once for the contained property object of type A and once again for the object class B, so I'm presuming that you have two distinct memory allocations and two distinct objects with a pointer to A inside B.

If a subclass only allocates memory once for the entire size of all its properties and all its inherited properties, and stores all that information inline, then wouldn't that make it a superior memory allocation approach than allocating multiple objects for one object?


来源: stackexchange

问:
SQL A simple way to select items from the larger category
I have a table with items that can be grouped into two categories. How do I select items from the larger category? For example, if my table looks like

```<code>| ItemID | ItemProperty |
|  1     |     true     |
|  2     |     true     |
|  3     |    false     |
|  4     |    false     |
|  5     |    false     |
|  6     |     true     |
|  7     |     true     |
</code>```

then the result should look like

```<code>| ItemID |
|  1     |
|  2     |
|  6     |
|  7     |
</code>```

This feels like something very simple, and yet I haven't been able to find the answer.

答:
Hmmmm.  Something like this:</p>

```<code>select t.ItemId
from t join
     (select ItemProperty
      from t
      group by ItemProperty
      order by count(*) desc
      limit 1
     ) tt
     on t.ItemProperty = tt.ItemProperty;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a table with items that can be grouped into two categories. How do I select items from the larger category? For example, if my table looks like

| ItemID | ItemProperty |
|  1     |     true     |
|  2     |     true     |
|  3     |    false     |
|  4     |    false     |
|  5     |    false     |
|  6     |     true     |
|  7     |     true     |

then the result should look like

| ItemID |
|  1     |
|  2     |
|  6     |
|  7     |

This feels like something very simple, and yet I haven't been able to find the answer.

Body:
Hmmmm.  Something like this:

select t.ItemId
from t join
     (select ItemProperty
      from t
      group by ItemProperty
      order by count(*) desc
      limit 1
     ) tt
     on t.ItemProperty = tt.ItemProperty;


问:
Caused by: org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name
When I try to start the tomcat server I got the following error in Server console. kindly let me know the issue cause.

```<code>Caused by: org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name [org.hibernate.dialect.OracleDialect ] as strategy [org.hibernate.dialect.Dialect]
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.selectStrategyImplementor(StrategySelectorImpl.java:128)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveDefaultableStrategy(StrategySelectorImpl.java:155)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveStrategy(StrategySelectorImpl.java:136)
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.constructDialect(DialectFactoryImpl.java:78)
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:68)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:205)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928)
at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:372)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:454)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:439)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1633)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570) [org.hibernate.dialect.Dialect]
</code>```

答:
Since you errormessage contains that suspicious extra space at the end:

```<code>Unable to resolve name [org.hibernate.dialect.OracleDialect ]
</code>```

I will take a wild guess that you have an extra space at the end of your dialect property.

So look for

```<code>"org.hibernate.dialect.OracleDialect "
</code>```

and change it to:

```<code>"org.hibernate.dialect.OracleDialect"
</code>```

Body:
When I try to start the tomcat server I got the following error in Server console. kindly let me know the issue cause.

Caused by: org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name [org.hibernate.dialect.OracleDialect ] as strategy [org.hibernate.dialect.Dialect]
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.selectStrategyImplementor(StrategySelectorImpl.java:128)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveDefaultableStrategy(StrategySelectorImpl.java:155)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveStrategy(StrategySelectorImpl.java:136)
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.constructDialect(DialectFactoryImpl.java:78)
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:68)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:205)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928)
at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:372)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:454)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:439)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1633)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570) [org.hibernate.dialect.Dialect]

Body:
Since you errormessage contains that suspicious extra space at the end:

Unable to resolve name [org.hibernate.dialect.OracleDialect ]

I will take a wild guess that you have an extra space at the end of your dialect property.

So look for

"org.hibernate.dialect.OracleDialect "

and change it to:

"org.hibernate.dialect.OracleDialect"


问:
When is data freed?
Does Python do any analysis to free memory earlier? For example, if I have:

```<code>d = some big array
# ... use(d) ...

# no d is used from here
# a lot of other code, the code could use more big arrays
</code>```

When does python decide to delete the memory used by d?

If I use d in a function, will d be freed when the function is done?

Maybe in general this is hard, because d can be assigned to others, and they may continue using d after the function is finished.

However, I was looking for some good practice that can keep python use less memory...

答:
You can use in your case del d to dereference the array when you are finished with it, but Python will take care of the memory itself after your program is finished running. I found 2 other questions that are similar and may delve deeper into memory management in python here are the links:

How can I explicitly free memory in Python?

and its answer:

https://stackoverflow.com/a/1316793/6475414

and:

Releasing memory in Python

Title: When is data freed?

Body:
Does Python do any analysis to free memory earlier? For example, if I have:

d = some big array
# ... use(d) ...

# no d is used from here
# a lot of other code, the code could use more big arrays

When does python decide to delete the memory used by d?

If I use d in a function, will d be freed when the function is done?

Maybe in general this is hard, because d can be assigned to others, and they may continue using d after the function is finished.

However, I was looking for some good practice that can keep python use less memory...


问:
Python won't let me use variable inside function
I don't understand why it won't let me use display_w or display_h inside of the function. I can't have it inside the function because I don't want it to reset when I use it again. How can I allow it to use those variables?</p>

```<code>import pygame

pygame.init()

display_w = 800
display_h = 600

white = (255, 255, 255)
black = (0, 0, 0)
grey = (100, 100, 100)

def run():

    print("Input your message: ")
    msg = input()

    print("Enter font size: ")
    font_size = int(input())

    display = pygame.display.set_mode((display_w, display_h))
    pygame.display.set_caption("TextPos")

    text_x = 0
    text_y = 0

    def message_to_screen(msg, color, font_size, x, y):

        font = pygame.font.SysFont(None, font_size)
        screen_text = font.render(msg, True, color)
        display.blit(screen_text, [x, y])
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r:
                    running = False
                    pygame.quit()
                    run()
                if event.key == pygame.K_q:

                    print("Enter display width: ")
                    display_w = int(input())

                    print("Enter display height: ")
                    display_h = int(input())
                    running = False

            message_to_screen(msg, (255, 255, 255), 50, text_x, text_y)
            m_x, m_y = pygame.mouse.get_pos()
            text_x = m_x
            text_y = m_y

            display.fill(white)
            message_to_screen("X: %s" % m_x, black, 30, 10, 10)
            message_to_screen("Y: %s" % m_y, black, 30, 10, 30)
            message_to_screen(msg, black, font_size, text_x, text_y)
            message_to_screen("Press Q to Change Screen Size", grey, 30, display_w - 310, 0)
            message_to_screen("Press R to Restart", grey, 30, display_w - 180, 30)

            pygame.display.update()
run()
</code>```

答:
From https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python:

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

In your case, you are attempting to set variables in your function, so Python treats them as local variables.

To treat them as global variables, use the global keyword when you locally define them to indicate you're referencing, and modifying, the values outside the function scope.

Body:
I don't understand why it won't let me use display_w or display_h inside of the function. I can't have it inside the function because I don't want it to reset when I use it again. How can I allow it to use those variables?

import pygame

pygame.init()

display_w = 800
display_h = 600

white = (255, 255, 255)
black = (0, 0, 0)
grey = (100, 100, 100)

def run():

    print("Input your message: ")
    msg = input()

    print("Enter font size: ")
    font_size = int(input())

    display = pygame.display.set_mode((display_w, display_h))
    pygame.display.set_caption("TextPos")

    text_x = 0
    text_y = 0

    def message_to_screen(msg, color, font_size, x, y):

        font = pygame.font.SysFont(None, font_size)
        screen_text = font.render(msg, True, color)
        display.blit(screen_text, [x, y])
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r:
                    running = False
                    pygame.quit()
                    run()
                if event.key == pygame.K_q:

                    print("Enter display width: ")
                    display_w = int(input())

                    print("Enter display height: ")
                    display_h = int(input())
                    running = False

            message_to_screen(msg, (255, 255, 255), 50, text_x, text_y)
            m_x, m_y = pygame.mouse.get_pos()
            text_x = m_x
            text_y = m_y

            display.fill(white)
            message_to_screen("X: %s" % m_x, black, 30, 10, 10)
            message_to_screen("Y: %s" % m_y, black, 30, 10, 30)
            message_to_screen(msg, black, font_size, text_x, text_y)
            message_to_screen("Press Q to Change Screen Size", grey, 30, display_w - 310, 0)
            message_to_screen("Press R to Restart", grey, 30, display_w - 180, 30)

            pygame.display.update()
run()


问:
ElasticSearch : Can we apply both n-gram and language analyzers during indexing
Thanks a lot @Random , I have modified the mapping as follows. For testing I have used "movie" as my type for indexing.
Note: I have added search_analyzer also. I was not getting proper results without that.
However I have following doubts for using search_analyzer.

1] Can we use custom search_analyzer in case of language analyzers ?

2] am I getting all the results due to n-gram analyzer I have used and not due to english analyzer?

```<code>{
    "settings": {
        "analysis": {
            "analyzer": {
                "english_ngram": {
                    "type": "custom",
                    "filter": [
                        "english_possessive_stemmer",
                        "lowercase",
                        "english_stop",
                        "english_stemmer",
                        "ngram_filter"
                    ],
                    "tokenizer": "whitespace"
                },
                "search_analyzer":{
                    "type": "custom",
                    "tokenizer": "whitespace",
                    "filter": "lowercase"
                }
            },
            "filter": {
                "english_stop": {
                    "type": "stop"
                },
                "english_stemmer": {
                    "type": "stemmer",
                    "language": "english"
                },
                "english_possessive_stemmer": {
                    "type": "stemmer",
                    "language": "possessive_english"
                },
                "ngram_filter": {
                    "type": "ngram",
                    "min_gram": 1,
                    "max_gram": 25
                }
            }
        }
    },
      "mappings": {
    "movie": {
      "properties": {
        "title": {
          "type": "string",
          "fields": {
            "en": {
              "type":     "string",
              "analyzer": "english_ngram",
              "search_analyzer": "search_analyzer"
            }
          }
        }
      }
    }
  }
}
</code>```

Update :

Using search analyzer also is not working consistently.and need more help with this.Updating question with my findings.

I used following mapping as suggested (Note: This mapping does not use search analyzer), for simplicity lets consider only English analyzer.

```<code>{
    "settings": {
        "analysis": {
            "analyzer": {
                "english_ngram": {
                    "type": "custom",
                    "filter": [
                        "english_possessive_stemmer",
                        "lowercase",
                        "english_stop",
                        "english_stemmer",
                        "ngram_filter"
                    ],
                    "tokenizer": "standard"
                }
            },
            "filter": {
                "english_stop": {
                    "type": "stop"
                },
                "english_stemmer": {
                    "type": "stemmer",
                    "language": "english"
                },
                "english_possessive_stemmer": {
                    "type": "stemmer",
                    "language": "possessive_english"
                },
                "ngram_filter": {
                    "type": "edge_ngram",
                    "min_gram": 1,
                    "max_gram": 25
                }
            }
        }
    }
}
</code>```

Created index:

PUT http://localhost:9200/movies/movie/1

```<code>{"title":"$peci@l movie"}
</code>```

Tried following query:

```<code>GET http://localhost:9200/movies/movie/_search

    {
        "query": {
            "multi_match": {
                "query": "$peci mov",
                "fields": ["title"],
                "operator": "and"
            }
            }
        }
    }
</code>```

I got no results for this, am I doing anything wrong ?
I am trying to get results for:

```<code>1] Special characters
2] Partial matches
3] Space separated partial and full words
</code>```

Thanks again !

答:
You can create a custom analyzer based on language analyzers. The only difference is that you add your ngram_filter token filter to the end of the chain. In this case you first get language-stemmed tokens (default chain) that converted to edge ngrams in the end (your filter). You can find the implementation of language analyzers here https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-lang-analyzer.html#english-analyzer in order to override them. Here is an example of this change for english language:

```<code>{
    "settings": {
        "analysis": {
            "analyzer": {
                "english_ngram": {
                    "type": "custom",
                    "filter": [
                        "english_possessive_stemmer",
                        "lowercase",
                        "english_stop",
                        "english_stemmer",
                        "ngram_filter"
                    ],
                    "tokenizer": "standard"
                }
            },
            "filter": {
                "english_stop": {
                    "type": "stop"
                },
                "english_stemmer": {
                    "type": "stemmer",
                    "language": "english"
                },
                "english_possessive_stemmer": {
                    "type": "stemmer",
                    "language": "possessive_english"
                },
                "ngram_filter": {
                    "type": "edge_ngram",
                    "min_gram": 1,
                    "max_gram": 25
                }
            }
        }
    }
}
</code>```

UPDATE

To support special characters you can try to use whitespace tokenizer instead of standard. In this case these characters will be part of your tokens:

```<code>{
    "settings": {
        "analysis": {
            "analyzer": {
                "english_ngram": {
                    "type": "custom",
                    "filter": [
                        "english_possessive_stemmer",
                        "lowercase",
                        "english_stop",
                        "english_stemmer",
                        "ngram_filter"
                    ],
                    "tokenizer": "whitespace"
                }
            },
            "filter": {
                "english_stop": {
                    "type": "stop"
                },
                "english_stemmer": {
                    "type": "stemmer",
                    "language": "english"
                },
                "english_possessive_stemmer": {
                    "type": "stemmer",
                    "language": "possessive_english"
                },
                "ngram_filter": {
                    "type": "edge_ngram",
                    "min_gram": 1,
                    "max_gram": 25
                }
            }
        }
    }
}
</code>```

Body:
Thanks a lot @Random , I have modified the mapping as follows. For testing I have used "movie" as my type for indexing.
Note: I have added search_analyzer also. I was not getting proper results without that.
However I have following doubts for using search_analyzer.

1] Can we use custom search_analyzer in case of language analyzers ?

2] am I getting all the results due to n-gram analyzer I have used and not due to english analyzer?

{
    "settings": {
        "analysis": {
            "analyzer": {
                "english_ngram": {
                    "type": "custom",
                    "filter": [
                        "english_possessive_stemmer",
                        "lowercase",
                        "english_stop",
                        "english_stemmer",
                        "ngram_filter"
                    ],
                    "tokenizer": "whitespace"
                },
                "search_analyzer":{
                    "type": "custom",
                    "tokenizer": "whitespace",
                    "filter": "lowercase"
                }
            },
            "filter": {
                "english_stop": {
                    "type": "stop"
                },
                "english_stemmer": {
                    "type": "stemmer",
                    "language": "english"
                },
                "english_possessive_stemmer": {
                    "type": "stemmer",
                    "language": "possessive_english"
                },
                "ngram_filter": {
                    "type": "ngram",
                    "min_gram": 1,
                    "max_gram": 25
                }
            }
        }
    },
      "mappings": {
    "movie": {
      "properties": {
        "title": {
          "type": "string",
          "fields": {
            "en": {
              "type":     "string",
              "analyzer": "english_ngram",
              "search_analyzer": "search_analyzer"
            }
          }
        }
      }
    }
  }
}

Update :

Using search analyzer also is not working consistently.and need more help with this.Updating question with my findings.

I used following mapping as suggested (Note: This mapping does not use search analyzer), for simplicity lets consider only English analyzer.

{
    "settings": {
        "analysis": {
            "analyzer": {
                "english_ngram": {
                    "type": "custom",
                    "filter": [
                        "english_possessive_stemmer",
                        "lowercase",
                        "english_stop",
                        "english_stemmer",
                        "ngram_filter"
                    ],
                    "tokenizer": "standard"
                }
            },
            "filter": {
                "english_stop": {
                    "type": "stop"
                },
                "english_stemmer": {
                    "type": "stemmer",
                    "language": "english"
                },
                "english_possessive_stemmer": {
                    "type": "stemmer",
                    "language": "possessive_english"
                },
                "ngram_filter": {
                    "type": "edge_ngram",
                    "min_gram": 1,
                    "max_gram": 25
                }
            }
        }
    }
}

Created index:

PUT http://localhost:9200/movies/movie/1

{"title":"$peci@l movie"}

Tried following query:

GET http://localhost:9200/movies/movie/_search

    {
        "query": {
            "multi_match": {
                "query": "$peci mov",
                "fields": ["title"],
                "operator": "and"
            }
            }
        }
    }

I got no results for this, am I doing anything wrong ?
I am trying to get results for:

1] Special characters
2] Partial matches
3] Space separated partial and full words

Thanks again !

Body:
You can create a custom analyzer based on language analyzers. The only difference is that you add your ngram_filter token filter to the end of the chain. In this case you first get language-stemmed tokens (default chain) that converted to edge ngrams in the end (your filter). You can find the implementation of language analyzers here https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-lang-analyzer.html#english-analyzer in order to override them. Here is an example of this change for english language:

{
    "settings": {
        "analysis": {
            "analyzer": {
                "english_ngram": {
                    "type": "custom",
                    "filter": [
                        "english_possessive_stemmer",
                        "lowercase",
                        "english_stop",
                        "english_stemmer",
                        "ngram_filter"
                    ],
                    "tokenizer": "standard"
                }
            },
            "filter": {
                "english_stop": {
                    "type": "stop"
                },
                "english_stemmer": {
                    "type": "stemmer",
                    "language": "english"
                },
                "english_possessive_stemmer": {
                    "type": "stemmer",
                    "language": "possessive_english"
                },
                "ngram_filter": {
                    "type": "edge_ngram",
                    "min_gram": 1,
                    "max_gram": 25
                }
            }
        }
    }
}

UPDATE

To support special characters you can try to use whitespace tokenizer instead of standard. In this case these characters will be part of your tokens:

{
    "settings": {
        "analysis": {
            "analyzer": {
                "english_ngram": {
                    "type": "custom",
                    "filter": [
                        "english_possessive_stemmer",
                        "lowercase",
                        "english_stop",
                        "english_stemmer",
                        "ngram_filter"
                    ],
                    "tokenizer": "whitespace"
                }
            },
            "filter": {
                "english_stop": {
                    "type": "stop"
                },
                "english_stemmer": {
                    "type": "stemmer",
                    "language": "english"
                },
                "english_possessive_stemmer": {
                    "type": "stemmer",
                    "language": "possessive_english"
                },
                "ngram_filter": {
                    "type": "edge_ngram",
                    "min_gram": 1,
                    "max_gram": 25
                }
            }
        }
    }
}


答:
Just to add a bit to the situation when d is used in function, it depends on when d is declared. If d is declared within the function, and there is no inner function referencing d, it will be garbage collected.

for example:

```<code>def outer():
     d = np.arange(10000)
     def inner():
         d += 1
         return d
     return inner
</code>```

in this case d will still reside in the memory if after outer() function is returned.

Title: When is data freed?

Body:
Just to add a bit to the situation when d is used in function, it depends on when d is declared. If d is declared within the function, and there is no inner function referencing d, it will be garbage collected.

for example:

def outer():
     d = np.arange(10000)
     def inner():
         d += 1
         return d
     return inner

in this case d will still reside in the memory if after outer() function is returned.


问:
How do I return multiple tables using MySqlDataReader?
I want to return two tables using a mySqlDataReader and load the results into two datatables.

```<code> using (MySqlConnection connMySql = new MySqlConnection(global.g_connString))
            {
               MySqlCommand cmd = connMySql.CreateCommand();
                cmd.CommandText = @"
                                    SELECT * FROM table1;
                                    SELECT * FROM table2;
                                    ";
                connMySql.Open();
                using (MySqlDataReader dr = cmd.ExecuteReader())
                {
                        DataTable dt1 = new DataTable();
                        dt1.Load(dr);
                        dr.NextResult();
                        DataTable dt2 = new DataTable();
                        dt2.Load(dr);

                        gridView1.DataSource = dt1;
                        gridView1.DataBind();
                        gridView2.DataSource = dt2;
                        gridView2.DataBind();
                 }
</code>```

However, when I run this, only one gridView is populated. Can I use NextResult in this way, or is there a better way to acheive this?

Thanks in advance,

Ben

答:
Don't call dr.NextResult() between the two Load calls. The reader is already advanced to the next resultset.

From MSDN : The Load method consumes the first result set from the loaded IDataReader, and after successful completion, sets the reader's position to the next result set, if any.

Steven

[edit]

Checking the result of dr.NextResult() will also make it easier to detect whats exactly happening in your code.

ContentLicense: CC BY-SA 2.5

Body:
I want to return two tables using a mySqlDataReader and load the results into two datatables.

 using (MySqlConnection connMySql = new MySqlConnection(global.g_connString))
            {
               MySqlCommand cmd = connMySql.CreateCommand();
                cmd.CommandText = @"
                                    SELECT * FROM table1;
                                    SELECT * FROM table2;
                                    ";
                connMySql.Open();
                using (MySqlDataReader dr = cmd.ExecuteReader())
                {
                        DataTable dt1 = new DataTable();
                        dt1.Load(dr);
                        dr.NextResult();
                        DataTable dt2 = new DataTable();
                        dt2.Load(dr);

                        gridView1.DataSource = dt1;
                        gridView1.DataBind();
                        gridView2.DataSource = dt2;
                        gridView2.DataBind();
                 }

However, when I run this, only one gridView is populated. Can I use NextResult in this way, or is there a better way to acheive this?

Thanks in advance,

Ben


问:
Acumatica: Retrieving first record in a view for a display field - extraneous Order Bys
We have created a screen and graph that stores custom information about a given serial number for an inventory item (INItemLotSerial).

I'm looking to be able to display the current location of the serial number, based on the location of the most recent transaction.  (Ideally I'd also like to be able display if the serial number is currently in inventory, but that's probably a different question.)

Here is my view on the graph:

```<code>public PXSelect<INTranSplit, Where<INTranSplit.lotSerialNbr, Equal<Optional<INItemLotSerial.lotSerialNbr>>,
    And<INTranSplit.inventoryID, Equal<Optional<INItemLotSerial.inventoryID>>>>, OrderBy<Desc<INTranSplit.createdDateTime>>> InventoryLocation;
</code>```

And my field on the page:

```<code><px:PXSegmentMask Enabled="False" AllowEdit="False" runat="server" ID="CstPXSegmentMask5" DataField="InventoryLocation.LocationID" ></px:PXSegmentMask>
</code>```

I'm expecting the field to grab the first record and ignore the rest.

However, when I look at the generated SQL in a SQL Trace, Acumatica appears to be adding its own Order By fields:

```<code>exec sp_executesql N'SELECT [INTranSplit].[DocType], [INTranSplit].[TranType], [INTranSplit].[RefNbr], [INTranSplit].[LineNbr], [INTranSplit].[POLineType], [INTranSplit].[TransferType], [INTranSplit].[ToSiteID], [INTranSplit].[ToLocationID], [INTranSplit].[SplitLineNbr], [INTranSplit].[TranDate], [INTranSplit].[InvtMult], [INTranSplit].[InventoryID], [INTranSplit].[SubItemID], [INTranSplit].[CostSubItemID], [INTranSplit].[CostSiteID], [INTranSplit].[SiteID], [INTranSplit].[LocationID], [INTranSplit].[LotSerialNbr], [INTranSplit].[ExpireDate], [INTranSplit].[Released], [INTranSplit].[UOM], [INTranSplit].[Qty], [INTranSplit].[BaseQty], [INTranSplit].[MaxTransferBaseQty], [INTranSplit].[OrigPlanType], [INTranSplit].[IsFixedInTransit], [INTranSplit].[PlanID], [INTranSplit].[TotalQty], [INTranSplit].[TotalCost], [INTranSplit].[AdditionalCost], ( CASE WHEN  ( [INTranSplit].[TotalQty] = .0) THEN  .0 ELSE  ( [INTranSplit].[TotalCost] /  [INTranSplit].[TotalQty]) END), [INTranSplit].[CreatedByID], [INTranSplit].[CreatedByScreenID], [INTranSplit].[CreatedDateTime], [INTranSplit].[LastModifiedByID], [INTranSplit].[LastModifiedByScreenID], [INTranSplit].[LastModifiedDateTime], [INTranSplit].[tstamp], [INTranSplit].[UsrQtyForQC], [INTranSplit].[UsrQtyCoded], [INTranSplit].[UsrQtyCompleted] FROM INTranSplit INTranSplit WHERE (INTranSplit.CompanyID = 2) AND  [INTranSplit].[LotSerialNbr] = @P0 AND [INTranSplit].[InventoryID] = @P1
ORDER BY [INTranSplit].[DocType], [INTranSplit].[RefNbr], [INTranSplit].[LineNbr], [INTranSplit].[SplitLineNbr], [INTranSplit].[CreatedDateTime] DESC OPTION(OPTIMIZE FOR UNKNOWN) /* IN.21.00.00 */',N'@P0 nvarchar(100),@P1 int',@P0=N'EOSC52270005',@P1=16067
</code>```

which are causing a different record to be returned first, rather than the most recent one.

How do I convince Acumatica to run the BQL I'm asking for and drop the extra order by fields?  Or is there an entirely different approach to displaying the most recent transaction location that would be preferable?

答:
What I would recommend doing in this particular situation if you need specialized filtering is using the IEnumerable sort

```<code>public IEnumerable inventoryLocation()
{
        PXView select = new PXView(this, true, InventoryLocation.View.BqlSelect);
        Int32 totalrow = 0;
        Int32 startrow = PXView.StartRow;
        List<object> result = select.Select(PXView.Currents, PXView.Parameters, PXView.Searches,
            PXView.SortColumns, PXView.Descendings, PXView.Filters, ref startrow, PXView.MaximumRows, ref totalrow);
        INTranSplit latest = null;
        if (result.Count > 0)
        {
            //We need to perform a custom order in order to get to the latest record.
            latest = result.First() as INTranSplit;
            foreach (INTranSplit row in result)
            {
                if (latest.CreatedDateTime.Value < row.CreatedDateTime.Value)
                {
                    latest = row;
                }

            }
        }
        return new List<object> { latest };
}
</code>```

Where you would grab all the records, get the first record, and then look to find the latest record.

Cheers!

Body:
We have created a screen and graph that stores custom information about a given serial number for an inventory item (INItemLotSerial).

I'm looking to be able to display the current location of the serial number, based on the location of the most recent transaction.  (Ideally I'd also like to be able display if the serial number is currently in inventory, but that's probably a different question.)

Here is my view on the graph:

public PXSelect<INTranSplit, Where<INTranSplit.lotSerialNbr, Equal<Optional<INItemLotSerial.lotSerialNbr>>,
    And<INTranSplit.inventoryID, Equal<Optional<INItemLotSerial.inventoryID>>>>, OrderBy<Desc<INTranSplit.createdDateTime>>> InventoryLocation;

And my field on the page:

<px:PXSegmentMask Enabled="False" AllowEdit="False" runat="server" ID="CstPXSegmentMask5" DataField="InventoryLocation.LocationID" ></px:PXSegmentMask>

I'm expecting the field to grab the first record and ignore the rest.

However, when I look at the generated SQL in a SQL Trace, Acumatica appears to be adding its own Order By fields:

exec sp_executesql N'SELECT [INTranSplit].[DocType], [INTranSplit].[TranType], [INTranSplit].[RefNbr], [INTranSplit].[LineNbr], [INTranSplit].[POLineType], [INTranSplit].[TransferType], [INTranSplit].[ToSiteID], [INTranSplit].[ToLocationID], [INTranSplit].[SplitLineNbr], [INTranSplit].[TranDate], [INTranSplit].[InvtMult], [INTranSplit].[InventoryID], [INTranSplit].[SubItemID], [INTranSplit].[CostSubItemID], [INTranSplit].[CostSiteID], [INTranSplit].[SiteID], [INTranSplit].[LocationID], [INTranSplit].[LotSerialNbr], [INTranSplit].[ExpireDate], [INTranSplit].[Released], [INTranSplit].[UOM], [INTranSplit].[Qty], [INTranSplit].[BaseQty], [INTranSplit].[MaxTransferBaseQty], [INTranSplit].[OrigPlanType], [INTranSplit].[IsFixedInTransit], [INTranSplit].[PlanID], [INTranSplit].[TotalQty], [INTranSplit].[TotalCost], [INTranSplit].[AdditionalCost], ( CASE WHEN  ( [INTranSplit].[TotalQty] = .0) THEN  .0 ELSE  ( [INTranSplit].[TotalCost] /  [INTranSplit].[TotalQty]) END), [INTranSplit].[CreatedByID], [INTranSplit].[CreatedByScreenID], [INTranSplit].[CreatedDateTime], [INTranSplit].[LastModifiedByID], [INTranSplit].[LastModifiedByScreenID], [INTranSplit].[LastModifiedDateTime], [INTranSplit].[tstamp], [INTranSplit].[UsrQtyForQC], [INTranSplit].[UsrQtyCoded], [INTranSplit].[UsrQtyCompleted] FROM INTranSplit INTranSplit WHERE (INTranSplit.CompanyID = 2) AND  [INTranSplit].[LotSerialNbr] = @P0 AND [INTranSplit].[InventoryID] = @P1
ORDER BY [INTranSplit].[DocType], [INTranSplit].[RefNbr], [INTranSplit].[LineNbr], [INTranSplit].[SplitLineNbr], [INTranSplit].[CreatedDateTime] DESC OPTION(OPTIMIZE FOR UNKNOWN) /* IN.21.00.00 */',N'@P0 nvarchar(100),@P1 int',@P0=N'EOSC52270005',@P1=16067

which are causing a different record to be returned first, rather than the most recent one.

How do I convince Acumatica to run the BQL I'm asking for and drop the extra order by fields?  Or is there an entirely different approach to displaying the most recent transaction location that would be preferable?

Body:
What I would recommend doing in this particular situation if you need specialized filtering is using the IEnumerable sort

public IEnumerable inventoryLocation()
{
        PXView select = new PXView(this, true, InventoryLocation.View.BqlSelect);
        Int32 totalrow = 0;
        Int32 startrow = PXView.StartRow;
        List<object> result = select.Select(PXView.Currents, PXView.Parameters, PXView.Searches,
            PXView.SortColumns, PXView.Descendings, PXView.Filters, ref startrow, PXView.MaximumRows, ref totalrow);
        INTranSplit latest = null;
        if (result.Count > 0)
        {
            //We need to perform a custom order in order to get to the latest record.
            latest = result.First() as INTranSplit;
            foreach (INTranSplit row in result)
            {
                if (latest.CreatedDateTime.Value < row.CreatedDateTime.Value)
                {
                    latest = row;
                }

            }
        }
        return new List<object> { latest };
}

Where you would grab all the records, get the first record, and then look to find the latest record.

Cheers!


问:
process.start() method is not producing files
I have an .exe file. I want to run the .exe file with Process.Start() command. The .exe file produces two files when executed one is .xls file and another one is .htm file. When I run the .exe file through .net code, the two files that are supposed to be produced are not produced. Below is my code:

```<code> static void Main(string[] args)
    {
        Process.Start(@"C:\Test\test.exe");
}
</code>```

I am not sure if the process is getting executed, but I don't see any error. Also, I don't see any files produced. If I manually run the process then I can see the two files produced in the same folder where the .exe file resides.

Any help will be appreciated.

答:
Try waiting for the process to finish:

```<code>Process.Start(@"C:\Test\test.exe").WaitForExit();
</code>```

Better for debugging:

```<code>Process process = Process.Start(@"C:\Test\test.exe");
int id = process.Id;
Process runningProc = Process.GetProcessById(id);
runningProc.WaitForExit();
</code>```

Body:
I have an .exe file. I want to run the .exe file with Process.Start() command. The .exe file produces two files when executed one is .xls file and another one is .htm file. When I run the .exe file through .net code, the two files that are supposed to be produced are not produced. Below is my code:

 static void Main(string[] args)
    {
        Process.Start(@"C:\Test\test.exe");
}

I am not sure if the process is getting executed, but I don't see any error. Also, I don't see any files produced. If I manually run the process then I can see the two files produced in the same folder where the .exe file resides.

Any help will be appreciated.

Body:
Try waiting for the process to finish:

Process.Start(@"C:\Test\test.exe").WaitForExit();

Better for debugging:

Process process = Process.Start(@"C:\Test\test.exe");
int id = process.Id;
Process runningProc = Process.GetProcessById(id);
runningProc.WaitForExit();


问:
Visual Studio 2015 - Properties window is blank sometimes?
Environment: Win 10, VS 2015, patched to the kazoo.

Behaviour: The VS 2015 (as of Aug 2015) has a blank properties window when opening some projects and clicking on some visual items (winforms).

Oddly - when I close VS 2015, the properties window suddenly populates with data just prior to closing, as if the data is there, but just not properly shown.

Fix attempts:

Restarting VS 2015 doesn't appear to fix the issue.  For some reason this view element seems 'confused' about which property it's showing content for, as clicking other winforms controls fails to update the property view

Restarting the entire OS (a hyperV VM in my case) fixes it.

I wouldn't mind just a restart of VS 2015, but the entire OS is both oddly required and frankly an annoyance.

答:
Whatever I tried, my custom control (maybe because it's in a DLL) did not throw an exception when debugging with a second VS instance.

So what I did as a workaround was to disable 'Enable Project Code' (On the small option bar in the XAML designer) which disabled all UI code in the editor and made it possible for me to work on it.

Warning: Only last resort.


问:
can i disable channel event logging records in database for specific context ?
i'm using the cel ( channel event logging ) for billing because CDR is not accurate for many purposes.

everything works well.
but i want to know if i can disable cel records for some contexts in my diaplan . (like the NoCDR() function for cdr module).

i only need cel records for specific contexts in my diaplan.

is there a function like NoCDR() or a setting to only allow cel records for specific contexts.

Thanks.

答:
No, you can't

But you can delete it from database using external script or trigger.


问:
Where-Object : Cannot bind parameter 'FilterScript'
I have one problem with two questions. I have following powercli cmd:

```<code>$snapLst = Get-VM vmindev |Get-Snapshot |Select VM, Name, Description, `
 @{Name='Created'; Expression={{$_.Created.ToString("yyMMdd")}}, `
 @{Name='SizeMB'; Expression={[int] $_.SizeMB}}
$resultLst=$snapLst| where SizeMB -gt 1000 |Sort-Object SizeMB |`
 Select @{Name='Type'; Expression={'BIG'}},*
</code>```

When run in my DEV env (powercli session on my desktop connecting to the vSphere sever), everything is fine. When run in PRODUCTION (ie. powercli session on the vSphere server), I get the following error:

```<code>Where-Object : Cannot bind parameter 'FilterScript'. Cannot convert the "SizeMB" value of type "System.String" to type System.Management.Automation.ScriptBlock".
    At C:\Users\kness\Scripts\sn2.ps1:32 char:27
    + $resultLst=$snapLst| where <<<<  SizeMB -gt 1000 |Sort-Object SizeMB |Select
    @{Name='Type'; Expression={'BIG'}},
        + CategoryInfo          : InvalidArgument: (:) [Where-Object], ParameterBindingException
        + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.WhereObjectCommand
</code>```

Q1: What - in the environment setup - would make the script behaves differently? I checked the versions of the powercli ... they're exactly the same.

Q2: Because the above error, I look into the property of the list by running this cmd:

```<code>$snapLst = Get-VM vmindev |Get-Snapshot |Get-Member |Findstr Size
SizeGB            Property   System.Nullable`1[[System.Decimal, mscorlib, Ve...
SizeMB            Property   System.Decimal SizeMB {get;}
</code>```

SizeMB is a "decimal" type; why the error complains that it is a "string"?

Thx in advance!

答:
I got it resolved with helps fr TessellatingHeckler.

A1. Although my PowerCLI package is the same, it operates on two different Powershell installation. On my desktop, PSVersion is 4.0 and on the production server, it is 2.0

A2. This is related to A1. In PS 4.0, the cmdlet where is translated properly to Where-Object {...}. Whereas in PS 2.0, it is a syntax error. The complain about SizeMB being System.String is just a red herring following the "where" syntax error.

By changing where SizeMB -gt 1000 to Where-Object {$_.SizeMB -gt 1000} the script is now working. I guess, the alternative would be to upgrade the PS on the vSphere server ... but I dont want to go there. Thanks for your helps everyone.

Body:
I have one problem with two questions. I have following powercli cmd:

$snapLst = Get-VM vmindev |Get-Snapshot |Select VM, Name, Description, `
 @{Name='Created'; Expression={{$_.Created.ToString("yyMMdd")}}, `
 @{Name='SizeMB'; Expression={[int] $_.SizeMB}}
$resultLst=$snapLst| where SizeMB -gt 1000 |Sort-Object SizeMB |`
 Select @{Name='Type'; Expression={'BIG'}},*

When run in my DEV env (powercli session on my desktop connecting to the vSphere sever), everything is fine. When run in PRODUCTION (ie. powercli session on the vSphere server), I get the following error:

Where-Object : Cannot bind parameter 'FilterScript'. Cannot convert the "SizeMB" value of type "System.String" to type System.Management.Automation.ScriptBlock".
    At C:\Users\kness\Scripts\sn2.ps1:32 char:27
    + $resultLst=$snapLst| where <<<<  SizeMB -gt 1000 |Sort-Object SizeMB |Select
    @{Name='Type'; Expression={'BIG'}},
        + CategoryInfo          : InvalidArgument: (:) [Where-Object], ParameterBindingException
        + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.WhereObjectCommand

Q1: What - in the environment setup - would make the script behaves differently? I checked the versions of the powercli ... they're exactly the same.

Q2: Because the above error, I look into the property of the list by running this cmd:

$snapLst = Get-VM vmindev |Get-Snapshot |Get-Member |Findstr Size
SizeGB            Property   System.Nullable`1[[System.Decimal, mscorlib, Ve...
SizeMB            Property   System.Decimal SizeMB {get;}

SizeMB is a "decimal" type; why the error complains that it is a "string"?

Thx in advance!


问:
Time Complexity - Bad Recursion - British Change Combinations
I recently came up with a naive (+ poor) solution to the British Change Problem (i.e. how many combinations of coins can generate a given total). I have a better solution now, but was still interested in solving the time and space complexity of the two solutions below.

Worst Solution

This solution recursively tries combining every number against itself and every other number, resulting in a lot of duplicate work. I believe it's O(n^n) time and not sure how to measure space complexity (but it's huge, since we're storing every result). Thoughts?

```<code>var makeChange = function(total){ // in pence
  var allSets = new Set();
  var coins = [1,2,5,10,20,50,100,200];

  var subroutine = (arr, total) => {
    if(total < 0){ return; }
    if(total === 0){
      allSets.add(''+arr);
    } else {
      // increase each coin amount by one and decrease the recursive total by one
      for(var i = 0; i<coins.length; i++){
        if((total - coins[i]) >= 0){
          subroutine(arr.slice(0,i).concat(arr[i]+1).concat(arr.slice(i+1)), (total - coins[i]))
        }
      }
    }
  };

  var zeros = new Array(coins.length).fill(0);
  subroutine(zeros, total);
  return allSets.size;
};
</code>```

Improved Solution

This solution still has massive space complexity but I believe the time complexity has -improved- to O(n!) since we're recursing on smaller subsets of coins each time.

```<code>var makeChange = function(total){ // in pence
  var allSets = new Set();
  var coins = [1,2,5,10,20,50,100,200];

  var subroutine = (arr, total, start) => {
    if(total < 0){ return; }
    if(total === 0){
      console.log(''+arr);
      allSets.add(''+arr);
    } else {
      // only solve for coins above start, since lower coins already solved
      for(var i = start; i<coins.length; i++){
        if((total - coins[i]) >= 0){
          subroutine(arr.slice(0,i).concat(arr[i]+1).concat(arr.slice(i+1)), (total - coins[i]), i);
        }
      }
    }
  };

  var zeros = new Array(coins.length).fill(0);
  for(let i = 0; i<coins.length; i++){
    subroutine(zeros, total, i);
  }

  return allSets.size;
};
</code>```

Please help me to understand if my time/space complexity estimates are correct, and how to better estimate future problems like these. Thanks!

答:
The complexity of the first algorithm is not actually an O(n^n). N is a variable which represents your input. In this case, I will refer to the variable "total" as your input, so N is based on total. For your algorithm to be O(n^n), it's recurrence tree would have to have a depth of N and a branching factor of N. Here, your depth of your recurrence is based on the smallest variable in your coins array. There is one branch of your recursion tree where you simply subtract that value off every time and recurse until total is zero. Given that that value is constant, it is safe to say your depth is n. Your branching factor for your recursion tree is also based off of your coins array, or the number of values in it. For every function call, you generate C other function calls, where C is the size of your coins array. That means your function is actually O(n^c) not O(n^n). Your time and space complexities are both based off of the size of your coins array as well as your input number.

The space complexity for your function is O(n^c * c). Every time you call your function, you also pass it an array of a size based on your input. We already showed that there are O(n^c) calls, and each call incorporates an array of size c.

Remember when analyzing the complexity of functions to take into account all inputs.

Body:
I recently came up with a naive (+ poor) solution to the British Change Problem (i.e. how many combinations of coins can generate a given total). I have a better solution now, but was still interested in solving the time and space complexity of the two solutions below.

Worst Solution

This solution recursively tries combining every number against itself and every other number, resulting in a lot of duplicate work. I believe it's O(n^n) time and not sure how to measure space complexity (but it's huge, since we're storing every result). Thoughts?

var makeChange = function(total){ // in pence
  var allSets = new Set();
  var coins = [1,2,5,10,20,50,100,200];

  var subroutine = (arr, total) => {
    if(total < 0){ return; }
    if(total === 0){
      allSets.add(''+arr);
    } else {
      // increase each coin amount by one and decrease the recursive total by one
      for(var i = 0; i<coins.length; i++){
        if((total - coins[i]) >= 0){
          subroutine(arr.slice(0,i).concat(arr[i]+1).concat(arr.slice(i+1)), (total - coins[i]))
        }
      }
    }
  };

  var zeros = new Array(coins.length).fill(0);
  subroutine(zeros, total);
  return allSets.size;
};

Improved Solution

This solution still has massive space complexity but I believe the time complexity has -improved- to O(n!) since we're recursing on smaller subsets of coins each time.

var makeChange = function(total){ // in pence
  var allSets = new Set();
  var coins = [1,2,5,10,20,50,100,200];

  var subroutine = (arr, total, start) => {
    if(total < 0){ return; }
    if(total === 0){
      console.log(''+arr);
      allSets.add(''+arr);
    } else {
      // only solve for coins above start, since lower coins already solved
      for(var i = start; i<coins.length; i++){
        if((total - coins[i]) >= 0){
          subroutine(arr.slice(0,i).concat(arr[i]+1).concat(arr.slice(i+1)), (total - coins[i]), i);
        }
      }
    }
  };

  var zeros = new Array(coins.length).fill(0);
  for(let i = 0; i<coins.length; i++){
    subroutine(zeros, total, i);
  }

  return allSets.size;
};

Please help me to understand if my time/space complexity estimates are correct, and how to better estimate future problems like these. Thanks!


问:
SSHTunnel not installed correctly?
I'm using anaconda python 3.5.2 in PyCharm using windows 10.

I'm pretty new to python and a complete noob to PyCharm!

I just want to use SSHtunnel.

I have intalled the package and it shown in the project interpreter page:

However when I try to run the code which I cut and pasted from example 1 here https://github.com/pahaz/sshtunnel:

```<code>from sshtunnel import SSHTunnelForwarder

server = SSHTunnelForwarder(
'pahaz.urfuclub.ru',
ssh_username="pahaz",
ssh_password="secret",
remote_bind_address=('127.0.0.1', 8080)
)

server.start()

print(server.local_bind_port)  # show assigned local port
# work with `SECRET SERVICE` through `server.local_bind_port`.

server.stop()
</code>```

I get the following error:

```<code>C:\Users\HP\Anaconda3\python.exe C:/Users/HP/PycharmProjects/SSH_Downloader/SSH_Downloader
Traceback (most recent call last):
  File "C:/Users/HP/PycharmProjects/SSH_Downloader/SSH_Downloader", line 1, in <module>
    from sshtunnel import SSHTunnelForwarder
ImportError: cannot import name 'SSHTunnelForwarder'

Process finished with exit code 1
</code>```

How can I sort this out?

答:
sshtunnel  for python and sshtunnel Anaconda-python are different modules.

To install sshtunnel for Anaconda; you need to use the Anaconda repository. use below pip command; Hope this helps:

pip install -i https://pypi.anaconda.org/pypi/simple sshtunnel

More Description Here

Title: SSHTunnel not installed correctly?

Body:
I'm using anaconda python 3.5.2 in PyCharm using windows 10.

I'm pretty new to python and a complete noob to PyCharm!

I just want to use SSHtunnel.

I have intalled the package and it shown in the project interpreter page:

However when I try to run the code which I cut and pasted from example 1 here https://github.com/pahaz/sshtunnel:

from sshtunnel import SSHTunnelForwarder

server = SSHTunnelForwarder(
'pahaz.urfuclub.ru',
ssh_username="pahaz",
ssh_password="secret",
remote_bind_address=('127.0.0.1', 8080)
)

server.start()

print(server.local_bind_port)  # show assigned local port
# work with `SECRET SERVICE` through `server.local_bind_port`.

server.stop()

I get the following error:

C:\Users\HP\Anaconda3\python.exe C:/Users/HP/PycharmProjects/SSH_Downloader/SSH_Downloader
Traceback (most recent call last):
  File "C:/Users/HP/PycharmProjects/SSH_Downloader/SSH_Downloader", line 1, in <module>
    from sshtunnel import SSHTunnelForwarder
ImportError: cannot import name 'SSHTunnelForwarder'

Process finished with exit code 1

How can I sort this out?


问:
How to solve Unresolved inclusion: <iostream> in eclipse?
I built a simple program in eclipse:

```<code>#include <iostream>

using namespace std;
int main()
{
    cout << "TEST" << endl;
    return 0;
}
</code>```

It worked in Visual Studio and CodeBlocks, but eclipse is acting weird. it says:

Unresolved inclusion: <iostream>

I read here:
C++ - Unresolved inclusion: <iostream>

and here: Unresolved <iostream> in Eclipse, Ubuntu

and neither of them worked.

Here are screenshots of project properties:

edit:

I downloaded MinGW and now i have this under Settings:

How should i proceed?
Maybe now i don't need #include <iostream> because it's now included in the project?

I found iostream under Includes.

So i tried deleting #include <iostream>, but when i try to run the program i get:
Launch Failed. Binary not found. error:

Thanks

edit:

Seems like if i compile in some other program (say CodeBlocks) and create the exe file, then eclipse can run it. But it can't build its own exe.

Why?

答:
This answer did not help me either. My issue was solved with the following steps:

You might try changing your source files from *.c to *.cpp. This will provoke gcc to think of the files as C++ and search the proper paths. Might need to make small modifications to the Makefile as well, like on the OBJ: line. Instead of:

OBJS = YourFile.o

try

OBJS = YourFile.cpp

Body:
I built a simple program in eclipse:

#include <iostream>

using namespace std;
int main()
{
    cout << "TEST" << endl;
    return 0;
}

It worked in Visual Studio and CodeBlocks, but eclipse is acting weird. it says:

Unresolved inclusion: <iostream>

I read here:
C++ - Unresolved inclusion: <iostream>

and here: Unresolved <iostream> in Eclipse, Ubuntu

and neither of them worked.

Here are screenshots of project properties:

edit:

I downloaded MinGW and now i have this under Settings:

How should i proceed?
Maybe now i don't need #include <iostream> because it's now included in the project?

I found iostream under Includes.

So i tried deleting #include <iostream>, but when i try to run the program i get:
Launch Failed. Binary not found. error:

Thanks

edit:

Seems like if i compile in some other program (say CodeBlocks) and create the exe file, then eclipse can run it. But it can't build its own exe.

Why?


问:
Background app best practices
Is Service and Notification the correct way to implement a background app with the following behavior?

1- User open the app, make some configurations and touch in a "run" button;

2- The main activity must be closed and a background service will be started;

3- A fixed notification will be displayed with some buttons ("stop" to finish the service and "Reconfigure");

thank you

答:
I did an app that at short intervals (1 to 10 sec) acquires constantly data from a remote TCP server, even on the background also with the screen off.

In the Main Activity onStop I acquire a Partial WakeLock and I start the Service with STARTFOREGROUND_ACTION intent, the Service calls startForeground and shows the Notification.

On Activity onResume the WakeLock is released, the Service stops with STOPFOREGROUND_ACTION intent and the Service itself calls stopForeground & stopSelf.

I don't have buttons in the notification, if user touches the notification the Activity is shown.

It works very well I tested it with hours of continuous operation.

Title: Background app best practices


问:
I'm getting ORA-00936: missing expression. Why is that? Can someone help me out?
```<code>INSERT ALL
INTO EMPLOYEE
(EMPL_CODE_ID, EMPL_FIRST_NAME, EMPL_LAST_NAME, EMPL_ADDRESS,
EMPL_WORKING_AREA, EMPL_TITLE, EMPL_PHONE_NUMBER, EMPL_DOB,
EMPL_STATE, EMPL_COUNTRY)
VALUES
('A4','ROB','BOB','123 TREE TOP','FRONT DESK','RECEPTIONIST','301-000-0004','01/04/1994','MD','USA')

INTO EMPLOYEE
(EMPL_CODE_ID, EMPL_FIRST_NAME, EMPL_LAST_NAME, EMPL_ADDRESS,
EMPL_WORKING_AREA, EMPL_TITLE, EMPL_PHONE_NUMBER, EMPL_DOB,
EMPL_STATE, EMPL_COUNTRY)
VALUES
('A5','JOSH','FROG','125 TREE BARK LANE','FRONT DESK','RECEPTIONIST','301-000-0005','08/09/1994','VA','USA')
INTO EMPLOYEE
(EMPL_CODE_ID, EMPL_FIRST_NAME, EMPL_LAST_NAME, EMPL_ADDRESS,
EMPL_WORKING_AREA, EMPL_TITLE, EMPL_PHONE_NUMBER, EMPL_DOB,
EMPL_STATE, EMPL_COUNTRY)
VALUES
INTO EMPLOYEE
(EMPL_CODE_ID, EMPL_FIRST_NAME, EMPL_LAST_NAME, EMPL_ADDRESS,
EMPL_WORKING_AREA, EMPL_TITLE, EMPL_PHONE_NUMBER, EMPL_DOB,
EMPL_STATE, EMPL_COUNTRY)
VALUES
INTO EMPLOYEE
(EMPL_CODE_ID, EMPL_FIRST_NAME, EMPL_LAST_NAME, EMPL_ADDRESS,
EMPL_WORKING_AREA, EMPL_TITLE, EMPL_PHONE_NUMBER, EMPL_DOB,
EMPL_STATE, EMPL_COUNTRY)
VALUES
('A6','FRED','KIM','123 SENECA WAY','FRONT DESK','RECEPTIONIST','301-000-0006','03/23/1997','VA','USA')
SELECT * FROM DUAL;
</code>```

答: I think that the problem is that you´re missing values at the third and forth "INTO EMPLOYEE" statement. </p>


问:
SQL Query to Bucket Table Items
I am trying to bucket values within my table by the range they fall in, for example, if my table is the following:

```<code>course_name | current enrollment
course_1    | 10
course_2    | 200
course_3    | 500
</code>```

I get the following result:

```<code>enrollment_range | courses
10               | 1
100              | 1
500              | 1
</code>```

So far, I have the following:

```<code>SELECT
  CASE
    WHEN courses.current_enrollment >= 500 THEN 500
    WHEN courses.current_enrollment >= 250 THEN 250
    WHEN courses.current_enrollment >= 100 THEN 100
    WHEN courses.current_enrollment >= 50 THEN 50
    WHEN courses.current_enrollment >= 30 THEN  30
    WHEN courses.current_enrollment >= 10 THEN 10
  END enrollment_range, count() AS total
FROM courses
GROUP BY enrollment_range
ORDER BY enrollment_range ASC
</code>```

but I end up with an extra result that is the total number of courses I have, so I get something like the following:

```<code>enrollment_range | courses
10               | 1
100              | 1
500              | 1
                 | 3
</code>```

答:
In you sql, you should use a group in the count. In my SQL server, I can produce the correct result using the following script :</p>

```<code>SELECT
  CASE
    WHEN current_enrollment >= 500 THEN 500
    WHEN current_enrollment >= 250 THEN 250
    WHEN current_enrollment >= 100 THEN 100
    WHEN current_enrollment >= 50 THEN 50
    WHEN current_enrollment >= 30 THEN  30
    WHEN current_enrollment >= 10 THEN 10
  END as enrollment_range, t.course_name, t.count
FROM courses

join
( select  Count(course_name) as count,course_name FROM courses group by course_name ) t

on courses.course_name = t.course_name
</code>```

Title: SQL Query to Bucket Table Items

Body:
I am trying to bucket values within my table by the range they fall in, for example, if my table is the following:

course_name | current enrollment
course_1    | 10
course_2    | 200
course_3    | 500

I get the following result:

enrollment_range | courses
10               | 1
100              | 1
500              | 1

So far, I have the following:

SELECT
  CASE
    WHEN courses.current_enrollment >= 500 THEN 500
    WHEN courses.current_enrollment >= 250 THEN 250
    WHEN courses.current_enrollment >= 100 THEN 100
    WHEN courses.current_enrollment >= 50 THEN 50
    WHEN courses.current_enrollment >= 30 THEN  30
    WHEN courses.current_enrollment >= 10 THEN 10
  END enrollment_range, count() AS total
FROM courses
GROUP BY enrollment_range
ORDER BY enrollment_range ASC

but I end up with an extra result that is the total number of courses I have, so I get something like the following:

enrollment_range | courses
10               | 1
100              | 1
500              | 1
                 | 3

Body:
In you sql, you should use a group in the count. In my SQL server, I can produce the correct result using the following script :

SELECT
  CASE
    WHEN current_enrollment >= 500 THEN 500
    WHEN current_enrollment >= 250 THEN 250
    WHEN current_enrollment >= 100 THEN 100
    WHEN current_enrollment >= 50 THEN 50
    WHEN current_enrollment >= 30 THEN  30
    WHEN current_enrollment >= 10 THEN 10
  END as enrollment_range, t.course_name, t.count
FROM courses

join
( select  Count(course_name) as count,course_name FROM courses group by course_name ) t

on courses.course_name = t.course_name


问:
How safe is a password stored in database with these conversions?
How secure is a password converted to bytes, to binary, to hash. In a database? For like storing a jPasswordField password.</p>

答: Using a strong hash with a random salt is sufficiently safe. You will need to store both the hash and the salt in the database. You should read more about how to securely store user credentials, and if you have security questions, https://security.stackexchange.com/ may be a better forum.</p>


问:
How to stop simple_form setting radio buttons as readonly, gives Capybara error?
I am 'acceptance' testing creation of a Quote object with various attrs, the form is made with simple_form_for with the f.input specifying :radio_buttons. When running my tests an:

```<code>creating quote request
    Attempt to set readonly element with value: true
     * This will raise an exception in a future version of Capybara
</code>```

warning is given, suggesting that the form input has a readonly html element, which was not explicitly specified by me as true. Capybara does not seem to have an issue setting values for other input element types, therefore suggesting that they are not set as readonly.

Why is simple_form setting radio_button elements as readonly, if that is indeed what's happening here? And how do I override this so that Capybara can set these attrs with the value i place in my factory?

Code as below:

Model; quote.rb:

```<code>class Quote < ApplicationRecord
    enum industry:          [ :financial_services, :architect, :business_consultancy ]
    enum payment_frequency: [ :annually, :monthly ]
end
</code>```

Controller; quotes_controller.rb:

```<code>Class QuotesController < ApplicationController

  def new
    @quote = Quote.new
  end

  def create
    @quote = Quote.new(quote_params)
    if @quote.save
        redirect_to root_url, notice: 'Quote request created'
    else
      render :new
    end
  end

  def show
    @quote = Quote.find(params[:id])
  end

private

  def quote_params
    params.require(:quote).permit(:lives_overseas)
  end
end
</code>```

quote/new.html.erb

```<code><div class='container'>
    <div class='row'>
        <div class='col-md-6'>
            <%= simple_form_for @quote do |f| %>
                <%= f.input :lives_overseas, as: :radio_buttons %>
                <%= f.submit "Get quote", class: 'btn btn-primary' %>
            <% end %>
        </div>
    </div>
</div>
</code>```

To clean up tests i refactored form completion into methods in spec/support/new_quote_form.rb:

```<code>class NewQuoteForm
    include Capybara::DSL

    def visit_page
        visit('/')
        self
    end

    def fill_in_with(params = {})
        check('GLA')                                                    # How to fetch params option if given here?
        within(".quote_prev_cover") { choose('No') }                    # How to fetch params option if given here?
        fill_in('Company name', with: params.fetch(:co_name, 'acme co'))
        fill_in('Company number', with: params.fetch(:co_number, '1234567'))
        fill_in('Postcode', with: params.fetch(:postcode, 'al1 1aa'))
        select('Financial services', from: 'Industry')                  # How to fetch params option if given here?
        within(".quote_lives_overseas") { choose('No') }                # How to fetch params option if given here?
        within("#quote_scheme_start_date_1i") { select('2018') }        # How to fetch params option if given here?
        within("#quote_scheme_start_date_2i") { select('January') }     # How to fetch params option if given here?
        within("#quote_scheme_start_date_3i") { select('1') }
        select('Monthly', from: 'Payment frequency')                    # How to fetch params option if given here?
        fill_in('Commission level', with: params.fetch(:commission_level, '10'))
        self
    end

    def submit
        click_on('Get quote')
        self
    end
end
</code>```

And the actual test which i now realise, thanks to @thomas-walpole, is the one generating the message is; create_quote_spec.rb

```<code>require 'rails_helper'
require_relative '../support/new_quote_form'

feature 'creating quote request' do
    let(:new_quote_form) { NewQuoteForm.new }

    scenario 'completing quote data' do
        new_quote_form.visit_page.fill_in_with().submit
        expect(page).to have_content('Quote request created')
    end

    scenario 'cannot reqest quote with invalid data' do
        new_quote_form.visit_page.submit
        expect(page).to have_content("Must be selected")
    end
end
</code>```

Chrome inspector shows this html:

```<code><input class="radio_buttons optional" readonly="readonly" value="false" name="quote[lives_overseas]" id="quote_lives_overseas_false" type="radio">
</code>```

I've attempted to comment out config/initializers/simple_form.rb; b.optional :readonly but no change to the test warning.

答:
The issue is a simple_form bug setting readonly="readonly" in the false option of this radiobutton. There are two solutions, courtesy of this post.

1) Within config/initializers/simple_form_bootstrap.rb comment out b.optional :readonly within the :vertical_radio_and_checkboxes wrapper.

2) set your simple form arguments as below:

<%= f.input :prev_cover, as: :radio_buttons, collection: [['Yes', true],
                        ['No', false]], readonly: nil %>

Though option 2 still has Capybara giving you a warning when you run your tests of; Attempt to set readonly element with value: true * This will raise an exception in a future version of Capybara

Body:
I am 'acceptance' testing creation of a Quote object with various attrs, the form is made with simple_form_for with the f.input specifying :radio_buttons. When running my tests an:

creating quote request
    Attempt to set readonly element with value: true
     * This will raise an exception in a future version of Capybara

warning is given, suggesting that the form input has a readonly html element, which was not explicitly specified by me as true. Capybara does not seem to have an issue setting values for other input element types, therefore suggesting that they are not set as readonly.

Why is simple_form setting radio_button elements as readonly, if that is indeed what's happening here? And how do I override this so that Capybara can set these attrs with the value i place in my factory?

Code as below:

Model; quote.rb:

class Quote < ApplicationRecord
    enum industry:          [ :financial_services, :architect, :business_consultancy ]
    enum payment_frequency: [ :annually, :monthly ]
end

Controller; quotes_controller.rb:

Class QuotesController < ApplicationController

  def new
    @quote = Quote.new
  end

  def create
    @quote = Quote.new(quote_params)
    if @quote.save
        redirect_to root_url, notice: 'Quote request created'
    else
      render :new
    end
  end

  def show
    @quote = Quote.find(params[:id])
  end

private

  def quote_params
    params.require(:quote).permit(:lives_overseas)
  end
end

quote/new.html.erb

            <%= simple_form_for @quote do |f| %>
                <%= f.input :lives_overseas, as: :radio_buttons %>
                <%= f.submit "Get quote", class: 'btn btn-primary' %>
            <% end %>

To clean up tests i refactored form completion into methods in spec/support/new_quote_form.rb:

class NewQuoteForm
    include Capybara::DSL

    def visit_page
        visit('/')
        self
    end

    def fill_in_with(params = {})
        check('GLA')                                                    # How to fetch params option if given here?
        within(".quote_prev_cover") { choose('No') }                    # How to fetch params option if given here?
        fill_in('Company name', with: params.fetch(:co_name, 'acme co'))
        fill_in('Company number', with: params.fetch(:co_number, '1234567'))
        fill_in('Postcode', with: params.fetch(:postcode, 'al1 1aa'))
        select('Financial services', from: 'Industry')                  # How to fetch params option if given here?
        within(".quote_lives_overseas") { choose('No') }                # How to fetch params option if given here?
        within("#quote_scheme_start_date_1i") { select('2018') }        # How to fetch params option if given here?
        within("#quote_scheme_start_date_2i") { select('January') }     # How to fetch params option if given here?
        within("#quote_scheme_start_date_3i") { select('1') }
        select('Monthly', from: 'Payment frequency')                    # How to fetch params option if given here?
        fill_in('Commission level', with: params.fetch(:commission_level, '10'))
        self
    end

    def submit
        click_on('Get quote')
        self
    end
end

And the actual test which i now realise, thanks to @thomas-walpole, is the one generating the message is; create_quote_spec.rb

require 'rails_helper'
require_relative '../support/new_quote_form'

feature 'creating quote request' do
    let(:new_quote_form) { NewQuoteForm.new }

    scenario 'completing quote data' do
        new_quote_form.visit_page.fill_in_with().submit
        expect(page).to have_content('Quote request created')
    end

    scenario 'cannot reqest quote with invalid data' do
        new_quote_form.visit_page.submit
        expect(page).to have_content("Must be selected")
    end
end

Chrome inspector shows this html:

<input class="radio_buttons optional" readonly="readonly" value="false" name="quote[lives_overseas]" id="quote_lives_overseas_false" type="radio">

I've attempted to comment out config/initializers/simple_form.rb; b.optional :readonly but no change to the test warning.


问:
How to hover a div and make its background-image slowly dissapear without affecting the content that's inside it?
I have a div with a background-color , background-image and some text on it . I want , when i hover the div , the background-image to slowly dissapear, like a transition effect or something, but the text and the color still remain there visible in the div.I am open to any type of method.

答:
You can do this easily using only CSS adding a few DOM elements.

.fadebg {
  position: relative;
  height: 100px;
  width: 100px;
  background-color: red;
}
.fadebg:hover .img, .fadebg:hover img {
    opacity: 0;
}

.text {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  color: white;
  z-index: 1;
}

.img {
    background-repeat: no-repeat;
  background-image: url(https://upload.wikimedia.org/wikipedia/en/b/bc/Screenshot_Snarf.jpg);
  background-size: 100px 100px;
}

.img, img {
  opacity: 1;
  height: 100px;
  width: 100px;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  overflow: hidden;
  -webkit-transition: 1s all;
  -moz-transition: 1s all;
  -ms-transition: 1s all;
  -o-transition: 1s all;
  transition: 1s all;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="fadebg">
    <div class="text">Hi</div>
    <div class="img"></div>
</div>
<br>
<div class="fadebg">
    <div class="text">Hi</div>
    <img src="https://upload.wikimedia.org/wikipedia/en/b/bc/Screenshot_Snarf.jpg">
</div></code>```

Body:
You can do this easily using only CSS adding a few DOM elements.

.fadebg {
  position: relative;
  height: 100px;
  width: 100px;
  background-color: red;
}
.fadebg:hover .img, .fadebg:hover img {
    opacity: 0;
}

.text {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  color: white;
  z-index: 1;
}

.img {
    background-repeat: no-repeat;
  background-image: url(https://upload.wikimedia.org/wikipedia/en/b/bc/Screenshot_Snarf.jpg);
  background-size: 100px 100px;
}

.img, img {
  opacity: 1;
  height: 100px;
  width: 100px;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  overflow: hidden;
  -webkit-transition: 1s all;
  -moz-transition: 1s all;
  -ms-transition: 1s all;
  -o-transition: 1s all;
  transition: 1s all;
}

<div class="fadebg">
    <div class="text">Hi</div>
    <div class="img"></div>
</div>
<br>
<div class="fadebg">
    <div class="text">Hi</div>
    <img src="https://upload.wikimedia.org/wikipedia/en/b/bc/Screenshot_Snarf.jpg">
</div>


问:
Webpacker, Yarn and capistrano, fsevents@1.1.1 error
I have a project that I recently migrate from rails 5.0 to rails 5.1, before this I had webpacker install and I deploy it with capistrano, in rails 5.0 everything was working, but when I did the change now capistrano is unable to finish the assets:precompile task and I get this error:

** DEPLOY FAILED
** Refer to log/capistrano.log for details. Here are the last 20 lines:
.....
DEBUG [04ae7a64] Command: cd /home/deploy/my-site/releases/20170602233846 && ( export RAILS_ENV="staging" ; ~/.rvm/bin/rvm default do bundle exec rake assets:precompile )

DEBUG [04ae7a64]   yarn install v0.24.5

DEBUG [04ae7a64]   [1/4] Resolving packages...

DEBUG [04ae7a64]   [2/4] Fetching packages...

DEBUG [04ae7a64]   warning fsevents@1.1.1: The platform "linux" is incompatible with this module.

DEBUG [04ae7a64]   info "fsevents@1.1.1" is an optional dependency and failed compatibility check. Excluding it from installation.

DEBUG [04ae7a64]   [3/4] Linking dependencies...

DEBUG [04ae7a64]   [4/4] Building fresh packages...

DEBUG [04ae7a64]   Done in 9.29s.

I'm using a local computer with ubuntu and ubuntu also is installed in the server.

I don't know where fsevents@1.1.1 is required as a dependency but I'm unabled to make deploy since 2 days ago and I haven't found a solution.

答:
EDIT: I think my original Webpacker installation must have gone wrong somehow. Using the master branch of webpacker and re-running bundle exec rake webpacker:install has fixed this issue.

Original Answer:
I came across this same error today. I think ./bin/yarn install --no-progress which is what the Rails rake task naturally runs, must return a non-zero exit code.

Firstly I tried overriding the yarn:install rake task to add --ignore-optional but this didn't work.

I have got my deployment to succeed by adding the rake task lib/tasks/yarn.rake containing:

```<code>namespace :yarn do
  desc "Install all JavaScript dependencies as specified via Yarn"
  task :install do
    puts "Ignoring yarn install failure"

    begin
      system "./bin/yarn install --no-progress --ignore-optional; true"
    rescue
      exit(true)
    end

    exit(true)
  end
end

task(:default).clear.enhance(['yarn:install'])

# Run Yarn prior to Sprockets assets precompilation, so dependencies are available for use.
if Rake::Task.task_defined?("assets:precompile")
  Rake::Task["assets:precompile"].enhance [ "yarn:install" ]
end
</code>```

This replaces Rails' default yarn install rake task to pretty much ensure any errors aren't caught by Capistrano. This isn't a good solution, but at least it gets the deployment to succeed. Hopefully a legitimate yarn install error would lead to another error later in the assets build.

Body:
EDIT: I think my original Webpacker installation must have gone wrong somehow. Using the master branch of webpacker and re-running bundle exec rake webpacker:install has fixed this issue.

Original Answer:
I came across this same error today. I think ./bin/yarn install --no-progress which is what the Rails rake task naturally runs, must return a non-zero exit code.

Firstly I tried overriding the yarn:install rake task to add --ignore-optional but this didn't work.

I have got my deployment to succeed by adding the rake task lib/tasks/yarn.rake containing:

namespace :yarn do
  desc "Install all JavaScript dependencies as specified via Yarn"
  task :install do
    puts "Ignoring yarn install failure"

    begin
      system "./bin/yarn install --no-progress --ignore-optional; true"
    rescue
      exit(true)
    end

    exit(true)
  end
end

task(:default).clear.enhance(['yarn:install'])

# Run Yarn prior to Sprockets assets precompilation, so dependencies are available for use.
if Rake::Task.task_defined?("assets:precompile")
  Rake::Task["assets:precompile"].enhance [ "yarn:install" ]
end

This replaces Rails' default yarn install rake task to pretty much ensure any errors aren't caught by Capistrano. This isn't a good solution, but at least it gets the deployment to succeed. Hopefully a legitimate yarn install error would lead to another error later in the assets build.


问:
Cannot resize tab control in Access 2016
I cannot resize the tab control in Access 2016. It is currently about 16 inches wide, and I need to make it 14 inches. I typed 14" in the Width property of the property window, but it resizes back to the original 16 inches. Would appreciate any help.

Thanks,
Howard Hong

答: I guess one of the other tabs have controls exceeding the 14". Check them.</p>


问:
Count frequency of words in multiple lists from a larger vocabulary?
I know how to count frequency of elements in a list but here's a lightly different question. I have a larger set of vocabulary and a few lists that only use part of the total vocabulary. Using numbers instead of words as an example:

```<code>vocab=[1,2,3,4,5,6,7]
list1=[1,2,3,4]
list2=[2,3,4,5,6,6,7]
list3=[3,2,4,4,1]
</code>```

and I want the output to keep "0"s when a word is not used:

```<code>count1=[1,1,1,1,0,0,0]
count2=[0,1,1,1,1,2,1]
count3=[1,1,1,2,0,0,0]
</code>```

I guess I need to sort the words, but how do I keep the "0" records?

答:
This can be done using the list object's inbuilt count function, within a list comprehension.

```<code>>>> vocab = [1, 2, 3, 4, 5, 6, 7]
>>> list1 = [1, 2, 3, 4]
>>> list2 = [2, 3, 4, 5, 6, 6, 7]
>>> list3 = [3, 2, 4, 4, 1]
>>> [list1.count(v) for v in vocab]
[1, 1, 1, 1, 0, 0, 0]
>>> [list2.count(v) for v in vocab]
[0, 1, 1, 1, 1, 2, 1]
>>> [list3.count(v) for v in vocab]
[1, 1, 1, 2, 0, 0, 0]
</code>```

Iterate over each value in vocab, accumulating the frequencies for them.

Body:
I know how to count frequency of elements in a list but here's a lightly different question. I have a larger set of vocabulary and a few lists that only use part of the total vocabulary. Using numbers instead of words as an example:

vocab=[1,2,3,4,5,6,7]
list1=[1,2,3,4]
list2=[2,3,4,5,6,6,7]
list3=[3,2,4,4,1]

and I want the output to keep "0"s when a word is not used:

count1=[1,1,1,1,0,0,0]
count2=[0,1,1,1,1,2,1]
count3=[1,1,1,2,0,0,0]

I guess I need to sort the words, but how do I keep the "0" records?

Body:
This can be done using the list object's inbuilt count function, within a list comprehension.

>>> vocab = [1, 2, 3, 4, 5, 6, 7]
>>> list1 = [1, 2, 3, 4]
>>> list2 = [2, 3, 4, 5, 6, 6, 7]
>>> list3 = [3, 2, 4, 4, 1]
>>> [list1.count(v) for v in vocab]
[1, 1, 1, 1, 0, 0, 0]
>>> [list2.count(v) for v in vocab]
[0, 1, 1, 1, 1, 2, 1]
>>> [list3.count(v) for v in vocab]
[1, 1, 1, 2, 0, 0, 0]

Iterate over each value in vocab, accumulating the frequencies for them.


问:
Ionic 2 with FCM Push notifications
I am using ionic 2

I installed the plugin

```<code>HTTP.post to FCM Server not working

cordova plugin add cordova-plugin-fcm
</code>```

Here is my code

```<code>import { Http, Headers } from '@angular/http';

someKey;
t;
constructor(public http: Http) {
      this.t="cwJHK1Ma-Mo:APA91bFRpBudeF9QhTosUs6-N7sSEW3D104cUO3M6gHFyTTDEodTWL5VVMbbbvqbhb5zkgRZwkIMC4p7PYbG7Pmfo6vb4IFB50ZTJN0W-2iJoJ-ZUdeBtcvjJ2nImflgUgtNplA210HP"
      this.someKey="AAAAbZuUvR8:APA91bF3-tKjl5FmXx...."
      let url = 'https://fcm.googleapis.com/fcm/send';
      let body =
       {
         "notification": {
             "title": "Notification title",
             "body": "Notification body",
             "sound": "default",
             "click_action": "FCM_PLUGIN_ACTIVITY",
             "icon": "fcm_push_icon"
         },
         "data": {
             "hello": "This is a Firebase Cloud Messagin  hbhj g Device Gr new v Message!",
         },
         "to": this.t
       };
    let headers: Headers = new Headers({
      'Content-Type': 'application/json',
      'Authorization': 'key='+this.someKey
    });
    let options = new RequestOptions({ headers: headers });

    console.log(JSON.stringify(headers));

      this.http.post(url, body, headers).map(response => {
        return response;
      }).subscribe(data => {
         //post doesn't fire if it doesn't get subscribed to
         console.log(data);
      });
 }
</code>```

But I am getting this err

console tells error to be The request was missing an Authentification Key (FCM Token). Please, refer to section "Authentification" of the FCM documentation, at firebase.google.com/docs/cloud-messaging/server. Error 401

```<code>EXCEPTION: Response with status: 401 OK for URL: https://fcm.googleapis.com/fcm/send
</code>```

How can i fix this issue.

Kindly advice me,

Thanks.

答: Hey man I use the https://firebase.google.com/docs/cloud-messaging/admin/send-messages it's easier and you don't have to handle manually the requests. </p>

Title: Ionic 2 with FCM Push notifications

Body:
I am using ionic 2

I installed the plugin

HTTP.post to FCM Server not working

cordova plugin add cordova-plugin-fcm

Here is my code

import { Http, Headers } from '@angular/http';

someKey;
t;
constructor(public http: Http) {
      this.t="cwJHK1Ma-Mo:APA91bFRpBudeF9QhTosUs6-N7sSEW3D104cUO3M6gHFyTTDEodTWL5VVMbbbvqbhb5zkgRZwkIMC4p7PYbG7Pmfo6vb4IFB50ZTJN0W-2iJoJ-ZUdeBtcvjJ2nImflgUgtNplA210HP"
      this.someKey="AAAAbZuUvR8:APA91bF3-tKjl5FmXx...."
      let url = 'https://fcm.googleapis.com/fcm/send';
      let body =
       {
         "notification": {
             "title": "Notification title",
             "body": "Notification body",
             "sound": "default",
             "click_action": "FCM_PLUGIN_ACTIVITY",
             "icon": "fcm_push_icon"
         },
         "data": {
             "hello": "This is a Firebase Cloud Messagin  hbhj g Device Gr new v Message!",
         },
         "to": this.t
       };
    let headers: Headers = new Headers({
      'Content-Type': 'application/json',
      'Authorization': 'key='+this.someKey
    });
    let options = new RequestOptions({ headers: headers });

    console.log(JSON.stringify(headers));

      this.http.post(url, body, headers).map(response => {
        return response;
      }).subscribe(data => {
         //post doesn't fire if it doesn't get subscribed to
         console.log(data);
      });
 }

But I am getting this err

console tells error to be The request was missing an Authentification Key (FCM Token). Please, refer to section "Authentification" of the FCM documentation, at firebase.google.com/docs/cloud-messaging/server. Error 401

EXCEPTION: Response with status: 401 OK for URL: https://fcm.googleapis.com/fcm/send

How can i fix this issue.

Kindly advice me,

Thanks.


问:
Split a string into a String[] of a specific size
Assuming my delimiter is ',' (comma), I'm looking for a function split that will guarantee that the returned String[] array is a certain size (no more, no less):

```<code>String[] split(String str, int limit);

split("hello", 2);               => ["hello", ""]
split("hello,", 2);              => ["hello", ""]
split(",hello", 2);              => ["", "hello"]
split("hello,world", 2);         => ["hello", "world"]
split("hello,world,goodbye", 2); => ["hello", "world,goodbye"]
</code>```

See how the array size is always 2? I can get some of this behavior with Pattern.split, but not for every case... How can I do this?

答:
You can use Arrays.copyOf() to return a padded array. However, the padding will be null instead of an empty string.

```<code>String[] parts = Arrays.copyOf("hello,".split(",", 2), 2);
String[] parts1 = Arrays.copyOf(",hello".split(",", 2), 2);
String[] parts2 = Arrays.copyOf("hello,world".split(",", 2), 2);
String[] parts3 = Arrays.copyOf("hello,world,goodbye".split(",", 2), 2);
String[] parts4 = Arrays.copyOf("hello,".split(",", 2), 4); //null padding
</code>```

Body:
Assuming my delimiter is ',' (comma), I'm looking for a function split that will guarantee that the returned String[] array is a certain size (no more, no less):

String[] split(String str, int limit);

split("hello", 2);               => ["hello", ""]
split("hello,", 2);              => ["hello", ""]
split(",hello", 2);              => ["", "hello"]
split("hello,world", 2);         => ["hello", "world"]
split("hello,world,goodbye", 2); => ["hello", "world,goodbye"]

See how the array size is always 2? I can get some of this behavior with Pattern.split, but not for every case... How can I do this?

Body:
You can use Arrays.copyOf() to return a padded array. However, the padding will be null instead of an empty string.

String[] parts = Arrays.copyOf("hello,".split(",", 2), 2);
String[] parts1 = Arrays.copyOf(",hello".split(",", 2), 2);
String[] parts2 = Arrays.copyOf("hello,world".split(",", 2), 2);
String[] parts3 = Arrays.copyOf("hello,world,goodbye".split(",", 2), 2);
String[] parts4 = Arrays.copyOf("hello,".split(",", 2), 4); //null padding