问:
SQL: columns name based on variable
I have a temporary table aaa that I use as an array.

```<code>    USE tempdb
    GO

    IF OBJECT_ID('tempdb..aaa') IS NOT NULL DROP TABLE aaa
    CREATE TABLE aaa (
        #1 char(40),
        #2 char(40),
        #3 char(40)
    );
    insert into aaa values ('aaaa','qqqq','eeee');
    declare @sql varchar(40);
    declare @var varchar(40)='#3';
    set @sql= '(select '+@var +' from aaa)';
       print @sql;
</code>```

What I'm trying to achieve is to store into the variable @sql the executed value of '(select '+@var +' from aaa)' which is: eeee and NOT simply the string (select #3 from aaa)

I know that ''this is not how SQL is supposed to work'' but after 320 questions read on SO(my history tab can prove) I'm out of ideas:)

答:
[1] tempdb..aaa isn't a temp table. Instead, it's nothing more than a standard table created within tempdb database and this means that will deleted when SQL Server Database Engine service is restarted (tempdb database is recreated everytime the service is started/restarted).

[2] If you want to use a temp table then you could use following syntax:

```<code>CREATE TABLE #Array (RowNum INT NOT NULL, Val AS VARCHAR(10)) -- See # prefix that means a local temp table
</code>```

or

```<code>CREATE TABLE ##Array (RowNum INT NOT NULL, Val AS VARCHAR(10)) -- See ## prefix that means a global temp table
</code>```

Example:

```<code>INSERT #Array (RowNum, Val) VALUES (1, 'A')
INSERT #Array (RowNum, Val) VALUES (2, 'BBB')
</code>```

and

```<code>SELECT ... FROM #Array WHERE RowNum = 1
</code>```

To see full list of all options for storing/using arrays in SQL Server see following article wrote by Erland Sommarskog http://www.sommarskog.se/arrays-in-sql.html . My personal choice will be to use XML or @table variable.

[3] Regarding approach proposed by current question: it is bad. Assuming that we have to simulate an array then values from that array should be stored (if we are using tables / ##temp tables / @table variables) within single column on rows (see above example) and not in different columns (Col1, Col2, etc.).

My recommendation is to read Erland Sommarskog's article and to select proper solution for your scenario.

Title: SQL: columns name based on variable

Body:
I have a temporary table aaa that I use as an array.

    USE tempdb
    GO

    IF OBJECT_ID('tempdb..aaa') IS NOT NULL DROP TABLE aaa
    CREATE TABLE aaa (
        #1 char(40),
        #2 char(40),
        #3 char(40)
    );
    insert into aaa values ('aaaa','qqqq','eeee');
    declare @sql varchar(40);
    declare @var varchar(40)='#3';
    set @sql= '(select '+@var +' from aaa)';
       print @sql;

What I'm trying to achieve is to store into the variable @sql the executed value of '(select '+@var +' from aaa)' which is: eeee and NOT simply the string (select #3 from aaa)

I know that ''this is not how SQL is supposed to work'' but after 320 questions read on SO(my history tab can prove) I'm out of ideas:)

Body:
[1] tempdb..aaa isn't a temp table. Instead, it's nothing more than a standard table created within tempdb database and this means that will deleted when SQL Server Database Engine service is restarted (tempdb database is recreated everytime the service is started/restarted).

[2] If you want to use a temp table then you could use following syntax:

CREATE TABLE #Array (RowNum INT NOT NULL, Val AS VARCHAR(10)) -- See # prefix that means a local temp table

or

CREATE TABLE ##Array (RowNum INT NOT NULL, Val AS VARCHAR(10)) -- See ## prefix that means a global temp table

Example:

INSERT #Array (RowNum, Val) VALUES (1, 'A')
INSERT #Array (RowNum, Val) VALUES (2, 'BBB')

and

SELECT ... FROM #Array WHERE RowNum = 1

To see full list of all options for storing/using arrays in SQL Server see following article wrote by Erland Sommarskog http://www.sommarskog.se/arrays-in-sql.html . My personal choice will be to use XML or @table variable.

[3] Regarding approach proposed by current question: it is bad. Assuming that we have to simulate an array then values from that array should be stored (if we are using tables / ##temp tables / @table variables) within single column on rows (see above example) and not in different columns (Col1, Col2, etc.).

My recommendation is to read Erland Sommarskog's article and to select proper solution for your scenario.


来源: stackexchange

问:
Converting a n dimension list to several DataFrames in Python
I have an array of lists I want to convert to DataFrames. For instance the following array :

```<code>[[{'count': 6L, 'eclipse_id': 11348}, {'count': 1L, 'eclipse_id': 11338},
{'count': 1L, 'eclipse_id': 11342}, {'count': 1L, 'eclipse_id': 11361},
{'count': 6L, 'eclipse_id': 11313}],
[[{'count': 1L, 'eclipse_id': 11374},{'count': 1L, 'eclipse_id': 11356},
{'count': 1L, 'eclipse_id': 11358}]]
</code>```

The expected output

It would be several arrays according to the list within the list :

First array :

```<code>    count  eclipse_id
0       6     11348.0
1       1     11338.0
2       1     11342.0
3       1     11361.0
4       6     11313.0
</code>```

Second array :

```<code>    count  eclipse_id
0       1     11374.0
1       1     11356.0
2       1     11358.0
</code>```

It would be even more wonderful if it were sorted !

My attempt

This is what I tried :

```<code>i = 0
for liste in listeGroupContentReactions:
    df_n[i] = pd.DataFrame(liste)
    i+1
</code>```

Yet it answered me ValueError: Wrong number of items passed 2, placement implies 1. The full error is the following :

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-64-851a5559a58d> in <module>()
      6 i = 0
      7 for liste in listeGroupContentReactions:
----> 8     df_n[i] = pd.DataFrame(liste)
      9     i+1
     10

/home/antoine/anaconda2/lib/python2.7/site-packages/pandas/core/frame.pyc in __setitem__(self, key, value)
   2427         else:
   2428             # set column
-> 2429             self._set_item(key, value)
   2430
   2431     def _setitem_slice(self, key, value):

/home/antoine/anaconda2/lib/python2.7/site-packages/pandas/core/frame.pyc in _set_item(self, key, value)
   2494         self._ensure_valid_index(value)
   2495         value = self._sanitize_column(key, value)
-> 2496         NDFrame._set_item(self, key, value)
   2497
   2498         # check if we are modifying a copy

/home/antoine/anaconda2/lib/python2.7/site-packages/pandas/core/generic.pyc in _set_item(self, key, value)
   1646
   1647     def _set_item(self, key, value):
-> 1648         self._data.set(key, value)
   1649         self._clear_item_cache()
   1650

/home/antoine/anaconda2/lib/python2.7/site-packages/pandas/core/internals.pyc in set(self, item, value, check)
   3716         except KeyError:
   3717             # This item wasn't present, just insert at end
-> 3718             self.insert(len(self.items), item, value)
   3719             return
   3720

/home/antoine/anaconda2/lib/python2.7/site-packages/pandas/core/internals.pyc in insert(self, loc, item, value, allow_duplicates)
   3817
   3818         block = make_block(values=value, ndim=self.ndim,
-> 3819                            placement=slice(loc, loc + 1))
   3820
   3821         for blkno, count in _fast_count_smallints(self._blknos[loc:]):

/home/antoine/anaconda2/lib/python2.7/site-packages/pandas/core/internals.pyc in make_block(values, placement, klass, ndim, dtype, fastpath)
   2717                      placement=placement, dtype=dtype)
   2718
-> 2719     return klass(values, ndim=ndim, fastpath=fastpath, placement=placement)
   2720
   2721 # TODO: flexible with index=None and/or items=None

/home/antoine/anaconda2/lib/python2.7/site-packages/pandas/core/internals.pyc in __init__(self, values, placement, ndim, fastpath)
    113             raise ValueError('Wrong number of items passed %d, placement '
    114                              'implies %d' % (len(self.values),
--> 115                                              len(self.mgr_locs)))
    116
    117     @property

ValueError: Wrong number of items passed 2, placement implies 1
</code>```

A "clinical" approach that worked

I tried this way :

```<code>df_n_0 = pd.DataFrame(listeGroupContentReactions[0])
</code>```

It worked but how can I make it iterate over the listeGroupContentReactions

答:
If you're sure you want to loop-append the data instead of clean the initial list:

```<code>values = [[{'count': 6L, 'eclipse_id': 11348},
           {'count': 1L, 'eclipse_id': 11338},
           {'count': 1L, 'eclipse_id': 11342},
           {'count': 1L, 'eclipse_id': 11361},
           {'count': 6L, 'eclipse_id': 11313}],
          [{'count': 754L, 'eclipse_id': 15428},
           {'count': 1L, 'eclipse_id': 11258},
           {'count': 1L, 'eclipse_id': 11342},
           {'count': 1L, 'eclipse_id': 14233},
           {'count': 6L, 'eclipse_id': 11313}]]

# This inits a DataFrame with the first value
df = pd.DataFrame(values[0])

# And this cycles the data appending to the first DataFrame
for value in values[1:]:
    df = df.append(pd.DataFrame(value), ignore_index=True)
</code>```

To create a list of dataframes you only have to do:

```<code>dfs = []

for value in values:
    dfs.append(pd.DataFrame(value))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an array of lists I want to convert to DataFrames. For instance the following array :

[[{'count': 6L, 'eclipse_id': 11348}, {'count': 1L, 'eclipse_id': 11338},
{'count': 1L, 'eclipse_id': 11342}, {'count': 1L, 'eclipse_id': 11361},
{'count': 6L, 'eclipse_id': 11313}],
[[{'count': 1L, 'eclipse_id': 11374},{'count': 1L, 'eclipse_id': 11356},
{'count': 1L, 'eclipse_id': 11358}]]

The expected output

It would be several arrays according to the list within the list :

First array :

    count  eclipse_id
0       6     11348.0
1       1     11338.0
2       1     11342.0
3       1     11361.0
4       6     11313.0

Second array :

    count  eclipse_id
0       1     11374.0
1       1     11356.0
2       1     11358.0

It would be even more wonderful if it were sorted !

My attempt

This is what I tried :

i = 0
for liste in listeGroupContentReactions:
    df_n[i] = pd.DataFrame(liste)
    i+1

Yet it answered me ValueError: Wrong number of items passed 2, placement implies 1. The full error is the following :

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-64-851a5559a58d> in <module>()
      6 i = 0
      7 for liste in listeGroupContentReactions:
----> 8     df_n[i] = pd.DataFrame(liste)
      9     i+1
     10

/home/antoine/anaconda2/lib/python2.7/site-packages/pandas/core/frame.pyc in __setitem__(self, key, value)
   2427         else:
   2428             # set column
-> 2429             self._set_item(key, value)
   2430
   2431     def _setitem_slice(self, key, value):

/home/antoine/anaconda2/lib/python2.7/site-packages/pandas/core/frame.pyc in _set_item(self, key, value)
   2494         self._ensure_valid_index(value)
   2495         value = self._sanitize_column(key, value)
-> 2496         NDFrame._set_item(self, key, value)
   2497
   2498         # check if we are modifying a copy

/home/antoine/anaconda2/lib/python2.7/site-packages/pandas/core/generic.pyc in _set_item(self, key, value)
   1646
   1647     def _set_item(self, key, value):
-> 1648         self._data.set(key, value)
   1649         self._clear_item_cache()
   1650

/home/antoine/anaconda2/lib/python2.7/site-packages/pandas/core/internals.pyc in set(self, item, value, check)
   3716         except KeyError:
   3717             # This item wasn't present, just insert at end
-> 3718             self.insert(len(self.items), item, value)
   3719             return
   3720

/home/antoine/anaconda2/lib/python2.7/site-packages/pandas/core/internals.pyc in insert(self, loc, item, value, allow_duplicates)
   3817
   3818         block = make_block(values=value, ndim=self.ndim,
-> 3819                            placement=slice(loc, loc + 1))
   3820
   3821         for blkno, count in _fast_count_smallints(self._blknos[loc:]):

/home/antoine/anaconda2/lib/python2.7/site-packages/pandas/core/internals.pyc in make_block(values, placement, klass, ndim, dtype, fastpath)
   2717                      placement=placement, dtype=dtype)
   2718
-> 2719     return klass(values, ndim=ndim, fastpath=fastpath, placement=placement)
   2720
   2721 # TODO: flexible with index=None and/or items=None

/home/antoine/anaconda2/lib/python2.7/site-packages/pandas/core/internals.pyc in __init__(self, values, placement, ndim, fastpath)
    113             raise ValueError('Wrong number of items passed %d, placement '
    114                              'implies %d' % (len(self.values),
--> 115                                              len(self.mgr_locs)))
    116
    117     @property

ValueError: Wrong number of items passed 2, placement implies 1

A "clinical" approach that worked

I tried this way :

df_n_0 = pd.DataFrame(listeGroupContentReactions[0])

It worked but how can I make it iterate over the listeGroupContentReactions

Body:
If you're sure you want to loop-append the data instead of clean the initial list:

values = [[{'count': 6L, 'eclipse_id': 11348},
           {'count': 1L, 'eclipse_id': 11338},
           {'count': 1L, 'eclipse_id': 11342},
           {'count': 1L, 'eclipse_id': 11361},
           {'count': 6L, 'eclipse_id': 11313}],
          [{'count': 754L, 'eclipse_id': 15428},
           {'count': 1L, 'eclipse_id': 11258},
           {'count': 1L, 'eclipse_id': 11342},
           {'count': 1L, 'eclipse_id': 14233},
           {'count': 6L, 'eclipse_id': 11313}]]

# This inits a DataFrame with the first value
df = pd.DataFrame(values[0])

# And this cycles the data appending to the first DataFrame
for value in values[1:]:
    df = df.append(pd.DataFrame(value), ignore_index=True)

To create a list of dataframes you only have to do:

dfs = []

for value in values:
    dfs.append(pd.DataFrame(value))


问:
Fluent NHibernate QueryOver to select items not in another table (left join)
I have two tables:

all:
id | propA | propB | someOtherColumn

hidden:
id | propA | propB

and corresponding classes (Mapped, no relationship mapped yet)

I would like to get all rows from first table, minus any results which match by propA or propB property.

I managed to do it by Criteria API but would like to see how it is done with QueryOver API, if possible without subqueries but with a left excluding join.

Criteria version:

```<code>var dc1 = DetachedCriteria.For<hidden>()
    .Add(Restrictions.IsNotNull(Projections.Property("propA")))
    .SetProjection(Projections.Property("propA"));

var dc2 = DetachedCriteria.For<hidden>()
    .Add(Restrictions.IsNotNull(Projections.Property("propB")))
    .SetProjection(Projections.Property("propB"));

var query = db
    .CreateCriteria<all>()
    .Add(Restrictions.On<all>(c => c.someOtherColumn).IsLike("1"))
    .Add(Subqueries.PropertyNotIn("propA", dc1))
    .Add(Subqueries.PropertyNotIn("propB", dc2))
</code>```

which gives roughly:

```<code>SELECT all.*
FROM all
WHERE (all.someOtherColumn LIKE '1')
    and all.propA not in (SELECT hidden.propA FROM hidden WHERE hidden.propA IS NOT NULL)
    and all.propB not in (SELECT hidden.propB FROM hidden WHERE hidden.propB IS NOT NULL)
</code>```

It is ok, though it seems performance wise this would be better:

```<code>SELECT all.*
FROM all
LEFT JOIN hidden ON all.propA = hidden.propA
LEFT JOIN hidden ON all.propB = hidden.propB
WHERE hidden.propA IS NULL
AND hidden.propB IS NULL
AND (all.someOtherColumn LIKE '1')
</code>```

If it is not possible to generate such a statement with unmapped relationships, I am open to suggestions on mapping.

答:
It seems to me that it's not possible to create joins without mapped relationships via QueryOver.
See this answer.

With subqueries you can do something like this:

```<code>All allAlias = null;
var result = Session.QueryOver(() => allAlias)
               .WhereRestrictionOn(x => x.someOtherColumn).IsLike('1')
               .WithSubquery.WhereNotExists(QueryOver.Of<hidden>()
                     .Where(h => h.propA == allAlias.propB || h.propB == allAlias.propB)
                     .Select(h => h.Id))
               .List();
</code>```

Body:
I have two tables:

all:
id | propA | propB | someOtherColumn

hidden:
id | propA | propB

and corresponding classes (Mapped, no relationship mapped yet)

I would like to get all rows from first table, minus any results which match by propA or propB property.

I managed to do it by Criteria API but would like to see how it is done with QueryOver API, if possible without subqueries but with a left excluding join.

Criteria version:

var dc1 = DetachedCriteria.For<hidden>()
    .Add(Restrictions.IsNotNull(Projections.Property("propA")))
    .SetProjection(Projections.Property("propA"));

var dc2 = DetachedCriteria.For<hidden>()
    .Add(Restrictions.IsNotNull(Projections.Property("propB")))
    .SetProjection(Projections.Property("propB"));

var query = db
    .CreateCriteria<all>()
    .Add(Restrictions.On<all>(c => c.someOtherColumn).IsLike("1"))
    .Add(Subqueries.PropertyNotIn("propA", dc1))
    .Add(Subqueries.PropertyNotIn("propB", dc2))

which gives roughly:

SELECT all.*
FROM all
WHERE (all.someOtherColumn LIKE '1')
    and all.propA not in (SELECT hidden.propA FROM hidden WHERE hidden.propA IS NOT NULL)
    and all.propB not in (SELECT hidden.propB FROM hidden WHERE hidden.propB IS NOT NULL)

It is ok, though it seems performance wise this would be better:

SELECT all.*
FROM all
LEFT JOIN hidden ON all.propA = hidden.propA
LEFT JOIN hidden ON all.propB = hidden.propB
WHERE hidden.propA IS NULL
AND hidden.propB IS NULL
AND (all.someOtherColumn LIKE '1')

If it is not possible to generate such a statement with unmapped relationships, I am open to suggestions on mapping.

Body:
It seems to me that it's not possible to create joins without mapped relationships via QueryOver.
See this answer.

With subqueries you can do something like this:

All allAlias = null;
var result = Session.QueryOver(() => allAlias)
               .WhereRestrictionOn(x => x.someOtherColumn).IsLike('1')
               .WithSubquery.WhereNotExists(QueryOver.Of<hidden>()
                     .Where(h => h.propA == allAlias.propB || h.propB == allAlias.propB)
                     .Select(h => h.Id))
               .List();


问:
Jetty - java.lang.IllegalStateException: zip file closed
I'm getting some error with some connection to our web server.

I saw that a bug causing this was solved in Jetty 7.6. Yes we get this error on our application running under Jetty 7.5.4 but we also get this with another apps running on a newer version 9.

Do you have any idea what this can be?

We are getting this error randomly:

```<code>java.lang.IllegalStateException: zip file closed
    at java.util.zip.ZipFile.ensureOpen(ZipFile.java:632)
    at java.util.zip.ZipFile.access$200(ZipFile.java:56)
    at java.util.zip.ZipFile$1.hasMoreElements(ZipFile.java:485)
    at java.util.jar.JarFile$1.hasMoreElements(JarFile.java:239)
    at org.eclipse.jetty.util.resource.JarFileResource.exists(JarFileResource.java:163)
    at org.eclipse.jetty.webapp.WebAppContext$Context.getResource(WebAppContext.java:1223)
    at org.eclipse.jetty.servlet.DefaultServlet.getResource(DefaultServlet.java:366)
    at org.eclipse.jetty.server.ResourceCache.lookup(ResourceCache.java:188)
    at org.eclipse.jetty.servlet.DefaultServlet.doGet(DefaultServlet.java:445)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:547)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:480)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:119)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:483)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:227)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:941)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:409)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:186)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:875)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117)
    at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:219)
    at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:149)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:110)
    at org.eclipse.jetty.server.Server.handle(Server.java:345)
    at org.eclipse.jetty.server.HttpConnection.handleRequest(HttpConnection.java:441)
    at org.eclipse.jetty.server.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:919)
    at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:582)
    at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:218)
    at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:51)
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:586)
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:44)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:598)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:533)
    at java.lang.Thread.run(Thread.java:722)
</code>```

答: I was having the same issue because of the actual WAR being corrupt. Try rerunning mvn clean install and redeploy.

Body:
I'm getting some error with some connection to our web server.

I saw that a bug causing this was solved in Jetty 7.6. Yes we get this error on our application running under Jetty 7.5.4 but we also get this with another apps running on a newer version 9.

Do you have any idea what this can be?

We are getting this error randomly:

java.lang.IllegalStateException: zip file closed
    at java.util.zip.ZipFile.ensureOpen(ZipFile.java:632)
    at java.util.zip.ZipFile.access$200(ZipFile.java:56)
    at java.util.zip.ZipFile$1.hasMoreElements(ZipFile.java:485)
    at java.util.jar.JarFile$1.hasMoreElements(JarFile.java:239)
    at org.eclipse.jetty.util.resource.JarFileResource.exists(JarFileResource.java:163)
    at org.eclipse.jetty.webapp.WebAppContext$Context.getResource(WebAppContext.java:1223)
    at org.eclipse.jetty.servlet.DefaultServlet.getResource(DefaultServlet.java:366)
    at org.eclipse.jetty.server.ResourceCache.lookup(ResourceCache.java:188)
    at org.eclipse.jetty.servlet.DefaultServlet.doGet(DefaultServlet.java:445)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:547)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:480)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:119)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:483)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:227)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:941)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:409)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:186)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:875)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117)
    at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:219)
    at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:149)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:110)
    at org.eclipse.jetty.server.Server.handle(Server.java:345)
    at org.eclipse.jetty.server.HttpConnection.handleRequest(HttpConnection.java:441)
    at org.eclipse.jetty.server.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:919)
    at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:582)
    at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:218)
    at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:51)
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:586)
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:44)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:598)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:533)
    at java.lang.Thread.run(Thread.java:722)


问:
How to show the widget same like an Alarm widget (Clock APP)?
I need to do the app same as Clock Alarm functionality. Once we set the Alarm for some time like 3.15PM (Even app is not in running state) It shows in

Today Notification screen -

we can do this(your alarm......) using APP Extension (using User defaults), right?

As Pop up screen

Alarm Pop Up in lock screen -

My Question -

a. How can we achieve both 2 and 3, Is this a same APP Extension concept?

b. In First - I believe they used User defaults, Can we do the API access in APP Extension like checking web service periodically?

Please suggest solution/idea to achieve this.

Thanks!

答: No, this is not the same thing as an app extension or widget. I also, don't believe its possible to do what you are trying to do. </p>


问:
Stacking dynamically growing divs on each other without spaces between them
I want to stack divs one after other without any space in between them but i've failed to do this. I've tried this on table and tried all methods to remove spacing between rows of a table but I failed. Now I am trying to implement the same with divs and I am unable to achieve the desired output. Below is my code.

```<code>    @model IEnumerable<Fast_Tally_Accounter.Models.CPVBase>
<p style="background-image:url('../../viewData/vcr_header.png'); background-repeat:no-repeat; border:0">
</p>
@if (Model != null)
{
    foreach (var v in Model)
    {
        <div class="row" style="margin-left:120px;background-image:url('../../viewData/vcr_row.png'); background-repeat:no-repeat;">

            <div class="col-lg-12">
                <div class="col-lg-6">
                    <p style="padding-top:inherit;">@v.headText</p>
                </div>
                <div class="col-lg-4">
                    <p style="padding-top:inherit; margin-left:5px;">@v.amount</p>
                </div>
            </div>

        </div>
    }
}
<div class="row" style="margin-left:120px;margin-top:-30px;background-image:url('../../viewData/vcr_total_footer.png'); background-repeat:no-repeat">
    <div class="col-lg-12">
        <p style="margin-left:450px;">@ViewBag.total</p>
    </div>
</div>
</code>```

this is what the above code looks like on a browser
click here to open the image

答:
It its Bootstrap then the nesting of elements is incorrect. Class "col" must be immediate child of "row". Also the sum of sizes of col must be 12 in one row. You have 6 + 4 i.e. 10. Make it col-lg-8 and col-lg-4 to fill the entire row.

Try changing this -

```<code><div class="col-lg-12">
            <div class="col-lg-6">
                <p style="padding-top:inherit;">@v.headText</p>
            </div>
            <div class="col-lg-4">
                <p style="padding-top:inherit; margin-left:5px;">@v.amount</p>
            </div>
        </div>
</code>```

to this - (Basically, remove the col-lg-12 div and the corresponding closing div)

```<code><div class="col-lg-8">
    <p>@v.headText</p>
</div>
<div class="col-lg-4">
    <p>@v.amount</p>
</div>
</code>```

Body:
I want to stack divs one after other without any space in between them but i've failed to do this. I've tried this on table and tried all methods to remove spacing between rows of a table but I failed. Now I am trying to implement the same with divs and I am unable to achieve the desired output. Below is my code.

    @model IEnumerable<Fast_Tally_Accounter.Models.CPVBase>

@if (Model != null)
{
    foreach (var v in Model)
    {

@v.headText

@v.amount

    }
}

@ViewBag.total

this is what the above code looks like on a browser
click here to open the image

Body:
It its Bootstrap then the nesting of elements is incorrect. Class "col" must be immediate child of "row". Also the sum of sizes of col must be 12 in one row. You have 6 + 4 i.e. 10. Make it col-lg-8 and col-lg-4 to fill the entire row.

Try changing this -

<div class="col-lg-12">
            <div class="col-lg-6">
                <p style="padding-top:inherit;">@v.headText</p>
            </div>
            <div class="col-lg-4">
                <p style="padding-top:inherit; margin-left:5px;">@v.amount</p>
            </div>
        </div>

to this - (Basically, remove the col-lg-12 div and the corresponding closing div)

<div class="col-lg-8">
    <p>@v.headText</p>
</div>
<div class="col-lg-4">
    <p>@v.amount</p>
</div>


问:
.htaccess redirect single domain to https instead of all domains (aliases) redirected
I have example.com and alias sub.example.com pointing to the same directory. I want all http://example.com redirect to https://example.com, but keep sub.example.com non-ssl

Here is what I try, but it is not redirecting example.com to https:

```<code>RewriteCond %{HTTPS} off
RewriteRule ^(http:\/\/example\.com.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</code>```

What am i doing wrong?

答:
RewriteRule doesn't match domain name. You will need to use a RewriteCond for that like this:

```<code>RewriteCond %{HTTP_HOST} ^(?:www\.)?example\.com$ [NC]
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
</code>```

Body:
I have example.com and alias sub.example.com pointing to the same directory. I want all http://example.com redirect to https://example.com, but keep sub.example.com non-ssl

Here is what I try, but it is not redirecting example.com to https:

RewriteCond %{HTTPS} off
RewriteRule ^(http:\/\/example\.com.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

What am i doing wrong?

Body:
RewriteRule doesn't match domain name. You will need to use a RewriteCond for that like this:

RewriteCond %{HTTP_HOST} ^(?:www\.)?example\.com$ [NC]
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]


问:
Catching thread exceptions from Java ExecutorService
I'm working on a software development framework for parallel computing JavaSeis.org. I need a robust mechanism for reporting thread exceptions. During development, knowing where exceptions came from has high value, so I would like to err on the side of over-reporting. I would also like to be able to handle Junit4 testing in threads as well. Is the approach below reasonable or is there a better way ?</p>

```<code>import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TestThreadFailure {

  public static void main(String[] args) {
    int size = 1;
    ExecutorService exec = Executors.newFixedThreadPool(size);
    ThreadFailTask worker = new ThreadFailTask();
    Future<Integer> result = exec.submit(worker);
    try {
      Integer value = result.get();
      System.out.println("Result: " + value);
    } catch (Throwable t) {
      System.out.println("Caught failure: " + t.toString());
      exec.shutdownNow();
      System.out.println("Stack Trace:");
      t.printStackTrace();
      return;
    }
    throw new RuntimeException("Did not catch failure !!");
  }

  public static class ThreadFailTask implements Callable<Integer> {
    @Override
    public Integer call() {
      int nbuf = 65536;
      double[][] buf = new double[nbuf][nbuf];
      return new Integer((int) buf[0][0]);
    }
  }
}
</code>```

答:
As explained in this thread What is the difference between submit and execute method with ThreadPoolExecutor, using execute will only work if you implement Runnable and not Callable as execute cannot return a Future.

I think in your scenario you should build the future object so that it can accommodate the exception stuff also. So in case of exception you build the error message object.

ContentLicense: CC BY-SA 2.5

Body:
I'm working on a software development framework for parallel computing JavaSeis.org. I need a robust mechanism for reporting thread exceptions. During development, knowing where exceptions came from has high value, so I would like to err on the side of over-reporting. I would also like to be able to handle Junit4 testing in threads as well. Is the approach below reasonable or is there a better way ?

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TestThreadFailure {

  public static void main(String[] args) {
    int size = 1;
    ExecutorService exec = Executors.newFixedThreadPool(size);
    ThreadFailTask worker = new ThreadFailTask();
    Future<Integer> result = exec.submit(worker);
    try {
      Integer value = result.get();
      System.out.println("Result: " + value);
    } catch (Throwable t) {
      System.out.println("Caught failure: " + t.toString());
      exec.shutdownNow();
      System.out.println("Stack Trace:");
      t.printStackTrace();
      return;
    }
    throw new RuntimeException("Did not catch failure !!");
  }

  public static class ThreadFailTask implements Callable<Integer> {
    @Override
    public Integer call() {
      int nbuf = 65536;
      double[][] buf = new double[nbuf][nbuf];
      return new Integer((int) buf[0][0]);
    }
  }
}


问:
Mathjax show formula expression on web edited by ckeditor
I add Mathjax to my ckeditor and editor some formula expression, but I can only show these formula expression code when I show these formula expression on another place.

This is what I edit on my ckeditor:

This is what it show on my web:

答: Use mathjax js in your web. it converts tex to formula view</p>


问:
Switch between R and Stata in Markdown
It is possible to generate Stata output with markdown in Rstudio, by spcifying the following in the script:

```<code>```{r}
statapath <- "C:/Program Files (x86)/Stata13/StataSE-64.exe"
opts_chunk$set(engine="stata", engine.path=statapath, comment="")
```
</code>```

After that, it is possible to use Stata syntax to generate the output.

Is it possible to switch back to R for some code chunks, then switch back to Stata again?

The reason is that I use Stata for regression (tables), but R for most of the other things I do. So a functionality like this would come in handy for me.

I tried:

```<code>```{r}
rpath <- "C:/Program Files/RStudio/bin/rstudio.exe"
opts_chunk$set(engine="R", engine.path=rpath, comment="")
```
</code>```

It did not work.

答: If you just skip the engine.path in the R code chunk, it should work.  You can easily switch between languages.</p>

Title: Switch between R and Stata in Markdown

Body:
It is possible to generate Stata output with markdown in Rstudio, by spcifying the following in the script:

```{r}
statapath <- "C:/Program Files (x86)/Stata13/StataSE-64.exe"
opts_chunk$set(engine="stata", engine.path=statapath, comment="")
```

After that, it is possible to use Stata syntax to generate the output.

Is it possible to switch back to R for some code chunks, then switch back to Stata again?

The reason is that I use Stata for regression (tables), but R for most of the other things I do. So a functionality like this would come in handy for me.

I tried:

```{r}
rpath <- "C:/Program Files/RStudio/bin/rstudio.exe"
opts_chunk$set(engine="R", engine.path=rpath, comment="")
```

It did not work.


问:
HasMap inserting null values instead of string?
Below is my code which I am trying to read the excel data using Apache POI and want to store the first column and last column values in Hashmap by taking First column values as keys and last column as values. I am facing an issue while putting the values in the hashmap. My expected output should be like

```<code>Key         value
UserDefined Xpath_original
seldriver   xpath;//div[@id='mBody']
Selenium    xpath;//table[@id='choice']/tbody/tr/td[1]/ul/li[1]
</code>```

but I am getting the output as

*

```<code>null null
null
null xpath;//div[@id='mBody']
</code>```

*
Below is my piece of code

```<code>package com.selenium.common;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

public class ReadMacroExcel {
public static void main(String[] args) {
 try {

         File f=new File("C:\\Users\\Rajaram.8.Kannuri\\Downloads\\Fire-IEBrowser1.4.xlsm");
         HashMap <String,String> innerMap =null;
         Workbook workbook = WorkbookFactory.create(f);
         System.out.println(workbook);
         int numberOfSheets = workbook.getNumberOfSheets();
         org.apache.poi.ss.usermodel.Sheet sheet=null;
         String key = "";
         String value = "";
         //Get the  sheet in the xlsx file
         for (int i = 0; i < numberOfSheets; i++) {
             sheet = workbook.getSheetAt(i);
             System.out.println(sheet.getSheetName());
             int firstColumn = sheet.getRow(0).getFirstCellNum();
             int lastColumn = sheet.getRow(0).getLastCellNum();
             Iterator<Row> rowIterator = sheet.iterator();
             innerMap = new HashMap<String,String>();
             while(rowIterator.hasNext())
             {
                     Row row = rowIterator.next();

                     Iterator<Cell> cellIterator = row.cellIterator();

                     while (cellIterator.hasNext())
                     {

                         Cell cell = cellIterator.next();

                         if(cell.getColumnIndex()==firstColumn||cell.getColumnIndex()==lastColumn-1)
                         {

                             switch (cell.getCellType())
                             {
                                 case Cell.CELL_TYPE_STRING:
                                         key = cell.getStringCellValue();
                                         /*System.out.print(key + "\t");*/
                                        /* Thread.sleep(5000);*/
                                 break;
                                 case Cell.CELL_TYPE_FORMULA:
                                        value = cell.getRichStringCellValue().toString();
                                        /*System.out.print(value + "\t");*/
                                        /*Thread.sleep(5000);*/
                                 break;
                              }
                            System.out.print(innerMap.put(key,value));
                         }

                     }

                     System.out.println("");

                 }
           /*  System.out.println(innerMap.get("UserDefined"));*/
             }

     }
     catch (Exception e)
     {
         e.printStackTrace();
     }

    }
}
</code>```

Can any one help me in solving this issue??

答:
It seems that you are trying to print the inserted value with

```<code>System.out.print(innerMap.put(key,value));
</code>```

However, put returns the previous value associated with the given key, or null if there was no mapping for that key.

See also https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#put-K-V-

You should use something like

```<code>innerMap.put(key,value);               // add the new mapping to the hashmap
System.out.print(innerMap);            // dumps the complete map with all entries
System.out.print(innerMap.get(key));   // dumps the value for the recently inserted key
</code>```

Body:
Below is my code which I am trying to read the excel data using Apache POI and want to store the first column and last column values in Hashmap by taking First column values as keys and last column as values. I am facing an issue while putting the values in the hashmap. My expected output should be like

Key         value
UserDefined Xpath_original
seldriver   xpath;//div[@id='mBody']
Selenium    xpath;//table[@id='choice']/tbody/tr/td[1]/ul/li[1]

but I am getting the output as

*

null null
null
null xpath;//div[@id='mBody']

*
Below is my piece of code

package com.selenium.common;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

public class ReadMacroExcel {
public static void main(String[] args) {
 try {

         File f=new File("C:\\Users\\Rajaram.8.Kannuri\\Downloads\\Fire-IEBrowser1.4.xlsm");
         HashMap <String,String> innerMap =null;
         Workbook workbook = WorkbookFactory.create(f);
         System.out.println(workbook);
         int numberOfSheets = workbook.getNumberOfSheets();
         org.apache.poi.ss.usermodel.Sheet sheet=null;
         String key = "";
         String value = "";
         //Get the  sheet in the xlsx file
         for (int i = 0; i < numberOfSheets; i++) {
             sheet = workbook.getSheetAt(i);
             System.out.println(sheet.getSheetName());
             int firstColumn = sheet.getRow(0).getFirstCellNum();
             int lastColumn = sheet.getRow(0).getLastCellNum();
             Iterator<Row> rowIterator = sheet.iterator();
             innerMap = new HashMap<String,String>();
             while(rowIterator.hasNext())
             {
                     Row row = rowIterator.next();

                     Iterator<Cell> cellIterator = row.cellIterator();

                     while (cellIterator.hasNext())
                     {

                         Cell cell = cellIterator.next();

                         if(cell.getColumnIndex()==firstColumn||cell.getColumnIndex()==lastColumn-1)
                         {

                             switch (cell.getCellType())
                             {
                                 case Cell.CELL_TYPE_STRING:
                                         key = cell.getStringCellValue();
                                         /*System.out.print(key + "\t");*/
                                        /* Thread.sleep(5000);*/
                                 break;
                                 case Cell.CELL_TYPE_FORMULA:
                                        value = cell.getRichStringCellValue().toString();
                                        /*System.out.print(value + "\t");*/
                                        /*Thread.sleep(5000);*/
                                 break;
                              }
                            System.out.print(innerMap.put(key,value));
                         }

                     }

                     System.out.println("");

                 }
           /*  System.out.println(innerMap.get("UserDefined"));*/
             }

     }
     catch (Exception e)
     {
         e.printStackTrace();
     }

    }
}

Can any one help me in solving this issue??

Body:
It seems that you are trying to print the inserted value with

System.out.print(innerMap.put(key,value));

However, put returns the previous value associated with the given key, or null if there was no mapping for that key.

See also https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#put-K-V-

You should use something like

innerMap.put(key,value);               // add the new mapping to the hashmap
System.out.print(innerMap);            // dumps the complete map with all entries
System.out.print(innerMap.get(key));   // dumps the value for the recently inserted key


问:
Issue while setting up a spring maven project in eclipse
I want to set up a maven based spring project using eclipse. The following code block shows the content of my pom.xml file:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>MyLearningProject</groupId>
<artifactId>MyLearningProject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
        <plugin>
            <artifactId>maven-war-plugin</artifactId>
            <version>3.0.0</version>
            <configuration>
                <warSourceDirectory>WebContent</warSourceDirectory>
            </configuration>
        </plugin>
    </plugins>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>3.0-alpha-1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
    </dependencies>
</build>
</code>```

I'm getting the following error but don't know why:

cvc-complex-type.2.4.a: Invalid content was found starting with
  element 'dependencies'.

答:
Your pom is incorrect. You put <dependencies> to <build> section and that's why you get an error.

Try to move <dependencies> from <build> section, so your pom will be something like that:

```<code><dependencies>
    ...
</dependencies>

<build>
    ...
</build>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to set up a maven based spring project using eclipse. The following code block shows the content of my pom.xml file:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>MyLearningProject</groupId>
<artifactId>MyLearningProject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
        <plugin>
            <artifactId>maven-war-plugin</artifactId>
            <version>3.0.0</version>
            <configuration>
                <warSourceDirectory>WebContent</warSourceDirectory>
            </configuration>
        </plugin>
    </plugins>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>3.0-alpha-1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
    </dependencies>
</build>

I'm getting the following error but don't know why:

cvc-complex-type.2.4.a: Invalid content was found starting with
  element 'dependencies'.

Body:
Your pom is incorrect. You put <dependencies> to <build> section and that's why you get an error.

Try to move <dependencies> from <build> section, so your pom will be something like that:

<dependencies>
    ...
</dependencies>

<build>
    ...
</build>


问:
Iterating grib tools over a folder of grib files
I am attempting to mass-convert a large number of GRIB files to netCDF using grib tools (I am on Windows 7) in a batch file.

I am using this code:

```<code>for /f %%f in (`dir /b O:\Praksa\incadata\2014\01\01`)
   do
     echo %%f grib_to_netcdf -D NC_FLOAT -o *.nc *.grb
</code>```

But when I run it nothing seems to happen except for CMD opening and closing really fast.

There is probably some syntax error I missed in there, but my main question is: Can I use wildcards (*) in grib tools statements?
Also, are spaces in directory pathnames problematic?

Thanks!

答:
You got the syntax wrong. cmd is very picky about syntax. Try this:

```<code>@echo off
for /f %%A in ('dir /b /a-d z:\*') do (
     echo %%~fA grib_to_netcdf -D NC_FLOAT -o %%~dpnA.nc %%~dpnA.grb
)
</code>```

%%~fA gives you the full qualified filename, %~dpnA the Drive, Path and Name only. See for /? for those modifiers. dir /a-d excludes foldernames. See dir /? for more info.

Body:
I am attempting to mass-convert a large number of GRIB files to netCDF using grib tools (I am on Windows 7) in a batch file.

I am using this code:

for /f %%f in (`dir /b O:\Praksa\incadata\2014\01\01`)
   do
     echo %%f grib_to_netcdf -D NC_FLOAT -o *.nc *.grb

But when I run it nothing seems to happen except for CMD opening and closing really fast.

There is probably some syntax error I missed in there, but my main question is: Can I use wildcards (*) in grib tools statements?
Also, are spaces in directory pathnames problematic?

Thanks!

Body:
You got the syntax wrong. cmd is very picky about syntax. Try this:

@echo off
for /f %%A in ('dir /b /a-d z:\*') do (
     echo %%~fA grib_to_netcdf -D NC_FLOAT -o %%~dpnA.nc %%~dpnA.grb
)

%%~fA gives you the full qualified filename, %~dpnA the Drive, Path and Name only. See for /? for those modifiers. dir /a-d excludes foldernames. See dir /? for more info.


问:
How to get and update last string after some character like '\ ' in python dataframe
How to split df['FullString'] and get the last phrase after '\' then update to df['Splitted']?

df:

```<code>FullString                          Splitted
2\0\2\0\R\A\T\I\O\0\0\0123456789    0123456789
2\0\2\0\R\A\T\I\O\0\0\25632589      25632589
</code>```

答:
You can use vectorised str.rsplit to achieve this:

```<code>In[81]:
df['Splitted'] = df['FullString'].str.rsplit('\\').str[-1]
df

Out[81]:
                         FullString   Splitted
0  2\0\2\0\R\A\T\I\O\0\0\0123456789  0123456789
1    2\0\2\0\R\A\T\I\O\0\0\25632589   25632589
</code>```

Body:
How to split df['FullString'] and get the last phrase after '\' then update to df['Splitted']?

df:

FullString                          Splitted
2\0\2\0\R\A\T\I\O\0\0\0123456789    0123456789
2\0\2\0\R\A\T\I\O\0\0\25632589      25632589

Body:
You can use vectorised str.rsplit to achieve this:

In[81]:
df['Splitted'] = df['FullString'].str.rsplit('\\').str[-1]
df

Out[81]:
                         FullString   Splitted
0  2\0\2\0\R\A\T\I\O\0\0\0123456789  0123456789
1    2\0\2\0\R\A\T\I\O\0\0\25632589   25632589


问:
How to use data from the localstorage in angular 2
How to use data from the localstorage for the another component. Localstorage in service are:

localStorage.setItem('currentUser', JSON.stringify({ username: username, token: success,res:res.data}));

I want to use id, username etc from the data in another component How it possible

答:
Try like this.</p>

```<code>    let currentUser = localStorage.getItem( 'currentUser' );
    this.token = JSON.parse( currentUser )['token'];
    this.username = JSON.parse( currentUser )['username'];
</code>```

Body:
Try like this.

    let currentUser = localStorage.getItem( 'currentUser' );
    this.token = JSON.parse( currentUser )['token'];
    this.username = JSON.parse( currentUser )['username'];


问:
What version of TLS is used in a .NET application installed on different operating systems
Say I have a standard .NET (4.5) web application that needs to connect to a secure server using TLS.

I want to stop supporting unused or weak protocols and cipher suites in my server and support only the ones which the client also supports (preferably TLS 1.2)

Does the version of TLS (1.0, 1.1 or 1.2) and/or cipher suites in use depend on the operation system or the .NET version?

In other words, will my .NET application use a different cipher suite or TLS version when installed on machines with different Operating systems / updates? Or does the usage of .NET 4.5 ensures that the protocols on every client-server communication will be identical?

答:
This is a much better answer than what i could write on the .NET question:
https://stackoverflow.com/a/28333370/4148708

In essence:

.NET 4.0 supports up to TLS 1.0 while .NET 4.5 supports up to TLS 1.2

In practice i've seen both .NET 4.5 and .NET 4.6 default to TLS 1.0 if you're not imperative about it:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
```

<s>Can't comment on .NET 4.7 but i would assume it still handshakes TLS 1.0 by default so the whole Internet doesn't suddenly break.</s>
.NET 4.7 uses whatever the OS default is through the SystemDefaultTlsVersions registry key (thanks Panagiotis Kanavos) — more findings in this repo.

What that really means is for .NET 4.7, ServicePointManager.SecurityProtocol now returns SystemDefault.

On the OS question, yes, .NET calls into SCHANNEL, which is Microsoft's Security Support Provider (think the "OpenSSL" of the Windows world). As long as you're running on Windows Server 2008 R2+, you are good for TLS 1.2.

Extract from this comprehensive blog post (blogs.msdn.microsoft.com):

Some further research (my own) available here —

https://github.com/snobu/tls-negotiations

Body:
This is a much better answer than what i could write on the .NET question:
https://stackoverflow.com/a/28333370/4148708

In essence:

.NET 4.0 supports up to TLS 1.0 while .NET 4.5 supports up to TLS 1.2

In practice i've seen both .NET 4.5 and .NET 4.6 default to TLS 1.0 if you're not imperative about it:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

<s>Can't comment on .NET 4.7 but i would assume it still handshakes TLS 1.0 by default so the whole Internet doesn't suddenly break.</s>
.NET 4.7 uses whatever the OS default is through the SystemDefaultTlsVersions registry key (thanks Panagiotis Kanavos) — more findings in this repo.

What that really means is for .NET 4.7, ServicePointManager.SecurityProtocol now returns SystemDefault.

On the OS question, yes, .NET calls into SCHANNEL, which is Microsoft's Security Support Provider (think the "OpenSSL" of the Windows world). As long as you're running on Windows Server 2008 R2+, you are good for TLS 1.2.

Extract from this comprehensive blog post (blogs.msdn.microsoft.com):

Some further research (my own) available here —

https://github.com/snobu/tls-negotiations


问:
Python convert list where one element has XYZ values to 3 integers
So I have a list of values where each element contains an x,y,z value.

Im trying to take a list of one element and find the distance between that element and a list of other elements. So List A has a main point and then there is a list B of other points I'm trying to find the distance to.

Example:

```<code>Listofpoints: [(6, 7, 2), (6, 1, 2), (7, 3, 7), (7, 1, 3), (6, 0, 3)]
MainPoint= [(4,2,3)]
distance =  mainpoint and all points in Listofpoints
</code>```

Any help is greatly appreciated.

答:
I don't know if I have fully understood your goal, but if I do, I think you just overcomplicated your code. What do you mean with distance between "an element and a list"? Assuming you need a list of distances between the element of list A and each element of list B, here is some code. </p>

```<code>def distance(point_a,point_b):
    d=0
    for e in range(0,3):
        d+=(point_a[e]-point_b[e])**2
    return d**(1/2)
def foo(list_A,list_B):
    l=[]
    el0=list_A[0]
    for el in list_B:
        l.append(distance(el0,el))
    return l
foo(list_A,list_B)
</code>```

<p>I didn't look in your code because I can't understand why you're using numpy for this simple task, why you're using random.sample and other stuff. </p>

Body:
So I have a list of values where each element contains an x,y,z value.

Im trying to take a list of one element and find the distance between that element and a list of other elements. So List A has a main point and then there is a list B of other points I'm trying to find the distance to.

Example:

Listofpoints: [(6, 7, 2), (6, 1, 2), (7, 3, 7), (7, 1, 3), (6, 0, 3)]
MainPoint= [(4,2,3)]
distance =  mainpoint and all points in Listofpoints

Any help is greatly appreciated.

Body:
I don't know if I have fully understood your goal, but if I do, I think you just overcomplicated your code. What do you mean with distance between "an element and a list"? Assuming you need a list of distances between the element of list A and each element of list B, here is some code.

def distance(point_a,point_b):
    d=0
    for e in range(0,3):
        d+=(point_a[e]-point_b[e])**2
    return d**(1/2)
def foo(list_A,list_B):
    l=[]
    el0=list_A[0]
    for el in list_B:
        l.append(distance(el0,el))
    return l
foo(list_A,list_B)

I didn't look in your code because I can't understand why you're using numpy for this simple task, why you're using random.sample and other stuff.


问:
RewriteRule redirects to unexpected page
I am trying to change my url through .htaccess in the following way

```<code>Original URL: http://www.example.com/latest-news.php?id=2/topic=testing
Rewritten URL:http://www.example.com/2/testing
Rule for .htaccess
RewriteRule ^([^/]*)/([^/]*)$ /latest-news.php?id=$1&topic=$2 [L]
</code>```

This is working fine but the other files which are existing in a folder are not opening. The url is opening as www.example.com/testing/foo.php but content of the page is of http://www.example.com/2/testing

答:
Can you try with a similar rule like the one bellow?

```<code>RewriteRule ^([0-9]+)/([a-zA-Z])$ /latest-news.php?id=$1&topic=$2 [L]
</code>```

Can't really test it on my server but you can adapt it to suit your needs

Body:
I am trying to change my url through .htaccess in the following way

Original URL: http://www.example.com/latest-news.php?id=2/topic=testing
Rewritten URL:http://www.example.com/2/testing
Rule for .htaccess
RewriteRule ^([^/]*)/([^/]*)$ /latest-news.php?id=$1&topic=$2 [L]

This is working fine but the other files which are existing in a folder are not opening. The url is opening as www.example.com/testing/foo.php but content of the page is of http://www.example.com/2/testing

Body:
Can you try with a similar rule like the one bellow?

RewriteRule ^([0-9]+)/([a-zA-Z])$ /latest-news.php?id=$1&topic=$2 [L]

Can't really test it on my server but you can adapt it to suit your needs


问:
Vertically centered text in a dynamic height wrapper
I'd normally just use line-height for vertical centering, but on this occasion the layout I'm working to is a little trickier.

I've put together this jsfiddle to show where I'm at so far. All the CSS hacks suggest using table-cell trickery for this but I can only get it to work if the wrapper has an absolute height, so for me this text isn't vertically centered:

```<code><div class="wrap">
    <a href="#">
        <img src="http://www.thekrausemouse.com/wp-content/uploads/2016/03/sample-1.jpg" />
        <span class="text"><span>Text that might span multiple lines</span></span>
    </a>
</div>
</code>```

https://jsfiddle.net/fdtbvmcw/

What I basically need is for the text, regardless of how many lines it spans, to sit in the middle of the image. The image can't be a background-image and I can't attach fixed widths or heights to the wrapper.

The wrapper is simulating a responsive column within a bigger page template and I need the image to retain full width of that column you see. Other HTML can be added within the column if need be.

Thoughts?

答:
I would also use flex for your solution.</p>

```<code>.wrap a .text {
  height: 100%;
  left: 0;
  position: absolute;
  text-align: center;
  top:0;
  display: flex;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  justify-content: center;
  align-items: center;
}
</code>```

Body:
I'd normally just use line-height for vertical centering, but on this occasion the layout I'm working to is a little trickier.

I've put together this jsfiddle to show where I'm at so far. All the CSS hacks suggest using table-cell trickery for this but I can only get it to work if the wrapper has an absolute height, so for me this text isn't vertically centered:

        Text that might span multiple lines

https://jsfiddle.net/fdtbvmcw/

What I basically need is for the text, regardless of how many lines it spans, to sit in the middle of the image. The image can't be a background-image and I can't attach fixed widths or heights to the wrapper.

The wrapper is simulating a responsive column within a bigger page template and I need the image to retain full width of that column you see. Other HTML can be added within the column if need be.

Thoughts?

Body:
I would also use flex for your solution.

.wrap a .text {
  height: 100%;
  left: 0;
  position: absolute;
  text-align: center;
  top:0;
  display: flex;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  justify-content: center;
  align-items: center;
}


问:
Update...Set...From...Where query is affecting all rows and not specific ones
The below query should only affect the row titled 'F0085'. However, it has affected all the rows. Setting the address to 'test' on every Job_No.

```<code>UPDATE TBTest.dbo.Site
SET Address ='FDAN'
FROM Jobs
WHERE Job_No = 'F0085'
</code>```

This is the first table:

答:
Your syntax is wrong. Since your update depends on other table, you need to join them. Try:

```<code>UPDATE t
SET
t.Address = 'FDAN'
FROM
TBTest.dbo.Site t
INNER JOIN JOBS j
ON t.Job_No = j.Job_No
WHERE j.Job_No = 'F0085'
</code>```

Body:
The below query should only affect the row titled 'F0085'. However, it has affected all the rows. Setting the address to 'test' on every Job_No.

UPDATE TBTest.dbo.Site
SET Address ='FDAN'
FROM Jobs
WHERE Job_No = 'F0085'

This is the first table:

Body:
Your syntax is wrong. Since your update depends on other table, you need to join them. Try:

UPDATE t
SET
t.Address = 'FDAN'
FROM
TBTest.dbo.Site t
INNER JOIN JOBS j
ON t.Job_No = j.Job_No
WHERE j.Job_No = 'F0085'


问:
Plot equally spaced markers along a spiral
I want to move a red star marker along the spiral trajectory with an equal distance of 5 units between the red star points on its circumference like in the below image.

```<code>vertspacing = 10;
horzspacing = 10;
thetamax = 10*pi;
% Calculation of (x,y) - underlying archimedean spiral.
b = vertspacing/2/pi;
theta = 0:0.01:thetamax;
x = b*theta.*cos(theta)+50;
y = b*theta.*sin(theta)+50;

% Calculation of equidistant (xi,yi) points on spiral.
smax = 0.5*b*thetamax.*thetamax;
s = 0:horzspacing:smax;
thetai = sqrt(2*s/b);
xi = b*thetai.*cos(thetai);
yi = b*thetai.*sin(thetai);
plot(x,y,'b-');
hold on
</code>```

I want to get a figure that looks like the following:

This is my code for the circle trajectory:

```<code>% Initialization steps.
format long g;
format compact;
fontSize = 20;
r1 = 50;
r2 = 35;
r3=  20;
xc = 50;
yc = 50;
% Since arclength = radius * (angle in radians),
% (angle in radians) = arclength / radius = 5 / radius.
deltaAngle1 = 5 / r1;
deltaAngle2 = 5 / r2;
deltaAngle3 = 5 / r3;
theta1 = 0 : deltaAngle1 : (2 * pi);
theta2 = 0 : deltaAngle2 : (2 * pi);
theta3 = 0 : deltaAngle3 : (2 * pi);
x1 = r1*cos(theta1) + xc;
y1 = r1*sin(theta1) + yc;
x2 = r2*cos(theta2) + xc;
y2 = r2*sin(theta2) + yc;
x3 = r3*cos(theta3) + xc;
y3 = r3*sin(theta3) + yc;
plot(x1,y1,'color',[1 0.5 0])
hold on
plot(x2,y2,'color',[1 0.5 0])
hold on
plot(x3,y3,'color',[1 0.5 0])
hold on

% Connecting Line:
plot([70 100], [50 50],'color',[1 0.5 0])
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0, 0, 1, 1]);
drawnow;
axis square;
for i = 1 : length(theta1)
    plot(x1(i),y1(i),'r*')
    pause(0.1)
end
for i = 1 : length(theta2)
    plot(x2(i),y2(i),'r*')
    pause(0.1)
end
for i = 1 : length(theta3)
    plot(x3(i),y3(i),'r*')
    pause(0.1)
end
</code>```

答:
I can't think of a way to compute distance along a spiral, so I'm approximating it with circles, in hopes that it will still be useful.

My solution relies on the InterX function from FEX, to find the intersection of circles with the spiral. I am providing an animation so it is easier to understand.

The code (tested on R2017a):

```<code>function [x,y,xi,yi] = q44916610(doPlot)
%% Input handling:
if nargin < 1 || isempty(doPlot)
  doPlot = false;
end
%% Initialization:
origin = [50,50];
vertspacing = 10;
thetamax = 5*(2*pi);
%% Calculation of (x,y) - underlying archimedean spiral.
b = vertspacing/(2*pi);
theta = 0:0.01:thetamax;
x = b*theta.*cos(theta) + origin(1);
y = b*theta.*sin(theta) + origin(2);
%% Calculation of equidistant (xi,yi) points on spiral.
DST = 5; cRes = 360;
numPts = ceil(vertspacing*thetamax); % Preallocation
[xi,yi] = deal(NaN(numPts,1));

if doPlot && isHG2() % Plots are only enabled if the MATLAB version is new enough.
  figure(); plot(x,y,'b-'); hold on; axis equal; grid on; grid minor;
  hAx = gca; hAx.XLim = [-5 105]; hAx.YLim = [-5 105];
  hP = plot(xi,yi,'r*');
else
  hP = struct('XData',xi,'YData',yi);
end
hP.XData(1) = origin(1); hP.YData(1) = origin(2);
for ind = 2:numPts
  P = InterX([x;y], makeCircle([hP.XData(ind-1),hP.YData(ind-1)],DST/2,cRes));
  [~,I] = max(abs(P(1,:)-origin(1)+1i*(P(2,:)-origin(2))));
  if doPlot, pause(0.1); end
  hP.XData(ind) = P(1,I); hP.YData(ind) = P(2,I);
  if doPlot, pause(0.1); delete(hAx.Children(1)); end
end
xi = hP.XData(~isnan(hP.XData)); yi = hP.YData(~isnan(hP.YData));

%% Nested function(s):
function [XY] = makeCircle(cnt, R, nPts)
  P = (cnt(1)+1i*cnt(2))+R*exp(linspace(0,1,nPts)*pi*2i);
  if doPlot, plot(P,'Color',lines(1)); end
  XY = [real(P); imag(P)];
end

end

%% Local function(s):
function tf = isHG2()
  try
    tf = ~verLessThan('MATLAB', '8.4');
  catch
    tf = false;
  end
end

function P = InterX(L1,varargin)
    % DOCUMENTATION REMOVED. For a full version go to:
    % https://www.mathworks.com/matlabcentral/fileexchange/22441-curve-intersections

    narginchk(1,2);
    if nargin == 1
        L2 = L1;    hF = @lt;   %...Avoid the inclusion of common points
    else
        L2 = varargin{1}; hF = @le;
    end

    %...Preliminary stuff
    x1  = L1(1,:)';  x2 = L2(1,:);
    y1  = L1(2,:)';  y2 = L2(2,:);
    dx1 = diff(x1); dy1 = diff(y1);
    dx2 = diff(x2); dy2 = diff(y2);

    %...Determine 'signed distances'
    S1 = dx1.*y1(1:end-1) - dy1.*x1(1:end-1);
    S2 = dx2.*y2(1:end-1) - dy2.*x2(1:end-1);

    C1 = feval(hF,D(bsxfun(@times,dx1,y2)-bsxfun(@times,dy1,x2),S1),0);
    C2 = feval(hF,D((bsxfun(@times,y1,dx2)-bsxfun(@times,x1,dy2))',S2'),0)';

    %...Obtain the segments where an intersection is expected
    [i,j] = find(C1 & C2);
    if isempty(i), P = zeros(2,0); return; end

    %...Transpose and prepare for output
    i=i'; dx2=dx2'; dy2=dy2'; S2 = S2';
    L = dy2(j).*dx1(i) - dy1(i).*dx2(j);
    i = i(L~=0); j=j(L~=0); L=L(L~=0);  %...Avoid divisions by 0

    %...Solve system of eqs to get the common points
    P = unique([dx2(j).*S1(i) - dx1(i).*S2(j), ...
                dy2(j).*S1(i) - dy1(i).*S2(j)]./[L L],'rows')';

    function u = D(x,y)
        u = bsxfun(@minus,x(:,1:end-1),y).*bsxfun(@minus,x(:,2:end),y);
    end
end
</code>```

Result:

Note that in the animation above, the diameter of the circle (and hence the distance between the red points) is 10 and not 5.

Body:
I want to move a red star marker along the spiral trajectory with an equal distance of 5 units between the red star points on its circumference like in the below image.

vertspacing = 10;
horzspacing = 10;
thetamax = 10*pi;
% Calculation of (x,y) - underlying archimedean spiral.
b = vertspacing/2/pi;
theta = 0:0.01:thetamax;
x = b*theta.*cos(theta)+50;
y = b*theta.*sin(theta)+50;

% Calculation of equidistant (xi,yi) points on spiral.
smax = 0.5*b*thetamax.*thetamax;
s = 0:horzspacing:smax;
thetai = sqrt(2*s/b);
xi = b*thetai.*cos(thetai);
yi = b*thetai.*sin(thetai);
plot(x,y,'b-');
hold on

I want to get a figure that looks like the following:

This is my code for the circle trajectory:

% Initialization steps.
format long g;
format compact;
fontSize = 20;
r1 = 50;
r2 = 35;
r3=  20;
xc = 50;
yc = 50;
% Since arclength = radius * (angle in radians),
% (angle in radians) = arclength / radius = 5 / radius.
deltaAngle1 = 5 / r1;
deltaAngle2 = 5 / r2;
deltaAngle3 = 5 / r3;
theta1 = 0 : deltaAngle1 : (2 * pi);
theta2 = 0 : deltaAngle2 : (2 * pi);
theta3 = 0 : deltaAngle3 : (2 * pi);
x1 = r1*cos(theta1) + xc;
y1 = r1*sin(theta1) + yc;
x2 = r2*cos(theta2) + xc;
y2 = r2*sin(theta2) + yc;
x3 = r3*cos(theta3) + xc;
y3 = r3*sin(theta3) + yc;
plot(x1,y1,'color',[1 0.5 0])
hold on
plot(x2,y2,'color',[1 0.5 0])
hold on
plot(x3,y3,'color',[1 0.5 0])
hold on

% Connecting Line:
plot([70 100], [50 50],'color',[1 0.5 0])
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0, 0, 1, 1]);
drawnow;
axis square;
for i = 1 : length(theta1)
    plot(x1(i),y1(i),'r*')
    pause(0.1)
end
for i = 1 : length(theta2)
    plot(x2(i),y2(i),'r*')
    pause(0.1)
end
for i = 1 : length(theta3)
    plot(x3(i),y3(i),'r*')
    pause(0.1)
end

Body:
I can't think of a way to compute distance along a spiral, so I'm approximating it with circles, in hopes that it will still be useful.

My solution relies on the InterX function from FEX, to find the intersection of circles with the spiral. I am providing an animation so it is easier to understand.

The code (tested on R2017a):

function [x,y,xi,yi] = q44916610(doPlot)
%% Input handling:
if nargin < 1 || isempty(doPlot)
  doPlot = false;
end
%% Initialization:
origin = [50,50];
vertspacing = 10;
thetamax = 5*(2*pi);
%% Calculation of (x,y) - underlying archimedean spiral.
b = vertspacing/(2*pi);
theta = 0:0.01:thetamax;
x = b*theta.*cos(theta) + origin(1);
y = b*theta.*sin(theta) + origin(2);
%% Calculation of equidistant (xi,yi) points on spiral.
DST = 5; cRes = 360;
numPts = ceil(vertspacing*thetamax); % Preallocation
[xi,yi] = deal(NaN(numPts,1));

if doPlot && isHG2() % Plots are only enabled if the MATLAB version is new enough.
  figure(); plot(x,y,'b-'); hold on; axis equal; grid on; grid minor;
  hAx = gca; hAx.XLim = [-5 105]; hAx.YLim = [-5 105];
  hP = plot(xi,yi,'r*');
else
  hP = struct('XData',xi,'YData',yi);
end
hP.XData(1) = origin(1); hP.YData(1) = origin(2);
for ind = 2:numPts
  P = InterX([x;y], makeCircle([hP.XData(ind-1),hP.YData(ind-1)],DST/2,cRes));
  [~,I] = max(abs(P(1,:)-origin(1)+1i*(P(2,:)-origin(2))));
  if doPlot, pause(0.1); end
  hP.XData(ind) = P(1,I); hP.YData(ind) = P(2,I);
  if doPlot, pause(0.1); delete(hAx.Children(1)); end
end
xi = hP.XData(~isnan(hP.XData)); yi = hP.YData(~isnan(hP.YData));

%% Nested function(s):
function [XY] = makeCircle(cnt, R, nPts)
  P = (cnt(1)+1i*cnt(2))+R*exp(linspace(0,1,nPts)*pi*2i);
  if doPlot, plot(P,'Color',lines(1)); end
  XY = [real(P); imag(P)];
end

end

%% Local function(s):
function tf = isHG2()
  try
    tf = ~verLessThan('MATLAB', '8.4');
  catch
    tf = false;
  end
end

function P = InterX(L1,varargin)
    % DOCUMENTATION REMOVED. For a full version go to:
    % https://www.mathworks.com/matlabcentral/fileexchange/22441-curve-intersections

    narginchk(1,2);
    if nargin == 1
        L2 = L1;    hF = @lt;   %...Avoid the inclusion of common points
    else
        L2 = varargin{1}; hF = @le;
    end

    %...Preliminary stuff
    x1  = L1(1,:)';  x2 = L2(1,:);
    y1  = L1(2,:)';  y2 = L2(2,:);
    dx1 = diff(x1); dy1 = diff(y1);
    dx2 = diff(x2); dy2 = diff(y2);

    %...Determine 'signed distances'
    S1 = dx1.*y1(1:end-1) - dy1.*x1(1:end-1);
    S2 = dx2.*y2(1:end-1) - dy2.*x2(1:end-1);

    C1 = feval(hF,D(bsxfun(@times,dx1,y2)-bsxfun(@times,dy1,x2),S1),0);
    C2 = feval(hF,D((bsxfun(@times,y1,dx2)-bsxfun(@times,x1,dy2))',S2'),0)';

    %...Obtain the segments where an intersection is expected
    [i,j] = find(C1 & C2);
    if isempty(i), P = zeros(2,0); return; end

    %...Transpose and prepare for output
    i=i'; dx2=dx2'; dy2=dy2'; S2 = S2';
    L = dy2(j).*dx1(i) - dy1(i).*dx2(j);
    i = i(L~=0); j=j(L~=0); L=L(L~=0);  %...Avoid divisions by 0

    %...Solve system of eqs to get the common points
    P = unique([dx2(j).*S1(i) - dx1(i).*S2(j), ...
                dy2(j).*S1(i) - dy1(i).*S2(j)]./[L L],'rows')';

    function u = D(x,y)
        u = bsxfun(@minus,x(:,1:end-1),y).*bsxfun(@minus,x(:,2:end),y);
    end
end

Result:

Note that in the animation above, the diameter of the circle (and hence the distance between the red points) is 10 and not 5.


问:
How to sort a Map by value in multi layer
Here is the map with the following structure:

```<code>Map<String, Oddcurve> curves;

class Oddcurve entends Curve {
    private String curvename;
}

class Curve {
    private int curveId;
    protected Set<CurvePoint> points = new TreeSet();
}

class CurvePoint {
    private double time;
    private double value;
}
</code>```

I want to sort the curves by the time ASC, and finally return still the same map :

```<code>proxyCurves.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue));
</code>```

I write in this way, When i debug it, I can see that the sorting works fine, but finally still returns the original curves, I don't know why?

```<code>proxyCurves.values().stream().forEach(curve -> curve.setPoints(curve.getPoints().stream().sorted(new ComparableComparator<>()).collect(Collectors.toSet())));
</code>```

答:
This is the code I use to solve the problem:</p>

```<code>curves.values().stream().forEach(
            curve -> {
                final Set<CurvePoint> sortedPoints = new TreeSet<>(
                        (curvePoint1, curvePoint2) -> Double.compare(curvePoint1.getTime(), curvePoint2.getTime()));
                sortedPoints.addAll(curve.getPoints());
                curve.setPoints(sortedPoints);
            });
</code>```

Body:
Here is the map with the following structure:

Map<String, Oddcurve> curves;

class Oddcurve entends Curve {
    private String curvename;
}

class Curve {
    private int curveId;
    protected Set<CurvePoint> points = new TreeSet();
}

class CurvePoint {
    private double time;
    private double value;
}

I want to sort the curves by the time ASC, and finally return still the same map :

proxyCurves.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue));

I write in this way, When i debug it, I can see that the sorting works fine, but finally still returns the original curves, I don't know why?

proxyCurves.values().stream().forEach(curve -> curve.setPoints(curve.getPoints().stream().sorted(new ComparableComparator<>()).collect(Collectors.toSet())));

Body:
This is the code I use to solve the problem:

curves.values().stream().forEach(
            curve -> {
                final Set<CurvePoint> sortedPoints = new TreeSet<>(
                        (curvePoint1, curvePoint2) -> Double.compare(curvePoint1.getTime(), curvePoint2.getTime()));
                sortedPoints.addAll(curve.getPoints());
                curve.setPoints(sortedPoints);
            });


问:
Is using __cplusplus undefined behaviour in C?
Modern C++ compilers are required by the standard to #define the macro __cplusplus.

This is often used in files that can be used by both C and C++ but the implementation differs slightly.

But in C (and C++ for that matter), the behaviour on using any double underscore in an identifier is undefined!

So therefore, if a C compiler sees something like

#ifdef __cplusplus

then is the behaviour undefined?

答:
But in C (and C++ for that matter), the behaviour on using any double underscore in an identifier is undefined!

You're mixing things up. It's not undefined behavior to use one, it's just that the names are reserved. The key point is you can't define some yourself, but it's fine to use them.

From ISO 9899:2011:

7.1.3 Reserved identifiers

— All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.


问:
read/write access violation c++ using libfreenect2
I'm a newbe to C++ and started fooling around with my Kinect V2 and libfreenect2.
The building of the library worked fine for me, I guess. But when I try to use it in my code I get some weird exceptions.

```<code>Freenect2 freenect2;
std::string serial="";
Freenect2Device *dev = 0;

freenect2.enumerateDevices();
serial = freenect2.getDefaultDeviceSerialNumber();
dev = freenect2.openDevice(serial);
</code>```

Everytime I run this code, it fails at getting the serial number [serial = freenect2.getDefaultDeviceSerialNumber();] with:

"Unhandled exception thrown: read access violation.

_Pnext was 0xFFFFFFFFFFFFFFFF."

In case I'm using

```<code>Freenect2 freenect2;
Freenect2Device *dev = 0;
SyncMultiFrameListener listener(Frame::Color);
FrameMap frames;

freenect2.enumerateDevices();
dev = freenect2.openDefaultDevice();
dev->setColorFrameListener(&listener);
dev->start();

listener.waitForNewFrame(frames)
</code>```

instead, it fails while waiting for a new frame [listener.waitForNewFrame(frames)] with following exception thrown:

"
Exception thrown at 0x000000018026D0C2 (ig75icd64.dll) in ConsoleApplication1.exe: 0xC0000005: Access violation writing location 0x000000002BA0D700.
"

So, what am I doing wrong and how can I do it better?

Thanks for your advice.

Edit: shortened the code...

答:
I was facing the same problem on Debug mode but it worked on Release.

After some hours researching, I've managed to solve the problem through a compilation flag on the libfreenect2 project (on debug setting).

The freenect2 project was marked as Multi-threaded DLL (/MD) and if
  you change it to Multi-threaded Debug DLL (/MDd) it should work.

In VS2015 you can access this property on:

Project Properties -> C/C++ -> Code Generation ->Runtime Library

Body:
I'm a newbe to C++ and started fooling around with my Kinect V2 and libfreenect2.
The building of the library worked fine for me, I guess. But when I try to use it in my code I get some weird exceptions.

Freenect2 freenect2;
std::string serial="";
Freenect2Device *dev = 0;

freenect2.enumerateDevices();
serial = freenect2.getDefaultDeviceSerialNumber();
dev = freenect2.openDevice(serial);

Everytime I run this code, it fails at getting the serial number [serial = freenect2.getDefaultDeviceSerialNumber();] with:

"Unhandled exception thrown: read access violation.

_Pnext was 0xFFFFFFFFFFFFFFFF."

In case I'm using

Freenect2 freenect2;
Freenect2Device *dev = 0;
SyncMultiFrameListener listener(Frame::Color);
FrameMap frames;

freenect2.enumerateDevices();
dev = freenect2.openDefaultDevice();
dev->setColorFrameListener(&listener);
dev->start();

listener.waitForNewFrame(frames)

instead, it fails while waiting for a new frame [listener.waitForNewFrame(frames)] with following exception thrown:

"
Exception thrown at 0x000000018026D0C2 (ig75icd64.dll) in ConsoleApplication1.exe: 0xC0000005: Access violation writing location 0x000000002BA0D700.
"

So, what am I doing wrong and how can I do it better?

Thanks for your advice.

Edit: shortened the code...


问:
Dynamically Including Components in Angular
I have an angular application that has (so far) a plugin mechanism so that I can add and modify menu items at runtime. To do this, I have a service where plugins can register themselves, such as:

```<code>MenuService.addItem(
    "/main/foo",
    "bar",
    {
        title : "Bar",
        templateUrl : "foo/bar/templates/bar.html",
        controller : "BarController",
        controllerAs : "bar",
        visible : true,
        [...]
    }
);
</code>```

and then I have a directive to retrieve and iterate over items add a given hierarchy level. Internally, this uses a $route to register routes, and a template can render the structure like this:

```<code> <li menu-item path="/main">
     <a href="{{item.path}}">{{item.title}}</a>
     <ul ng-if="items.children.length>0">
         <li menu-item path="{{item.path}}">
         </li>
     </ul>
 </li>
</code>```

this is all pretty simple and works fine. Now, I also want to include entire views in a similar way. Approximately like this:

```<code><div include-components path="/main/foo">
</div>
</code>```

I would like to iterate over the items registered at this path and either duplicate the node the directive is on or add child nodes with the right templates and controllers set. If there's only one item like the one above is registered, the resulting DOM should look like this:

```<code><div
    include-components
    path="/main/foo"
    ng-controller="BarController"
    ng-include="...template.html">

    [included template+controller render here]

</div>
</code>```

or (with child elements):

```<code><div include-components path="/main/foo">
    [first registered template /w controller]
    [second registered template /w controller]
    [...]
</div>
</code>```

My current attempt kind of looks like this:

```<code>angular.module("angular-plugin").directive(
    "includeComponents",
    function(MenuService,$route,$templateCache) {
        console.log($route);
        return {
            transclude: 'element',
            scope: {
                path : "@"
            },
            link: function(scope, el, attr, ctrl,transclude) {
                var items = MenuService.get(scope.path);
                items.forEach(function(each){
                     [... what?]
                });
            }
        }
    }
});
</code>```

I tried a lot of different things inside that loop ... but I've not been able to make the template display, much less to get the controller in that item to initialize. I was looking at the source code of ngView, which should be doing something really similar... but I've not been able to get it to work. Any ideas?

答:
OK, now I spent some more time looking at ngView ... and I figured out the directive below. This does work, pretty much. Is there anything missing? Do I have to do any cleanup afterwards?</p>

```<code>angular.module("foobar").directive(
    "includeComponents",
    function(PluginMenuService,$route,$templateCache,$controller,$compile) {
        console.log($route);
        return {
            scope: {
                path : "@"
            },
            link: function(scope, el, attr, ctrl,transclude) {
                var items = PluginMenuService.get(scope.path);
                if(items.length > 0) {
                    items.forEach(
                        function(each) {
                            templ = $templateCache.get(each.templateUrl);
                            var child = el.append(templ);
                            var controller = $controller(each.controller, {});
                            var link = $compile(child.contents());

                            childScope = scope.$new();

                            childScope[each.controllerAs] = controller;
                            childScope["component"] = each;
                            child.data('$ngControllerController', controller);

                            link(childScope);
                        }
                    );
                }
            }
        }
    });
</code>```

Body:
I have an angular application that has (so far) a plugin mechanism so that I can add and modify menu items at runtime. To do this, I have a service where plugins can register themselves, such as:

MenuService.addItem(
    "/main/foo",
    "bar",
    {
        title : "Bar",
        templateUrl : "foo/bar/templates/bar.html",
        controller : "BarController",
        controllerAs : "bar",
        visible : true,
        [...]
    }
);

and then I have a directive to retrieve and iterate over items add a given hierarchy level. Internally, this uses a $route to register routes, and a template can render the structure like this:

     {{item.title}}

0">

this is all pretty simple and works fine. Now, I also want to include entire views in a similar way. Approximately like this:

I would like to iterate over the items registered at this path and either duplicate the node the directive is on or add child nodes with the right templates and controllers set. If there's only one item like the one above is registered, the resulting DOM should look like this:

    [included template+controller render here]

or (with child elements):

    [first registered template /w controller]
    [second registered template /w controller]
    [...]

My current attempt kind of looks like this:

angular.module("angular-plugin").directive(
    "includeComponents",
    function(MenuService,$route,$templateCache) {
        console.log($route);
        return {
            transclude: 'element',
            scope: {
                path : "@"
            },
            link: function(scope, el, attr, ctrl,transclude) {
                var items = MenuService.get(scope.path);
                items.forEach(function(each){
                     [... what?]
                });
            }
        }
    }
});

I tried a lot of different things inside that loop ... but I've not been able to make the template display, much less to get the controller in that item to initialize. I was looking at the source code of ngView, which should be doing something really similar... but I've not been able to get it to work. Any ideas?

Body:
OK, now I spent some more time looking at ngView ... and I figured out the directive below. This does work, pretty much. Is there anything missing? Do I have to do any cleanup afterwards?

angular.module("foobar").directive(
    "includeComponents",
    function(PluginMenuService,$route,$templateCache,$controller,$compile) {
        console.log($route);
        return {
            scope: {
                path : "@"
            },
            link: function(scope, el, attr, ctrl,transclude) {
                var items = PluginMenuService.get(scope.path);
                if(items.length > 0) {
                    items.forEach(
                        function(each) {
                            templ = $templateCache.get(each.templateUrl);
                            var child = el.append(templ);
                            var controller = $controller(each.controller, {});
                            var link = $compile(child.contents());

                            childScope = scope.$new();

                            childScope[each.controllerAs] = controller;
                            childScope["component"] = each;
                            child.data('$ngControllerController', controller);

                            link(childScope);
                        }
                    );
                }
            }
        }
    });


问:
What happens in the background of array initialization in c?
Given that this is legal

```<code>uint8_t bytes[4] = { 1, 2, 3, 4 };
</code>```

And this is not:

```<code>uint8_t bytes2[4];
bytes2 = { 1, 2, 3, 4 };
</code>```

what does { 1, 2, 3, 4 } represent?

Am assuming it's neither an rvalue or an lvalue. A preprocessor code candy that expands to something?

答:
{1,2,3,4} is an initializer-list, a particular syntax token that can only be used on the line where the array is declared.

This is regulated purely by the C standard syntax. There's no particular rationale behind it, this is just how the language is defined. In the C syntax, arrays cannot be assigned to, nor copied by assignment.

You can however dodge the syntax restrictions in several ways, to overwrite all values at once. The simplest way is just to create a temporary array and memcpy:

```<code>uint8_t tmp[] = {5,6,7,8};
memcpy(bytes, tmp, sizeof bytes);
</code>```

Alternatively, use a compound literal:

```<code>memcpy(bytes, (uint8_t[]){5,6,7,8}, sizeof bytes);
</code>```

If it makes sense for the specific application, you can also wrap the array in a struct to bypass the syntax restrictions:

```<code>typedef struct
{
  uint8_t data [4];
} array_t;

...

array_t bytes = { .data = {1,2,3,4} };
array_t tmp   = { .data = {5,6,7,8} };
bytes = tmp; // works just fine, structs can be copied this way
</code>```

Body:
Given that this is legal

uint8_t bytes[4] = { 1, 2, 3, 4 };

And this is not:

uint8_t bytes2[4];
bytes2 = { 1, 2, 3, 4 };

what does { 1, 2, 3, 4 } represent?

Am assuming it's neither an rvalue or an lvalue. A preprocessor code candy that expands to something?

Body:
{1,2,3,4} is an initializer-list, a particular syntax token that can only be used on the line where the array is declared.

This is regulated purely by the C standard syntax. There's no particular rationale behind it, this is just how the language is defined. In the C syntax, arrays cannot be assigned to, nor copied by assignment.

You can however dodge the syntax restrictions in several ways, to overwrite all values at once. The simplest way is just to create a temporary array and memcpy:

uint8_t tmp[] = {5,6,7,8};
memcpy(bytes, tmp, sizeof bytes);

Alternatively, use a compound literal:

memcpy(bytes, (uint8_t[]){5,6,7,8}, sizeof bytes);

If it makes sense for the specific application, you can also wrap the array in a struct to bypass the syntax restrictions:

typedef struct
{
  uint8_t data [4];
} array_t;

...

array_t bytes = { .data = {1,2,3,4} };
array_t tmp   = { .data = {5,6,7,8} };
bytes = tmp; // works just fine, structs can be copied this way


问:
My multilanguage menu for wordpress site
I have a word press site and i need to add multi language. I've add the WPML plugin but i don't like how the menu for language is shown. I added manually in header.php in a div the two languages (En, It).
Is there anyway to add script so these two "buttons" to be my multilanguage menu?

Thanx in adv.

答:
You could try to use a Twig templating engine to make a custom language switcher.

Here is a comprehensive WPML documentation on that topic.

Using the template example inside the article, you could modify it to something like:

```<code><ul>
   {% for code, language in languages %}
<li class="{{ language.css_classes }} my-custom-switcher-item">
           <a href="{{ language.url }}">
           {{ language.code }}
           </a>
</li>
{% endfor %}
</ul>
</code>```

Body:
You could try to use a Twig templating engine to make a custom language switcher.

Here is a comprehensive WPML documentation on that topic.

Using the template example inside the article, you could modify it to something like:

<ul>
   {% for code, language in languages %}
<li class="{{ language.css_classes }} my-custom-switcher-item">
           <a href="{{ language.url }}">
           {{ language.code }}
           </a>
</li>
{% endfor %}
</ul>


问:
Download to computer from URL
I have a server for which I send a request (ID) in response from the server I get a json, inside json i have field ImagePath with url to image. How can I download this picture?

html

```<code><button md-raised-button (click)="DownloadImage(application.ApplicationId)">Download Image</button>
</code>```

Component

```<code> DownloadImage(applicationId:number)
    {
        var ID=applicationId;
        this.httpService.downloadImage(ID).subscribe((response)=>{
            console.log(response);
        })

    }
</code>```

Service

```<code>downloadImage(applicationId:number)
{
         return this.http.get('http://192.168.0.138/api/GetPhoto?applicationId='+applicationId,{headers:this.headers})
                         .map((res:Response)=> res.json() as DownloadImage
                        );

}
</code>```

JSON

```<code>Object {ImagePath: "http://192.168.0.138:80/Content/photos/29ef5a62-8a84-41cf-92d7-7b76da20357b.jpg"}
</code>```

答:
Just try to use regular html anchor tag with download attribute :)

Note: Replace the "response.ImagePath" based on what you name the variable in the controller.

```<code><a [href]="response.ImagePath" download="download.jpg"><i class="fa fa-download"></i> Download</a>
</code>```

Hope this helps.

Title: Download to computer from URL

Body:
I have a server for which I send a request (ID) in response from the server I get a json, inside json i have field ImagePath with url to image. How can I download this picture?

html

<button md-raised-button (click)="DownloadImage(application.ApplicationId)">Download Image</button>

Component

 DownloadImage(applicationId:number)
    {
        var ID=applicationId;
        this.httpService.downloadImage(ID).subscribe((response)=>{
            console.log(response);
        })

    }

Service

downloadImage(applicationId:number)
{
         return this.http.get('http://192.168.0.138/api/GetPhoto?applicationId='+applicationId,{headers:this.headers})
                         .map((res:Response)=> res.json() as DownloadImage
                        );

}

JSON

Object {ImagePath: "http://192.168.0.138:80/Content/photos/29ef5a62-8a84-41cf-92d7-7b76da20357b.jpg"}

Body:
Just try to use regular html anchor tag with download attribute :)

Note: Replace the "response.ImagePath" based on what you name the variable in the controller.

<a [href]="response.ImagePath" download="download.jpg"><i class="fa fa-download"></i> Download</a>

Hope this helps.


问:
uib-popover-template do not show data inside
I am trying to use a uib-popover-template. It worked before, but now empty popup without data(can't attach img). How can i fix this issue? Code below

  {{user.first_name}} {{user.last_name}}

```

答:
The ng-src directive works better with just one interpolation binding:</p>

```<code><!-- REPLACE
<img ng-src="{{user.actions.server}}storage/user/mini/{{user.user.avatar}}" />
-->

<!-- INSTEAD -->
<img  ng-src="{{user.actions.server +'storage/user/mini/'+ user.user.avatar}}" />
</code>```

Body:
The ng-src directive works better with just one interpolation binding:

<!-- REPLACE
<img ng-src="{{user.actions.server}}storage/user/mini/{{user.user.avatar}}" />
-->

<!-- INSTEAD -->
<img  ng-src="{{user.actions.server +'storage/user/mini/'+ user.user.avatar}}" />


问:
How to determine the identity of a UISlider assigned to a struct variable
I have a struct that stores the last three UISliders touched. These are defined in another class (my ViewController).
Here's the struct:

```<code>struct lastSlider {
   var current: UISlider!
   var previous: UISlider!
   var previousprevious: UISlider!

   mutating func setCurrent(slider: UISlider) {
      if slider != current {
         //push into stack
         previousprevious = previous
         previous = current
         current = slider
   }
}
</code>```

For debug purposes I want to be able to determine which UISliders are lastSlider.current etc.
I have tried simply printing their .debugDescription but that only gives me information about them, not their name.

How do I identify a UISlider for debugging?

答:
As @crizzis wrote:

How about using tags? developer.apple.com/documentation/uikit/uiview/1622493-tag

This solved my problem!

Body:
I have a struct that stores the last three UISliders touched. These are defined in another class (my ViewController).
Here's the struct:

struct lastSlider {
   var current: UISlider!
   var previous: UISlider!
   var previousprevious: UISlider!

   mutating func setCurrent(slider: UISlider) {
      if slider != current {
         //push into stack
         previousprevious = previous
         previous = current
         current = slider
   }
}

For debug purposes I want to be able to determine which UISliders are lastSlider.current etc.
I have tried simply printing their .debugDescription but that only gives me information about them, not their name.

How do I identify a UISlider for debugging?


问:
jQuery val() returns empty though element.value returns value
I have a JavaScript issue that appears sometimes and sometimes not (inconsistent behavior) ... I can see on Chrome console that when the issue happens, the code:

```<code>alert( document.getElementById('F_GCEO_MEETING_DATE').value);
</code>```

returns value while the code:

```<code>var meetingDate22 = $("input[name='F_GCEO_MEETING_DATE']").val();
alert(meetingDate22);
</code>```

that I am using in the code returns empty... this empty string is causing the issue... can any one help with the reason?

答:
Try this:

```<code>var meetingDate22 = $("input[name=F_GCEO_MEETING_DATE]").val();
alert(meetingDate22);
</code>```

I think you should not use quotes after name

Body:
I have a JavaScript issue that appears sometimes and sometimes not (inconsistent behavior) ... I can see on Chrome console that when the issue happens, the code:

alert( document.getElementById('F_GCEO_MEETING_DATE').value);

returns value while the code:

var meetingDate22 = $("input[name='F_GCEO_MEETING_DATE']").val();
alert(meetingDate22);

that I am using in the code returns empty... this empty string is causing the issue... can any one help with the reason?

Body:
Try this:

var meetingDate22 = $("input[name=F_GCEO_MEETING_DATE]").val();
alert(meetingDate22);

I think you should not use quotes after name