问:
Datastore fetch VS fetch(keys_only=True) then get_multi
I am fetching multiple entities 100+ from datastore using the below Query

return entity.query(ancestor = ancestorKey).filter(entity.year= myStartYear).order(entity.num).fetch()

Which was taking a long time (order of a few seconds) to load.

Trying to find an optimum way, I created exactly 100 entities, found that it takes anywhere between 750ms ~ 1000ms to fetch the 100 entities on local server, which is a lot of course. I am not sure how to get around a single line fetch to make it more efficient!

In a desperate attempt to optimize, I tried

Removing the order part, still got the same results

Removing the filter part, still got the same results

Removing the order & filter part, still got the same results

So apparently it is something else. In a desperate attempt, I tried fetching for keys only then passing the keys to ndb.get_multi() function:

qKeys = entity.query(ancestor = ancestorKey).filter(entity.year= myStartYear).order(entity.num).fetch(keys_only=True)

return ndb.get_multi(qKeys)

To my surprise I get a better throughput! query results now loads in 450 ~ 550ms which is around ~40% better performance on average!

I am not sure why this happens, I would have thought that the fetch function already queries entities in the most optimum time.

Question:
Any idea how I can optimize the single query line to load faster?

Side Question:
Anyone knows what's the underlying mechanism for the fetch function, and why fetching keys only, then using ndb.get_multi() is faster?

答:
FWIW, you shouldn't expect meaningful results from datastore performance tests performed locally, using either the development server or the datastore emulator - they're just emulators, they don't have the same performance (or even the 100% equivalent functionality) as the real datastore.

Credit goes to @snakecharmerb, who correctly identified the culprit, confirmed by OP:

Be aware that performance characteristics in the cloud may differ from
  those on your local machine. You really want to be running these tests
  in the cloud. – snakecharmerb yesterday

@snakecharmerb you were right on your suggestion! Just tested on the
  cloud it's actually the other way around on the cloud in terms of
  performance. fetch() ~550ms, fetch(keysonly) then get_multi was ~700ms
  seems that fetch() works better on the cloud! – Khaled yesterday


来源: stackexchange

问:
DBMS_LDAP.delete_s result in error: ERR_268 Cannot find a partition for
I have problem in deleting any LDAP entry using DBMS_LDAP.delete_s function. My code looks like:

```<code>DECLARE
    l_ldap_user    VARCHAR2(256) := 'dc=example,dc=com';
    l_session      DBMS_LDAP.session;
    ...
BEGIN
    ...
    l_retval := dbms_ldap.delete_s(l_session, l_ldap_user || ',cn=Tink');
    ...
END
/
</code>```

I use Apache Directory Studio version 2.0.0 to store LDAP data and it looks like:

```<code>dn: dc=example,dc=com
objectclass: top
objectclass: domain
dc: example
userPassword:: e1NTSEF9YTZIYUF0U1BGSnFOQ2piZm9ENStpV3BMQnJ1VnBlT21IbFAraHc9P
 Q==

dn: cn=Tink,dc=example,dc=com
objectClass: inetOrgPerson
objectClass: person
objectClass: organizationalPerson
objectClass: top
cn: Tink
sn: Tink
userPassword:: e1NTSEF9eDZBZUV2SzVEYmkrYlA2c0FCZU1zdk5YMzlUN1JUL3FOSk9KQmc9P
 Q==
</code>```

As a result I receive following error message:

```<code>Error report -
ORA-31202: DBMS_LDAP: LDAP client/server error: No such object.
NO_SUCH_OBJECT: failed for MessageType : DEL_REQUEST
Message ID : 2
    Del request
        Entry : 'dc=example,dc=com,cn=Tink'
org.apache.directory.api.ldap.model.message.DeleteRequestImpl@ac23db41:
ERR_268 Cannot find a partition for dc=example,dc=com,cn=Tink
ORA-06512: at "SYS.DBMS_SYS_ERROR", line 86
ORA-06512: at "SYS.DBMS_LDAP", line 1487
ORA-06512: at "SYS.DBMS_LDAP", line 709
ORA-06512: at line 69
31202. 00000 -  "DBMS_LDAP: LDAP client/server error: %s"
*Cause:    There is a problem either on the LDAP server or on the client.
*Action:   Please report this error to the LDAP server administrator or
           your Database administrator.
</code>```

Help me please because I run out of ideas how repair this code.

答:
Problem was in the line:

```<code>l_retval := dbms_ldap.delete_s(l_session, l_ldap_user || ',cn=Tink');
</code>```

Correct reading nodes in LDAP is: leaf.domainname.domainname

Answer for this problem:

```<code>l_retval := dbms_ldap.delete_s(l_session, 'cn=Tink,' || l_ldap_user); --l_ldap_user = 'dn=domain,dn=com'.
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have problem in deleting any LDAP entry using DBMS_LDAP.delete_s function. My code looks like:

DECLARE
    l_ldap_user    VARCHAR2(256) := 'dc=example,dc=com';
    l_session      DBMS_LDAP.session;
    ...
BEGIN
    ...
    l_retval := dbms_ldap.delete_s(l_session, l_ldap_user || ',cn=Tink');
    ...
END
/

I use Apache Directory Studio version 2.0.0 to store LDAP data and it looks like:

dn: dc=example,dc=com
objectclass: top
objectclass: domain
dc: example
userPassword:: e1NTSEF9YTZIYUF0U1BGSnFOQ2piZm9ENStpV3BMQnJ1VnBlT21IbFAraHc9P
 Q==

dn: cn=Tink,dc=example,dc=com
objectClass: inetOrgPerson
objectClass: person
objectClass: organizationalPerson
objectClass: top
cn: Tink
sn: Tink
userPassword:: e1NTSEF9eDZBZUV2SzVEYmkrYlA2c0FCZU1zdk5YMzlUN1JUL3FOSk9KQmc9P
 Q==

As a result I receive following error message:

Error report -
ORA-31202: DBMS_LDAP: LDAP client/server error: No such object.
NO_SUCH_OBJECT: failed for MessageType : DEL_REQUEST
Message ID : 2
    Del request
        Entry : 'dc=example,dc=com,cn=Tink'
org.apache.directory.api.ldap.model.message.DeleteRequestImpl@ac23db41:
ERR_268 Cannot find a partition for dc=example,dc=com,cn=Tink
ORA-06512: at "SYS.DBMS_SYS_ERROR", line 86
ORA-06512: at "SYS.DBMS_LDAP", line 1487
ORA-06512: at "SYS.DBMS_LDAP", line 709
ORA-06512: at line 69
31202. 00000 -  "DBMS_LDAP: LDAP client/server error: %s"
*Cause:    There is a problem either on the LDAP server or on the client.
*Action:   Please report this error to the LDAP server administrator or
           your Database administrator.

Help me please because I run out of ideas how repair this code.

Body:
Problem was in the line:

l_retval := dbms_ldap.delete_s(l_session, l_ldap_user || ',cn=Tink');

Correct reading nodes in LDAP is: leaf.domainname.domainname

Answer for this problem:

l_retval := dbms_ldap.delete_s(l_session, 'cn=Tink,' || l_ldap_user); --l_ldap_user = 'dn=domain,dn=com'.


问:
Save input into a char array C++
How can I save input into a char array C++?

The problem I have is that I do not know beforehand how much input will the user provide.

I would like to use only arrays and chars.

答:
If you think the user will input more than one character definitely change it to a string array. below is how you would enter data into an array and print them out. count is the number of values that will be entered so you can change that to something more or less.</p>

```<code>#include <iostream>
using namespace std;

int main()
 {
   int count = 5;
   string data;
   string stringArray[count];
   for(int i = 0; i<count; i++)
   {
     cout << "Enter a value";
     cin >> stringArray[i];
    }

    for(int i=0; I < count; i++)
    {
     cout << stringArray[i] << " ";
     }
      return 0;
     }
</code>```

Title: Save input into a char array C++

Body:
If you think the user will input more than one character definitely change it to a string array. below is how you would enter data into an array and print them out. count is the number of values that will be entered so you can change that to something more or less.

#include <iostream>
using namespace std;

int main()
 {
   int count = 5;
   string data;
   string stringArray[count];
   for(int i = 0; i<count; i++)
   {
     cout << "Enter a value";
     cin >> stringArray[i];
    }

    for(int i=0; I < count; i++)
    {
     cout << stringArray[i] << " ";
     }
      return 0;
     }


问:
Visual studio wrong contextual error message
I am using vs2017 latest build. Sometimes when I changed my code in debug mode, vs shows a red squiggly underline, without any reason. I should close and reopen the vs to remove the wrong errors, but now these errors still exist.
Sorry for my bad English. The picture explains my mean:

How can I refresh / reset the editor to clear the wrong errors?
Thanks

答:
You don't refresh or reset the IDE. You build your project and if there are any errors in your code, including at the underlined spot, they show up in the "Error List" window. Then you work them out and build again. Repeat this procedure until there are no errors in the "Error List". During this procedure, any false positives - e.g. red underline - should be gone. Even if they exist, but the error list is empty, your program is doing fine.

If you don't see the "Error List", you display it on the "View -> Error List" or through the shortcut "Ctrl + \,E".


问:
ELMAH not logging in ASP.NET MVC 2
I cannot figure out what I'm doing wrong here, trying to use ELMAH in my MVC 2 application and it doesnt log anything, ever.

Here's what I have in my web.config (relevant parts)

```<code><sectionGroup name="elmah">
  <section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah" />
  <section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah" />
  <section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah" />
  <section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah" />
</sectionGroup>

<elmah>
  <security allowRemoteAccess="0" />
  <errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="ELMAH.SqlServer" />
  <!--
  <errorMail from="youremail@example.com" to="youremail@example.com" cc="" subject="Elmah Error" async="true" smtpPort="25" smtpServer="[EmailServerName]" userName="" password="" />
  <errorLog type="Elmah.XmlFileErrorLog, Elmah" logPath="~/App_Data" />
  -->
</elmah>

<connectionStrings>
  ...
  <add
      name="ELMAH.SqlServer"
      connectionString="data source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ELMAH_Logging.mdf;Integrated Security=SSPI;Connect Timeout=30;User Instance=True;"
      providerName="System.Data.SqlClient"/>
</connectionStrings>

<system.Web>
   <httpHandlers>
      <add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
      ...
    </httpHandlers>
    <httpModules>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
      ...
    </httpModules>
</system.Web>

<system.webServer>
   <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true">
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
    </modules>
    <handlers>
      <add name="Elmah" verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah"/>
      ...
    </handlers>
</system.webServer>
</code>```

Then using the code from DotNetDarren.com but no matter what I do no exceptions are ever logged?

答:
I'll have to echo Paul's preCondition but I also have preCondition="managedHandler" under the modules section for every entry.

I also use allowRemoteAccess="1" under elmah's security group but I locked down the path so that only admin level authenticated users could access the page via the controller call.

I noticed the XML error log entry commented out. Does it work at all via XML mode versus SQL? I know when I first started out I had to work in XML mode until I worked through connection string and database schema issues I was having.

You could also be running into full/medium trust issues depending on deployment but I think you get exceptions from elmah in those situations. Have you tried looking at the eventlog on the machine? That has also helped me with getting through the growing pains I had setting it up.

Lastly, I just noticed this in their Jan 14th changelog: http://code.google.com/p/elmah/source/detail?r=782 pointing to  ELMAH - Filtering 404 Errors which merely says that the ErrorFilter module needs to be registered last for filtering to work as expected. You didn't paste filter config params so I doubt it applies but the order things are registered does matter apparently so maybe there is some relation.

ContentLicense: CC BY-SA 2.5

Title: ELMAH not logging in ASP.NET MVC 2

Body:
I cannot figure out what I'm doing wrong here, trying to use ELMAH in my MVC 2 application and it doesnt log anything, ever.

Here's what I have in my web.config (relevant parts)

<sectionGroup name="elmah">

</sectionGroup>

<elmah>
  <security allowRemoteAccess="0" />
  <errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="ELMAH.SqlServer" />

</elmah>

<connectionStrings>
  ...
  <add
      name="ELMAH.SqlServer"
      connectionString="data source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ELMAH_Logging.mdf;Integrated Security=SSPI;Connect Timeout=30;User Instance=True;"
      providerName="System.Data.SqlClient"/>
</connectionStrings>

<system.Web>
   <httpHandlers>
      <add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
      ...
    </httpHandlers>
    <httpModules>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
      ...
    </httpModules>
</system.Web>

<system.webServer>
   <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true">
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
    </modules>
    <handlers>
      <add name="Elmah" verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah"/>
      ...
    </handlers>
</system.webServer>

Then using the code from DotNetDarren.com but no matter what I do no exceptions are ever logged?


问:
Extract properties from a connection string using Regex
In C# I am trying to get the Data Source and initial catalog properties from a connection string.

So if I have

```<code>metadata=res://*/model.csdl|res://*/model.ssdl|res://*/model.msl;provider=System.Data.SqlClient;provider connection string="data source=myDESKTOP;initial catalog=dbName;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"
</code>```

How can I extract just the values myDESKTOP and dbName regardless of case on the left hand of the expression?

答:
You could dissect your connection string for Entity Framework and extract the internal basic connection string. At that point the SqlConnectionStringBuilder could give you the individual parts that compose the connection string</p>

```<code>string test = "metadata=res://*/model.csdl|res://*/model.ssdl|res://*/model.msl;provider=System.Data.SqlClient;provider connection string=\"data source = myDESKTOP; initial catalog = dbName; integrated security = True; MultipleActiveResultSets = True; App = EntityFramework";

string con = string.Join("=",
                    string.Join(";", test.Split(';').Skip(2))
                          .Split('=').Skip(1)).Trim('"');

SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder(con);
Console.WriteLine(sb.DataSource);
Console.WriteLine(sb.InitialCatalog);
</code>```

Body:
In C# I am trying to get the Data Source and initial catalog properties from a connection string.

So if I have

metadata=res://*/model.csdl|res://*/model.ssdl|res://*/model.msl;provider=System.Data.SqlClient;provider connection string="data source=myDESKTOP;initial catalog=dbName;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"

How can I extract just the values myDESKTOP and dbName regardless of case on the left hand of the expression?

Body:
You could dissect your connection string for Entity Framework and extract the internal basic connection string. At that point the SqlConnectionStringBuilder could give you the individual parts that compose the connection string

string test = "metadata=res://*/model.csdl|res://*/model.ssdl|res://*/model.msl;provider=System.Data.SqlClient;provider connection string=\"data source = myDESKTOP; initial catalog = dbName; integrated security = True; MultipleActiveResultSets = True; App = EntityFramework";

string con = string.Join("=",
                    string.Join(";", test.Split(';').Skip(2))
                          .Split('=').Skip(1)).Trim('"');

SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder(con);
Console.WriteLine(sb.DataSource);
Console.WriteLine(sb.InitialCatalog);


问:
CSS Div Positions
I'm a beginner in html and im clueless, i apologize if i seem ignorant.

In this picture example am I supposed to use absolute position or relative for the containers

and how many total containers do I need to make

This is the code i currently have:

  Ali Omar
 November 13,2017

 The important difference is that floated elements still remain a part of the "flow" of the page where absolutely positioned elements do that.
      As such, they can be more than "flexible" choice.

  Guest
 November 13,2017
 Hi Ali,,,

 When i'm increasing a window size, the div container is not fixed in a particular position, I also used an absolute position, but it is not working. help me

```

In addition ,the 2nd division container is not included in the first one with its border, what could be causing it

答:
Positioning an element as absolute requires that some of its containers has a position: relative property. The relative postioned container will work as field of reference for the absolute positioned element. So just add position: relative to the parent container as in the code below.
Do you really want

  Ali Omar
 November 13,2017

 The important difference is that floated elements still remain a part of the "flow" of the page where absolutely positioned elements do that.
      As such, they can be more than "flexible" choice.

  Guest
 November 13,2017
 Hi Ali,,,

 When i'm increasing a window size, the div container is not fixed in a particular position, I also used an absolute position, but it is not working. help me

```

Title: CSS Div Positions

Body:
I'm a beginner in html and im clueless, i apologize if i seem ignorant.

In this picture example am I supposed to use absolute position or relative for the containers

and how many total containers do I need to make

This is the code i currently have:

  Ali Omar
 November 13,2017

 The important difference is that floated elements still remain a part of the "flow" of the page where absolutely positioned elements do that.
      As such, they can be more than "flexible" choice.

  Guest
 November 13,2017
 Hi Ali,,,

 When i'm increasing a window size, the div container is not fixed in a particular position, I also used an absolute position, but it is not working. help me

In addition ,the 2nd division container is not included in the first one with its border, what could be causing it

Body:
Positioning an element as absolute requires that some of its containers has a position: relative property. The relative postioned container will work as field of reference for the absolute positioned element. So just add position: relative to the parent container as in the code below.
Do you really want

<div style="border-style: solid; border-color:blue; position: relative">
     <div>
      <img id="logo"src="insta.jpg">
      <img id="logo"src="twitter.png">
      <img id="logo"src="facebook.png">
            <br>
         <br>
      <img src="u1.png">
      <p> <strong> Ali Omar <br> November 13,2017 </strong> </p>
      <br>
      <p> The important difference is that floated elements still remain a part of the "flow" of the page where absolutely positioned elements do that.
      As such, they can be more than "flexible" choice. </p>
     </div>

     <div style="position:absolute;border-style: solid;border-color:orange;">
         <br>
      <img style="float:left;" src="u2.png">
      <p> <strong> Guest <br> November 13,2017 <br> Hi Ali,,, </strong> </p>
      <br>
      <p> When i'm increasing a window size, the div container is not fixed in a particular position, I also used an absolute position, but it is not working. help me </p>
     </div>

    </div>


问:
Is there a data race if pthread_cond_signal is the last call in a thread?
Compiling this with -fsanitize=thread yields a data race report between pthread_cond_signal and pthread_cond_destroy:

```<code>#include <stdio.h>
#include <pthread.h>
#include <err.h>

bool done = false;

pthread_mutex_t mutex;
pthread_cond_t cond;

void *func(void *)
{
    pthread_mutex_lock(&mutex);

    done = true;

    pthread_mutex_unlock(&mutex);

    pthread_cond_signal(&cond);

    return NULL;
}

int main()
{
    pthread_t thread;

    pthread_cond_init(&cond, NULL);
    pthread_mutex_init(&mutex, NULL);

    if (pthread_create(&thread, NULL, func, NULL) != 0)
        err(1, "pthread_create()");

    pthread_mutex_lock(&mutex);

    while (!done)
        pthread_cond_wait(&cond, &mutex);

    pthread_mutex_unlock(&mutex);

    pthread_cond_destroy(&cond);
    pthread_mutex_destroy(&mutex);

    pthread_join(thread, NULL);

    return 0;
}
</code>```

The report goes away if I call pthread_mutex_unlock after pthread_cond_signal. But the manual says pthread_cond_signal doesn't need the mutex to be taken. Is it documented anywhere that calling pthread_cond_signal as the last call that references a pthread_cond_t, and destroying it from the thread that does pthread_cond_wait is not legal ?

答:
It is a bad idea to destroy the condition variable and the mutex before joining the thread that may still use it. Consider this scenario:

Main creates the thread and is interrupted.

func() runs until the pthread_mutex_unlock, but is interrupted before it signals.

main continues, done is true, so it never waits, unlocks the mutex and destroys the condition variable, then waits for the thread to exit.

func() calls pthread_cond_signal on the destroyed condition variable - probably a bad idea.

Fix:

Move the join before the two "destroys".

In your example I think holding the mutex longer would prevent this, but I think it is not a sustainable approach for larger software.

I would not recommend to destroy any synchronization objects (mutex, condition, etc.) before it is absolutely obvious, that all threads that are supposed to use them are joined or are guaranteed by other explicit synchronization to never access the synchronization objects again.

Body:
Compiling this with -fsanitize=thread yields a data race report between pthread_cond_signal and pthread_cond_destroy:

#include <stdio.h>
#include <pthread.h>
#include <err.h>

bool done = false;

pthread_mutex_t mutex;
pthread_cond_t cond;

void *func(void *)
{
    pthread_mutex_lock(&mutex);

    done = true;

    pthread_mutex_unlock(&mutex);

    pthread_cond_signal(&cond);

    return NULL;
}

int main()
{
    pthread_t thread;

    pthread_cond_init(&cond, NULL);
    pthread_mutex_init(&mutex, NULL);

    if (pthread_create(&thread, NULL, func, NULL) != 0)
        err(1, "pthread_create()");

    pthread_mutex_lock(&mutex);

    while (!done)
        pthread_cond_wait(&cond, &mutex);

    pthread_mutex_unlock(&mutex);

    pthread_cond_destroy(&cond);
    pthread_mutex_destroy(&mutex);

    pthread_join(thread, NULL);

    return 0;
}

The report goes away if I call pthread_mutex_unlock after pthread_cond_signal. But the manual says pthread_cond_signal doesn't need the mutex to be taken. Is it documented anywhere that calling pthread_cond_signal as the last call that references a pthread_cond_t, and destroying it from the thread that does pthread_cond_wait is not legal ?


问:
Insert elements in a BST
I get an error with this code, where i try insert elements of a list into a BST.

The error is tree-value: expects a tree, given 4 but i have no clue why this happens.

```<code>(define-struct tree (left right value))
(define example (make-tree
             (make-tree empty empty 3)
              (make-tree
               (make-tree 4 empty 7)
               (make-tree empty empty 10) 8)5))
(define app (list 1 2 3 4 6 11 12 13))

(define (insert tree val)
(cond [(empty? tree) (make-tree empty empty val)]
    [(= val (tree-value tree)) tree]
    [(< val (tree-value tree))
     (make-tree (insert (tree-left tree) val) (tree-right tree) (tree-value tree))]
    [(> val (tree-value tree))
     (make-tree  (tree-left tree) (insert (tree-right tree) val) (tree-value tree))]))

(define (insert-list tree lst)
(cond [(empty? lst) tree]
    [else (insert-list (insert tree (first lst)) (rest lst))]))

> (insert-list example app)
tree-value: expects a tree, given 4
>
</code>```

答:
The example tree was incorrectly built - a tree was expected, but a number was passed in the node with value 4. Also, a value of 4 there doesn't satisfy the order property of a BST (4 is less than 5, yet you located it to its right). We should change it to a valid value, say - 6. Please use this tree instead:

```<code>(define example
  (make-tree
   (make-tree empty empty 3)
   (make-tree
    (make-tree (make-tree empty empty 6) empty 7)
    (make-tree empty empty 10)
    8)
   5))
</code>```

Title: Insert elements in a BST

Body:
I get an error with this code, where i try insert elements of a list into a BST.

The error is tree-value: expects a tree, given 4 but i have no clue why this happens.

(define-struct tree (left right value))
(define example (make-tree
             (make-tree empty empty 3)
              (make-tree
               (make-tree 4 empty 7)
               (make-tree empty empty 10) 8)5))
(define app (list 1 2 3 4 6 11 12 13))

(define (insert tree val)
(cond [(empty? tree) (make-tree empty empty val)]
    [(= val (tree-value tree)) tree]
    [(< val (tree-value tree))
     (make-tree (insert (tree-left tree) val) (tree-right tree) (tree-value tree))]
    [(> val (tree-value tree))
     (make-tree  (tree-left tree) (insert (tree-right tree) val) (tree-value tree))]))

(define (insert-list tree lst)
(cond [(empty? lst) tree]
    [else (insert-list (insert tree (first lst)) (rest lst))]))

> (insert-list example app)
tree-value: expects a tree, given 4
>

Body:
The example tree was incorrectly built - a tree was expected, but a number was passed in the node with value 4. Also, a value of 4 there doesn't satisfy the order property of a BST (4 is less than 5, yet you located it to its right). We should change it to a valid value, say - 6. Please use this tree instead:

(define example
  (make-tree
   (make-tree empty empty 3)
   (make-tree
    (make-tree (make-tree empty empty 6) empty 7)
    (make-tree empty empty 10)
    8)
   5))


问:
How to invoke enum value specific method outside of enum?
I have enum like this:

```<code>  public enum Email{
        WELCOME,
        LOGIN
    }
</code>```

EmailService has following method signature:

```<code>public void sendEmail(String from, String subject, String[] to, Map<String, String> props, String templateFileName)
</code>```

I want to have API like this:

```<code>Email.WELCOME.send(from, subject, to, welcomeProp1, welcomeProp2....)

Email.LOGIN.send(from, subject, to, loginProp1, loginProp2....)
</code>```

To acheve this I tried to add specific methods to enum fields:

```<code>public enum Email{
    WELCOME{
        public void send(String param1,String param2,String param3,String param4){
           ....
        }
    },
    LOGIN{
        public void send(String anotherParam1,String anotherParam2,String anotherParam3){
            ....
        }
    }
}
</code>```

But I found out that I could not invoke this methods outside of enum. To acheve it I need to create abstract method and override in each enum value. But problem that signature of these methods are different and it is impossible to do it.

Any ideas?

答:
You can use polymorphism for in such case. First of all, define some interface, for instance:

```<code>public interface Message {
}
</code>```

Then you should add an abstract method to the enum:

```<code>public abstract void send(Message message);
</code>```

After that, create two child classes - the first one is for WELCOME and the second one is for LOGIN:

```<code>class WelcomeMessage implements Message {
    private String param1;
    private String param2;
    private String param3;
    private String param4;

    // constructor, getters
}

class LoginMessage implements Message {
    private String anotherParam1;
    private String anotherParam2;
    private String anotherParam3;

    // constructor, getters
}
</code>```

Then add implementations of send() method:

```<code>public enum Email {
    WELCOME {
        public void send(Message message) {
            WelcomeMessage wm = (WelcomeMessage) message;
            ....
        }
    },
    LOGIN {
        public void send(Message message) {
            LoginMessage lm = (LoginMessage) message;
            ....
        }
    }
}
</code>```

UPD.
@gstackoverflow mentioned that it's possible to invoke methods with "incorrect" implementation. I guess I know how to prevent this.

```<code>public enum Email {
    WELCOME {
        protected void sendInternal(Message message) {
            WelcomeMessage wm = (WelcomeMessage) message;
            ....
        }

        protected Class<? extends Message> getSupportedClass() {
            return WelcomeMessage.class;
        }
    },
    LOGIN {
        protected void sendInternal(Message message) {
            LoginMessage lm = (LoginMessage) message;
            ....
        }

        protected Class<? extends Message> getSupportedClass() {
            return LoginMessage;
        }
    };

    public static void send(Message message) {
        for (Email email : values()) {
            if (email.getSupportedClass().equals(message.getClass()) {
                email.sendInternal(message);
            }
        }
    }
    protected abstract void sendInternal(Message message);
    protected abstract Class<? extends Message> getSupportedClass();
}
</code>```

Body:
I have enum like this:

  public enum Email{
        WELCOME,
        LOGIN
    }

EmailService has following method signature:

public void sendEmail(String from, String subject, String[] to, Map<String, String> props, String templateFileName)

I want to have API like this:

Email.WELCOME.send(from, subject, to, welcomeProp1, welcomeProp2....)

Email.LOGIN.send(from, subject, to, loginProp1, loginProp2....)

To acheve this I tried to add specific methods to enum fields:

public enum Email{
    WELCOME{
        public void send(String param1,String param2,String param3,String param4){
           ....
        }
    },
    LOGIN{
        public void send(String anotherParam1,String anotherParam2,String anotherParam3){
            ....
        }
    }
}

But I found out that I could not invoke this methods outside of enum. To acheve it I need to create abstract method and override in each enum value. But problem that signature of these methods are different and it is impossible to do it.

Any ideas?

Body:
You can use polymorphism for in such case. First of all, define some interface, for instance:

public interface Message {
}

Then you should add an abstract method to the enum:

public abstract void send(Message message);

After that, create two child classes - the first one is for WELCOME and the second one is for LOGIN:

class WelcomeMessage implements Message {
    private String param1;
    private String param2;
    private String param3;
    private String param4;

    // constructor, getters
}

class LoginMessage implements Message {
    private String anotherParam1;
    private String anotherParam2;
    private String anotherParam3;

    // constructor, getters
}

Then add implementations of send() method:

public enum Email {
    WELCOME {
        public void send(Message message) {
            WelcomeMessage wm = (WelcomeMessage) message;
            ....
        }
    },
    LOGIN {
        public void send(Message message) {
            LoginMessage lm = (LoginMessage) message;
            ....
        }
    }
}

UPD.
@gstackoverflow mentioned that it's possible to invoke methods with "incorrect" implementation. I guess I know how to prevent this.

public enum Email {
    WELCOME {
        protected void sendInternal(Message message) {
            WelcomeMessage wm = (WelcomeMessage) message;
            ....
        }

        protected Class<? extends Message> getSupportedClass() {
            return WelcomeMessage.class;
        }
    },
    LOGIN {
        protected void sendInternal(Message message) {
            LoginMessage lm = (LoginMessage) message;
            ....
        }

        protected Class<? extends Message> getSupportedClass() {
            return LoginMessage;
        }
    };

    public static void send(Message message) {
        for (Email email : values()) {
            if (email.getSupportedClass().equals(message.getClass()) {
                email.sendInternal(message);
            }
        }
    }
    protected abstract void sendInternal(Message message);
    protected abstract Class<? extends Message> getSupportedClass();
}


问:
Keeping track of SKNodes for a category
I have a function that adds enemies to my scene that get called by an timing interval

How can I keep track of the number of enemies on the Scene to limit the amount of enemies I have in each level?

**In my update function **

```<code>CFTimeInterval timeSinceLastEnemy = currentTime - self.lastEnemyUpdateTime;
self.lastEnemyUpdateTime = currentTime;
if (timeSinceLastEnemy > 1) { // more than a second since last update
    timeSinceLastEnemy = 1.0 / 60.0;
    self.lastEnemyUpdateTime = currentTime;
}

[self spwanEnemyWithTime:timeSinceLastEnemy];
</code>```

**The timer and The method to add enemies **

```<code>- (void)spwanEnemyWithTime:(CFTimeInterval)timeSinceLast {

    self.lastEnemySpawn += timeSinceLast;
    if (self.lastEnemySpawn > 0.6) {
        self.lastEnemySpawn = 0;
        [self spawnEnemy];
    }
}

-(void) spawnEnemy {

    SKSpriteNode *enemy = [SKSpriteNode spriteNodeWithImageNamed: enemySprite];

    int minX = 5;
    int maxX = self.frame.size.width;
    int rangeX = maxX - minX;
    int actualX = (arc4random() % rangeX) + minX;

    // Create the enemy slightly off-screen along the upper edge,

    enemy.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(enemy.size.height - 10 , enemy.size.width)];
    enemy.physicsBody.dynamic = YES;
    enemy.physicsBody.categoryBitMask = enemyCategory;
    enemy.physicsBody.contactTestBitMask = bulletCategory;
    enemy.physicsBody.collisionBitMask = 0;

    // and along a random position along the X axis as calculated above
    enemy.position = CGPointMake(actualX, self.frame.size.height + enemy.size.height);
    [self addChild:enemy];
    enemy.xScale = 0.2;
    enemy.yScale = 0.2;
    enemy.zPosition = 4;

    // Create the actions
    SKAction * actionMove = [SKAction moveToY:(0 - enemy.size.height) duration:4];
    SKAction * actionMoveDone = [SKAction removeFromParent];
    [enemy runAction:[SKAction sequence:@[actionMove, actionMoveDone]]];
}
</code>```

答:
I confess I couldn't grasp what you are doing with the double timers, so I will assume that portion works as you want it to. for the enemy count couldn't this be as simple as incrementing a counter on your spawnEnemy and decrementing the counter when the enemy removes itself from the scene?

You'll have to double check my Obj-c I haven't used it in a while.

```<code>int enemyCount = 0;

-(void) spawnEnemy {

    enemyCount += 1

    ...

    // Create the actions
    SKAction *actionMove = [SKAction moveToY:(0 - enemy.size.height) duration:4];
    SKAction *actionMoveDone = [SKAction removeFromParent];
    SKAction *decrementCount = [SKAction runBlock: ^(void) {
        enemyCount -= 1;
    }];

    [enemy runAction:[SKAction sequence:@[actionMove, actionMoveDone, decrementCount]]];
}
</code>```

FYI you have a typo in your method "spwanEnemyWithTime"

Title: Keeping track of SKNodes for a category

Body:
I have a function that adds enemies to my scene that get called by an timing interval

How can I keep track of the number of enemies on the Scene to limit the amount of enemies I have in each level?

**In my update function **

CFTimeInterval timeSinceLastEnemy = currentTime - self.lastEnemyUpdateTime;
self.lastEnemyUpdateTime = currentTime;
if (timeSinceLastEnemy > 1) { // more than a second since last update
    timeSinceLastEnemy = 1.0 / 60.0;
    self.lastEnemyUpdateTime = currentTime;
}

[self spwanEnemyWithTime:timeSinceLastEnemy];

**The timer and The method to add enemies **

- (void)spwanEnemyWithTime:(CFTimeInterval)timeSinceLast {

    self.lastEnemySpawn += timeSinceLast;
    if (self.lastEnemySpawn > 0.6) {
        self.lastEnemySpawn = 0;
        [self spawnEnemy];
    }
}

-(void) spawnEnemy {

    SKSpriteNode *enemy = [SKSpriteNode spriteNodeWithImageNamed: enemySprite];

    int minX = 5;
    int maxX = self.frame.size.width;
    int rangeX = maxX - minX;
    int actualX = (arc4random() % rangeX) + minX;

    // Create the enemy slightly off-screen along the upper edge,

    enemy.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(enemy.size.height - 10 , enemy.size.width)];
    enemy.physicsBody.dynamic = YES;
    enemy.physicsBody.categoryBitMask = enemyCategory;
    enemy.physicsBody.contactTestBitMask = bulletCategory;
    enemy.physicsBody.collisionBitMask = 0;

    // and along a random position along the X axis as calculated above
    enemy.position = CGPointMake(actualX, self.frame.size.height + enemy.size.height);
    [self addChild:enemy];
    enemy.xScale = 0.2;
    enemy.yScale = 0.2;
    enemy.zPosition = 4;

    // Create the actions
    SKAction * actionMove = [SKAction moveToY:(0 - enemy.size.height) duration:4];
    SKAction * actionMoveDone = [SKAction removeFromParent];
    [enemy runAction:[SKAction sequence:@[actionMove, actionMoveDone]]];
}

Body:
I confess I couldn't grasp what you are doing with the double timers, so I will assume that portion works as you want it to. for the enemy count couldn't this be as simple as incrementing a counter on your spawnEnemy and decrementing the counter when the enemy removes itself from the scene?

You'll have to double check my Obj-c I haven't used it in a while.

int enemyCount = 0;

-(void) spawnEnemy {

    enemyCount += 1

    ...

    // Create the actions
    SKAction *actionMove = [SKAction moveToY:(0 - enemy.size.height) duration:4];
    SKAction *actionMoveDone = [SKAction removeFromParent];
    SKAction *decrementCount = [SKAction runBlock: ^(void) {
        enemyCount -= 1;
    }];

    [enemy runAction:[SKAction sequence:@[actionMove, actionMoveDone, decrementCount]]];
}

FYI you have a typo in your method "spwanEnemyWithTime"


问:
Html Tags in Xamarin App
Is there a way to show HTML Content (Text formatted with HTML Tags) in a Xamarin.Forms App?

If yes, are there Html Tags that are not allowed?

The content comes from a wysiwyg-editor in the web backend.

答:
You can use a WebView to display HTML. The documentation says

WebView supports various content sources, including embedded HTML, web pages, and HTML strings.

You could - for example - bind the content to a property

```<code><WebView Content="{Binding HtmlContent}" />
</code>```

when the BindingContext of the webview or any parent view is set accordingly.

e.g. in your viewmodel (if you are familiar with MVVM)

```<code>void LoadContent()
{
    var htmlContent = LoadContentFromServer();
    HtmlContent = htmlContent;
}
</code>```

AFAIK there are no illegal HTML tags.

Title: Html Tags in Xamarin App

Body:
You can use a WebView to display HTML. The documentation says

WebView supports various content sources, including embedded HTML, web pages, and HTML strings.

You could - for example - bind the content to a property

<WebView Content="{Binding HtmlContent}" />

when the BindingContext of the webview or any parent view is set accordingly.

e.g. in your viewmodel (if you are familiar with MVVM)

void LoadContent()
{
    var htmlContent = LoadContentFromServer();
    HtmlContent = htmlContent;
}

AFAIK there are no illegal HTML tags.


问:
How to match any non white space character except a particular one?
In Perl \S matches any non-whitespace character.

How can I match any non-whitespace character except a backslash \?

答:
On my system: CentOS 5

I can use \s outside of collections but have to use [:space:] inside of collections. In fact I can use [:space:] only inside collections. So to match a single space using this I have to use [[:space:]]
Which is really strange.

```<code>echo a b cX | sed -r "s/(a\sb[[:space:]]c[^[:space:]])/Result: \1/"

Result: a b cX
</code>```

first space I match with \s

second space I match alternatively with [[:space:]]

the X I match with "all but no space" [^[:space:]]

These two will not work:

```<code>a[:space:]b  instead use a\sb or a[[:space:]]b

a[^\s]b      instead use a[^[:space:]]b
</code>```

Body:
On my system: CentOS 5

I can use \s outside of collections but have to use [:space:] inside of collections. In fact I can use [:space:] only inside collections. So to match a single space using this I have to use [[:space:]]
Which is really strange.

echo a b cX | sed -r "s/(a\sb[[:space:]]c[^[:space:]])/Result: \1/"

Result: a b cX

first space I match with \s

second space I match alternatively with [[:space:]]

the X I match with "all but no space" [^[:space:]]

These two will not work:

a[:space:]b  instead use a\sb or a[[:space:]]b

a[^\s]b      instead use a[^[:space:]]b


问:
LogCat is not showing null pointer exception
My LogCat is often not showing null pointer exceptions..

Sample:

```<code>ProgressDialog pd;
ps.show();
</code>```

Application stops (do not reacts for any action), but there is no information about any reason in logcat.
Another sample is with database - if there is no DB and I'm making actions on it, the same happens.
I tried (that action with DB) on my colleague's phone and there was normal error. I have all needed programmer options in my phone turned on.
Maybe someone know , why it is so? It was not burdensome, when I had small app, but now when it's bigger, it can be really frustrating.

答: In my case I was using: Thread.setDefaultUncaughtExceptionHandler in my application file. If that is not turned off during debugging you won't see any exception output. ( Just make sure to turn it back on again when you release so you can still handle your issues ).

Body:
My LogCat is often not showing null pointer exceptions..

Sample:

ProgressDialog pd;
ps.show();

Application stops (do not reacts for any action), but there is no information about any reason in logcat.
Another sample is with database - if there is no DB and I'm making actions on it, the same happens.
I tried (that action with DB) on my colleague's phone and there was normal error. I have all needed programmer options in my phone turned on.
Maybe someone know , why it is so? It was not burdensome, when I had small app, but now when it's bigger, it can be really frustrating.


问:
Twig error when try to format {$
Try to format that code in twig format:

```<code><textarea class="form-control" name="email_review_subject_<?php echo $language['language_id']; ?>" ><?php echo isset(${'email_review_subject_' . $language['language_id']}) ? ${'email_review_subject_' . $language['language_id']} : ''; ?></textarea>
</code>```

So i tried with that format:

```<code><textarea class="form-control" name="email_review_subject_{{ language['language_id'] }}" >{{ isset({'email_review_subject_' . language.language_id}) ? {'email_review_subject_' . language.language_id} : '' }}</textarea>
</code>```

Error:

Uncaught exception 'Twig_Error_Syntax' with message 'A hash key must
  be followed by a colon (:). Unexpected token "punctuation" of value
  "." ("punctuation" expected with value ":")

答: I am pretty sure you can't use . to concatenate strings in Twig. Try ~, and look here: How to concatenate strings in twig

Title: Twig error when try to format {$

Body:
Try to format that code in twig format:

<textarea class="form-control" name="email_review_subject_<?php echo $language['language_id']; ?>" ><?php echo isset(${'email_review_subject_' . $language['language_id']}) ? ${'email_review_subject_' . $language['language_id']} : ''; ?></textarea>

So i tried with that format:

<textarea class="form-control" name="email_review_subject_{{ language['language_id'] }}" >{{ isset({'email_review_subject_' . language.language_id}) ? {'email_review_subject_' . language.language_id} : '' }}</textarea>

Error:

Uncaught exception 'Twig_Error_Syntax' with message 'A hash key must
  be followed by a colon (:). Unexpected token "punctuation" of value
  "." ("punctuation" expected with value ":")


问:
One big MySQL DB or a thousand little SQLite databases?
I am working on a Web based organisation tool. I am not aiming the same market as the wonderful Basecamp, but let's say the way users and data interact look like the same.

I will have to deal with user customisation, file uploads and graphical tweaks. There is a fora for each account as well. And I'd like to provide a way to backup easily each account.

I have been thinking how to create a reasonable architecture and have been trained to use beautifully normalized data in a single (yet distributed if needed) MySQL DB. Recently I have been wondering :
is it possible to think about using one SQLITE DB to store the data  for each account and only use MYSQL for the general web site management ?

The pro :

backing up is straightforward  : set version, zip, upload.

don't bother if each account use a massive fora : the mess is in one file for every one of them.

SQLITE is lightening fast, no expensive connection time...

Table scheme is much simplier : no need to make any distinction between account every times

The cons :

don't know if it's scalable

don't know if the hard drive will keep up

don't know if there is a way for SQLITE to not be stored in RAM since it would be quickly a disaster

lots of dir and subdirs : will this be ok ?

maintenance issue : upgrading the live site means upgrading all the db one by one

dev issue : setting a dev / pre prod / prod env will be quite hard

commom data will still require using mysql, so we would end end with 2 DB connections for each page, arg

More cons that pros, still, it makes me wonder (zepplin style).

What do you say ?

答:
SQLite isn't exactly the most scalable solution. There's a reason why you were trained to use a beautiful, normalized database which can be distributed if need be. It's scalable, and it's easier to maintain.

I would stick with a single MySQL database, because you're already familiar with that architecture, and it's more than likely the best solution for the job.

OwnerDisplayName: e-satis

LastEditorDisplayName: Alex Fort

OwnerDisplayName: Alex Fort

LastEditorDisplayName: Rich B


问:
The mysql use of addslashes()

Possible Duplicate:

  What does mysql_real_escape_string() do that addslashes() doesn't?

If you are trying to prevent sql injection, the first thing you would do is use mysql_real_escape_string.  Is it possible to inject a database using addslashes()?

答:
addslashes is the rough equivalent of str_replace($str, "'", "\\'"). You can bypass it trivially with any number of unicode sequences that evaluate down to ' in mysql, but look completely different to addslashes().

Mysql_real_escape_String() on the other hand, uses the actual internal mysql escaping function, which knows exactly what to look for and fix to make it "safe" for mysql. What works for mysql may not work for another database, as each has slightly different escaping semantics and requirements, but if you're working with mysql, then the "real escape string" is the way to go.

Title: The mysql use of addslashes()


问:
PropTypes isRequired on React Router 4 params prop
I have props been passed from React router in its match > params object which I want to be set in my static propTypes as a required string value.
When I set it as photo: PropTypes.string.isRequired I get an error.

```<code>Warning: Failed prop type: The prop `photo` is marked as required in `BlogEntry`, but its value is `undefined`.
</code>```

When I do a log of what is coming in via the router props I can see photo is a string id.

```<code>const {match:{params:{photo}}} = this.props;
console.log("photo = ", photo);
// result:
photo =  5a03c474e1bbc026de896aa8
</code>```

Is there any way of having a required type validation on photo ?

Here is my setup.

```<code>import React, {Component} from 'react';
import {connect} from 'react-redux';
import PropTypes from 'prop-types';
import {fetchBlogEntry} from '../../actions/index';
import BlogPost from '../../components/client/blog-post';

class BlogEntry extends Component{

  constructor(props){
    super(props);
    console.log('constructor = ', this.props.match.params.photo);
  }

  static propTypes={
    entry: PropTypes.object.isRequired,
    photo: PropTypes.string.isRequired
  }

  componentWillMount(){
    const {match:{params:{photo}}} = this.props;
    console.log("photo = ", photo);
    this.props.fetchBlogEntry(photo);
  }

  render(){
    const {entry} = this.props;
    return(
      <div id='blog' className='container'>
        <BlogPost {...entry}/>
      </div>
    )
  }
}

function mapStateToProps({blog:{entry}}){
  return{
    entry
  }
}

export default connect(({blog:{entry}}) => ({entry}), {fetchBlogEntry})(BlogEntry);
</code>```

答:
If you want to type check photos and it comes from React Router you have to change your props to expect it to be in match.

For example if I want to type check props.match.params.name my proptypes
would be:

```<code>  match: PropTypes.shape({
    params: PropTypes.shape({
      name: PropTypes.string.isRequired
    })
  }),
</code>```

Body:
I have props been passed from React router in its match > params object which I want to be set in my static propTypes as a required string value.
When I set it as photo: PropTypes.string.isRequired I get an error.

Warning: Failed prop type: The prop `photo` is marked as required in `BlogEntry`, but its value is `undefined`.

When I do a log of what is coming in via the router props I can see photo is a string id.

const {match:{params:{photo}}} = this.props;
console.log("photo = ", photo);
// result:
photo =  5a03c474e1bbc026de896aa8

Is there any way of having a required type validation on photo ?

Here is my setup.

import React, {Component} from 'react';
import {connect} from 'react-redux';
import PropTypes from 'prop-types';
import {fetchBlogEntry} from '../../actions/index';
import BlogPost from '../../components/client/blog-post';

class BlogEntry extends Component{

  constructor(props){
    super(props);
    console.log('constructor = ', this.props.match.params.photo);
  }

  static propTypes={
    entry: PropTypes.object.isRequired,
    photo: PropTypes.string.isRequired
  }

  componentWillMount(){
    const {match:{params:{photo}}} = this.props;
    console.log("photo = ", photo);
    this.props.fetchBlogEntry(photo);
  }

  render(){
    const {entry} = this.props;
    return(

        <BlogPost {...entry}/>

    )
  }
}

function mapStateToProps({blog:{entry}}){
  return{
    entry
  }
}

export default connect(({blog:{entry}}) => ({entry}), {fetchBlogEntry})(BlogEntry);

Body:
If you want to type check photos and it comes from React Router you have to change your props to expect it to be in match.

For example if I want to type check props.match.params.name my proptypes
would be:

  match: PropTypes.shape({
    params: PropTypes.shape({
      name: PropTypes.string.isRequired
    })
  }),


问:
Creating a single thread for multiple objects
I have a thread which I am creating whenever an object is created of the class , the thread I am creating in the constructor itself. So, depending on how many objects are created , the number of threads will be equal to number of objects created. But I want to create only a single thread , no matter how many objects are created..

Any help would be appreciated.

I can't put the code here as it is too big.
A simple suggestion will be helpful for me.

答:
I would suggest to move thread into separate class and make its static object in your main class t.e. something like this

```<code>MyThreadClass {
    // implement your code to handle thread
};

MyObjectClass {
    static MyThreadClass* myThread; // static object to keep single thread
};

main() {
    // create multiple MyObjectClass
}
</code>```

I made very simple code to check this concept with std::thread

Body:
I would suggest to move thread into separate class and make its static object in your main class t.e. something like this

MyThreadClass {
    // implement your code to handle thread
};

MyObjectClass {
    static MyThreadClass* myThread; // static object to keep single thread
};

main() {
    // create multiple MyObjectClass
}

I made very simple code to check this concept with std::thread


答:
One solution is to make all the methods take exactly the same object, they just use different parameters from it.

```<code>class EmailDetails {
    String param1;
    String param2;
    String param3;
    String param4;
    String anotherParam1;
    String anotherParam2;
    String anotherParam3;
}

public enum Email {
    WELCOME {
        public void send(EmailDetails details) {
            System.out.println("Welcome!!");
        }
    },
    LOGIN {
        public void send(EmailDetails details) {
            System.out.println("Log in!!");
        }
    };

    public abstract void send(EmailDetails details);
}

public void test(String[] args) {
    Email.WELCOME.send(new EmailDetails());
    Email.LOGIN.send(new EmailDetails());
}
</code>```

You will generally find that many of the fields are common to all uses.

Title: How to invoke enum value specific method outside of enum?

Body:
One solution is to make all the methods take exactly the same object, they just use different parameters from it.

class EmailDetails {
    String param1;
    String param2;
    String param3;
    String param4;
    String anotherParam1;
    String anotherParam2;
    String anotherParam3;
}

public enum Email {
    WELCOME {
        public void send(EmailDetails details) {
            System.out.println("Welcome!!");
        }
    },
    LOGIN {
        public void send(EmailDetails details) {
            System.out.println("Log in!!");
        }
    };

    public abstract void send(EmailDetails details);
}

public void test(String[] args) {
    Email.WELCOME.send(new EmailDetails());
    Email.LOGIN.send(new EmailDetails());
}

You will generally find that many of the fields are common to all uses.


问:
Changing size of embedding TensorFlow (e.g. creating a new user in Recommendation Engine)
I have a TensorFlow recommendation system based off TF-recomm. Each user has 1+numFactors numbers associated with her: a vector of numFactors, and an offset of a single number. Each task also has a bias and a vector of numFactors assigned. The TF-recomm code is

```<code>def inference_svd(user_batch, item_batch, user_num, item_num, dim=5):
    bias_global = tf.get_variable("bias_global", shape=[])
    w_bias_user = tf.get_variable("embd_bias_user", shape=[user_num])
    w_bias_item = tf.get_variable("embd_bias_item", shape=[item_num])
    bias_user = tf.nn.embedding_lookup(w_bias_user, user_batch, name="bias_user")
    bias_item = tf.nn.embedding_lookup(w_bias_item, item_batch, name="bias_item")
    w_user = tf.get_variable("embd_user", shape=[user_num, dim], initializer=tf.truncated_normal_initializer(stddev=0.02))
    w_item = tf.get_variable("embd_item", shape=[item_num, dim], initializer=tf.truncated_normal_initializer(stddev=0.02))
    embd_user = tf.nn.embedding_lookup(w_user, user_batch, name="embedding_user")
    embd_item = tf.nn.embedding_lookup(w_item, item_batch, name="embedding_item")
    infer = tf.reduce_sum(tf.multiply(embd_user, embd_item), 1)
    infer = tf.add(infer, bias_global)
    infer = tf.add(infer, bias_user)
    infer = tf.add(infer, bias_item, name="svd_inference")
    regularizer = tf.add(tf.nn.l2_loss(embd_user), tf.nn.l2_loss(embd_item), name="svd_regularizer")
    return infer, regularizer
</code>```

I have been able to get this code to work, and have been able to link it up with a REST-API.

The problem that I encounter is when I get new users. I know what I want to do:

Add a row to the bias_user, initialized to 0

Add a row to the embd_user, initialized to 0

When users rate new items, we use the same graph but freeze the weights on the items (which I can do with var_list on optimizer.minimize)

However, the weights and biases have their shapes declared ahead of time. All the material I have seen on tensorflow (running or deploying) allows the weights to change, but doesn't seem to allow the network to grow.

If I implemented this in numpy I would simply add new rows to the appropriate matrices. There are a couple of ways of doing this, such as creating new graphs and variables, but it seems best to reuse the graph used to train the model in the first place (to ensure consistency).

I am looking for a system of "best practices" for dealing with changing the size of embedding tensors, especially for a system that is online where it will have to serve predictions quickly (which prevents expensive operations).

答:
The fundamental difficulty when it comes to adding new users in your system is that you need retraining to be able to give meaningful predictions to new users. Even if you were able to dynamically resize the embedding matrices, what values would you use for the parameters describing the new user?

Taking this into account, you have a couple of options.

Save the weights of the graph, then create a new graph with adjusted dimensions and retrain it on data that includes information on the new user. As you say, this may be too costly to be in your critical path.

Use some sort of fold-in approach. For example, you could initialise the new user's embedding using the average of embeddings of users that have interacted with similar items.

Use a model that doesn't have this problem and that can incorporate new users in a more natural manner.

My recommendation would be the third option. There are classes of models that take the sequence (or set) of user interactions directly when making predictions, and do not rely on you declaring the number of users ahead of time. For example, you could use on of the following:

The AutoRec model: a simple autoencoder model that takes the set of items the user has interacted with as the input.

Session-based Recommendations with Recurrent Neural Networks: a recurrent model that takes as input the sequence of user interactions at prediction time.

Both models naturally handle new users without changes to the computation graph; adding new items will require re-training.

One implementation for the first class of models is here; for the second class, check out my recommender system package Spotlight.

Body:
I have a TensorFlow recommendation system based off TF-recomm. Each user has 1+numFactors numbers associated with her: a vector of numFactors, and an offset of a single number. Each task also has a bias and a vector of numFactors assigned. The TF-recomm code is

def inference_svd(user_batch, item_batch, user_num, item_num, dim=5):
    bias_global = tf.get_variable("bias_global", shape=[])
    w_bias_user = tf.get_variable("embd_bias_user", shape=[user_num])
    w_bias_item = tf.get_variable("embd_bias_item", shape=[item_num])
    bias_user = tf.nn.embedding_lookup(w_bias_user, user_batch, name="bias_user")
    bias_item = tf.nn.embedding_lookup(w_bias_item, item_batch, name="bias_item")
    w_user = tf.get_variable("embd_user", shape=[user_num, dim], initializer=tf.truncated_normal_initializer(stddev=0.02))
    w_item = tf.get_variable("embd_item", shape=[item_num, dim], initializer=tf.truncated_normal_initializer(stddev=0.02))
    embd_user = tf.nn.embedding_lookup(w_user, user_batch, name="embedding_user")
    embd_item = tf.nn.embedding_lookup(w_item, item_batch, name="embedding_item")
    infer = tf.reduce_sum(tf.multiply(embd_user, embd_item), 1)
    infer = tf.add(infer, bias_global)
    infer = tf.add(infer, bias_user)
    infer = tf.add(infer, bias_item, name="svd_inference")
    regularizer = tf.add(tf.nn.l2_loss(embd_user), tf.nn.l2_loss(embd_item), name="svd_regularizer")
    return infer, regularizer

I have been able to get this code to work, and have been able to link it up with a REST-API.

The problem that I encounter is when I get new users. I know what I want to do:

Add a row to the bias_user, initialized to 0

Add a row to the embd_user, initialized to 0

When users rate new items, we use the same graph but freeze the weights on the items (which I can do with var_list on optimizer.minimize)

However, the weights and biases have their shapes declared ahead of time. All the material I have seen on tensorflow (running or deploying) allows the weights to change, but doesn't seem to allow the network to grow.

If I implemented this in numpy I would simply add new rows to the appropriate matrices. There are a couple of ways of doing this, such as creating new graphs and variables, but it seems best to reuse the graph used to train the model in the first place (to ensure consistency).

I am looking for a system of "best practices" for dealing with changing the size of embedding tensors, especially for a system that is online where it will have to serve predictions quickly (which prevents expensive operations).


问:
Button becomes disabled after executing command
Sometimes the button (Done) becomes disabled after the click event.

I also have to click on the form again in order to re-enable the button.

Here is my code:

XAML:

```<code><Button
    Grid.Column="1"
    Height="20"
    Margin="10,5"
    Command="{Binding DoneCommand}"
    Content="Done" />
</code>```

C#:

```<code>private readonly RaiseCommand doneCommand;
private readonly BackgroundWorker worker;

private object _currentUserState;
private int _currentProgress;

public RaiseCommand DoneCommand
{
    get { return doneCommand; }
}

public MainWindowViewModel()
{
    doneCommand = new RaiseCommand(o => worker.RunWorkerAsync(), o => !worker.IsBusy);

    worker = new BackgroundWorker();
    worker.DoWork += DoDoneCommand;
    worker.ProgressChanged += ProgressChanged;
    worker.RunWorkerCompleted += RunWorkerCompleted;
    worker.WorkerReportsProgress = true;
}

private void DoDoneCommand(object sender, DoWorkEventArgs e)
{
    MessageBox.Show("test");
}

private void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    CurrentUserState = e.UserState;
    CurrentProgress = e.ProgressPercentage;
}

private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{

}
</code>```

EDIT:

My command class.

This class is  processing my commands of XAML.

It implements ICommand interface.

```<code>public class RaiseCommand : ICommand
{
    readonly Action<object> _action;
    readonly Func<object, bool> _canExecute;

    public RaiseCommand(Action<object> execute) : this(execute, null) { }

    public RaiseCommand(Action<object> execute, Func<object, bool> canExecute)
    {
        _action = execute ?? throw new ArgumentNullException("execute");
        _canExecute = canExecute;
    }

    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute(parameter);
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public void Execute(object parameter)
    {
        _action(parameter);
    }
}
</code>```

答:
You could call the CommandManager.InvalidateRequerySuggested() method in your RunWorkerCompleted method to force the CommandManager to refresh the state of all commands:

```<code>private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    CommandManager.InvalidateRequerySuggested();
}
</code>```

Or you could use an ICommand implementation that provides a method to raise the CanExecuteChanged event, such as for example Prism's DelegateCommand or MvvmLight's RelayCommand.

Body:
Sometimes the button (Done) becomes disabled after the click event.

I also have to click on the form again in order to re-enable the button.

Here is my code:

XAML:

<Button
    Grid.Column="1"
    Height="20"
    Margin="10,5"
    Command="{Binding DoneCommand}"
    Content="Done" />

C#:

private readonly RaiseCommand doneCommand;
private readonly BackgroundWorker worker;

private object _currentUserState;
private int _currentProgress;

public RaiseCommand DoneCommand
{
    get { return doneCommand; }
}

public MainWindowViewModel()
{
    doneCommand = new RaiseCommand(o => worker.RunWorkerAsync(), o => !worker.IsBusy);

    worker = new BackgroundWorker();
    worker.DoWork += DoDoneCommand;
    worker.ProgressChanged += ProgressChanged;
    worker.RunWorkerCompleted += RunWorkerCompleted;
    worker.WorkerReportsProgress = true;
}

private void DoDoneCommand(object sender, DoWorkEventArgs e)
{
    MessageBox.Show("test");
}

private void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    CurrentUserState = e.UserState;
    CurrentProgress = e.ProgressPercentage;
}

private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{

}

EDIT:

My command class.

This class is  processing my commands of XAML.

It implements ICommand interface.

public class RaiseCommand : ICommand
{
    readonly Action<object> _action;
    readonly Func<object, bool> _canExecute;

    public RaiseCommand(Action<object> execute) : this(execute, null) { }

    public RaiseCommand(Action<object> execute, Func<object, bool> canExecute)
    {
        _action = execute ?? throw new ArgumentNullException("execute");
        _canExecute = canExecute;
    }

    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute(parameter);
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public void Execute(object parameter)
    {
        _action(parameter);
    }
}

Body:
You could call the CommandManager.InvalidateRequerySuggested() method in your RunWorkerCompleted method to force the CommandManager to refresh the state of all commands:

private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    CommandManager.InvalidateRequerySuggested();
}

Or you could use an ICommand implementation that provides a method to raise the CanExecuteChanged event, such as for example Prism's DelegateCommand or MvvmLight's RelayCommand.


问:
WinForms: Is there a concept of associating a label with a textbox?
I'm using Visual Studio 2010 with C#.  Is there a concept in Windows Forms development of somehow linking a label with is text box?  Something so that they move together as a unit?  In the ASP.NET world, there is the AssociatedControlId property of the label control.  I also think I remember MS Access form designer having some way of associating (or linking) labels with controls.  Does this feature even exist in Visual Studio world?

If not, how do you group labels with controls such that if you move a text box you don't have to manually move the label also?

答:
I 2nd @Neils answer of just creating a user control with a textbox in it. The panel can be used to group controls, but it can be pretty tedious if you have a lot of controls on the form.

If you want to support more than just textboxes, WinForms allows you to create your own designer. If you inherit your designer from the ParentControlDesigner class, you can drop any control you want into your custom label control.


问:
Helping C++11 macros to run code with or without multithreading
I'm trying to create a preprocessing macro that allows code to be multithreaded or not depending on runtime variable.
My first attempt was only a compile-time macro and worked, but the runtime version is not.

```<code>// Working compile-time version (defined in MultiThreadMacros.h)

#ifdef USE_MT

    #define MT_START(Thread)                              \
        std::atomic<bool> Thread ## Ret = true;           \
        std::thread Thread([&]()                          \
        {                                                 \
            std::atomic<bool> & __mtRet = Thread ## Ret;  \
            try{

    #define MT_END                                        \
            }catch(...){__mtRet = false;}                 \
    };

    #define MT_JOIN(Thread)                     \
        if (Thread.joinable()) Thread.join();   \
        if (Thread ## Ret){ throw; }

#else

    #define MT_START(Thread)
    #define MT_END

#endif
</code>```

Here is a minimal use example

```<code>#define USE_MT
#include "MultiThreadMacros.h"

void function()
{
    int i = 0;
    int j = 0;

    MT_START(th1)
    {
        i += 2;

        MT_START(th3)
        {
            i += 4;
        }
        MT_END;

        MT_JOIN(th3);
    }
    MT_END;

    MT_START(th2)
    {
        j += 2;
    }
    MT_END

    MT_JOIN(th1);
    MT_JOIN(th2);
}
</code>```

Now here's the conditional version. I'm creating a lambda from user code and executing the lambda if the condition is false, otherwise I'm launching a thread with the lambda.

The main difficulty here is that the compile-time version is already widely in use on the project and I'm trying to change macro without rewriting all previous code (which leads to those __mt references)

```<code>#define MT_START(Thread, Cond)                           \
    std::thread Thread;                                  \
    std::atomic<bool> Thread ## Ret = true;              \
    {                                                    \
        auto & __mtTh = Thread;                          \
        const bool __mtCond = Cond;                      \
        auto __mtLambda = [&]() -> void                  \
        {                                                \
            std::atomic<bool> & __mtRet = Thread ## Ret; \
            try {

#define MT_END                                           \
            }catch(...){__mtRet = false;}                \
        };                                               \
        if (__mtCond)                                    \
        {                                                \
            __mtTh = std::thread{__mtLambda};            \
        }                                                \
        else                                             \
        {                                                \
            __mtLambda();                                \
        }                                                \
    }
</code>```

This last version makes unit tests to fail randomly, and I can't see why this last set of macros is different from the first one.

If anyone can help.
Thanks

答: In fact, macros are working, it was a use problem.</p>

Body:
I'm trying to create a preprocessing macro that allows code to be multithreaded or not depending on runtime variable.
My first attempt was only a compile-time macro and worked, but the runtime version is not.

// Working compile-time version (defined in MultiThreadMacros.h)

#ifdef USE_MT

    #define MT_START(Thread)                              \
        std::atomic<bool> Thread ## Ret = true;           \
        std::thread Thread([&]()                          \
        {                                                 \
            std::atomic<bool> & __mtRet = Thread ## Ret;  \
            try{

    #define MT_END                                        \
            }catch(...){__mtRet = false;}                 \
    };

    #define MT_JOIN(Thread)                     \
        if (Thread.joinable()) Thread.join();   \
        if (Thread ## Ret){ throw; }

#else

    #define MT_START(Thread)
    #define MT_END

#endif

Here is a minimal use example

#define USE_MT
#include "MultiThreadMacros.h"

void function()
{
    int i = 0;
    int j = 0;

    MT_START(th1)
    {
        i += 2;

        MT_START(th3)
        {
            i += 4;
        }
        MT_END;

        MT_JOIN(th3);
    }
    MT_END;

    MT_START(th2)
    {
        j += 2;
    }
    MT_END

    MT_JOIN(th1);
    MT_JOIN(th2);
}

Now here's the conditional version. I'm creating a lambda from user code and executing the lambda if the condition is false, otherwise I'm launching a thread with the lambda.

The main difficulty here is that the compile-time version is already widely in use on the project and I'm trying to change macro without rewriting all previous code (which leads to those __mt references)

#define MT_START(Thread, Cond)                           \
    std::thread Thread;                                  \
    std::atomic<bool> Thread ## Ret = true;              \
    {                                                    \
        auto & __mtTh = Thread;                          \
        const bool __mtCond = Cond;                      \
        auto __mtLambda = [&]() -> void                  \
        {                                                \
            std::atomic<bool> & __mtRet = Thread ## Ret; \
            try {

#define MT_END                                           \
            }catch(...){__mtRet = false;}                \
        };                                               \
        if (__mtCond)                                    \
        {                                                \
            __mtTh = std::thread{__mtLambda};            \
        }                                                \
        else                                             \
        {                                                \
            __mtLambda();                                \
        }                                                \
    }

This last version makes unit tests to fail randomly, and I can't see why this last set of macros is different from the first one.

If anyone can help.
Thanks


问:
Post load image on tripadvisor make the widget move
It's a pretty bizzare behavior, i have add the tripadvisor widget to this site : http://intermiel.com/fr/ high up in the top menu.... for week, maybe years, it's have been fine... NOW there is a post load script (?) that load a img 0px in size, that make the badge to move. i try to get the widget code again, and THIS IMG is not in the original code, it's added after.

this is the img code that cause problem

```<code><img src="https://p.travelsmarter.net/api/usersync/seed.gif?api_key=gqLWKHSnTxes4YmmtgWkqA&loc_id=3203440&publisher_browser_id=edbf833c549700c33bb814721d4e1b6d348fdf32&cb=1510760507695" alt="" width="0" height="0">
</code>```

After trying to figure out way to fix it in css for 2-3 hours, i give up.

my question : is this normal, why it apprend ?, and how to fix it.

thanks in advance

答:
Looks like something in generated code was changed, and probably some of you styles put margin or something. Do it simple:</p>

```<code>#CDSWIDLNKR{top:-12px}
</code>```

Body:
It's a pretty bizzare behavior, i have add the tripadvisor widget to this site : http://intermiel.com/fr/ high up in the top menu.... for week, maybe years, it's have been fine... NOW there is a post load script (?) that load a img 0px in size, that make the badge to move. i try to get the widget code again, and THIS IMG is not in the original code, it's added after.

this is the img code that cause problem

After trying to figure out way to fix it in css for 2-3 hours, i give up.

my question : is this normal, why it apprend ?, and how to fix it.

thanks in advance

Body:
Looks like something in generated code was changed, and probably some of you styles put margin or something. Do it simple:

#CDSWIDLNKR{top:-12px}


问:
Regular expression to match C #include file
I need some help trying to match a C include file with full path like so:

```<code>#include <stdio.h>  -> stdio.h
#include "monkey/chicken.h" -> monkey/chicken.h
</code>```

So far I have (adapted from another expression I found):

```<code>^\s*\#include\s+(["'<])([^"'<>/\|\b]+)*([">])
</code>```

But, I'm kind of stuck at this point - it doesn't match in the second case, and I'm not sure how to return the result of the match, eg the file path back to regcomp().

BTW I've looked at regexplib.com, but can't find anything suitable.

Edit: Yes I am a total regexp newbie, using POSIX regex with regmatch_t and friends...

Body:
I need some help trying to match a C include file with full path like so:

#include <stdio.h>  -> stdio.h
#include "monkey/chicken.h" -> monkey/chicken.h

So far I have (adapted from another expression I found):

^\s*\#include\s+(["'<])([^"'<>/\|\b]+)*([">])

But, I'm kind of stuck at this point - it doesn't match in the second case, and I'm not sure how to return the result of the match, eg the file path back to regcomp().

BTW I've looked at regexplib.com, but can't find anything suitable.

Edit: Yes I am a total regexp newbie, using POSIX regex with regmatch_t and friends...

Body:
This works for me:

'\#include\s*(<([^"<>|\b]+)>|"([^"<>|\b]+)")'


问:
AWS API Gateway {"error": "missing authentication token"}
I've been constantly getting the "missing authentication token" error when I click the AWS API gateway POST method url through the browser. I set "AUTH" as none and it's working totally fine through Postman but not with the browser. The problem is that I'm using swift to trigger the method and it doesn't seem to be reaching the gateway at all (no log on CloudWatch) and I don't think my code is wrong (or maybe it is). If someone could point out what my mistake is or a solution to this problem I'd appreciate it so much.

P.S. My lambda function is working totally fine and I typed in the right URL (one in the code is just for example)

Here's my code:

```<code>func postNonceToServer(paymentMethodNonce: String) {

    let paymentURL = URL(string: "https://example-url.us-east-1.amazonaws.com/prod/create-transaction")!
    var request = URLRequest(url: paymentURL)
    request.httpBody = "\(paymentMethodNonce)".data(using: String.Encoding.utf8)
    request.httpMethod = "POST"
}
</code>```

答:
This mostly would be because of CORS issue.

Please enable CORS in you API gateway like below. After enabling CORS please redeploy the API

If you don't have OPTIONS added, please follow below steps (If OPTIONS already there just add CORS),

Create a new OPTIONS method under the /services resource

Create and populate the Access-Control-Allow-Origin/Method/Headers in the OPTIONS method.

Enable CORS like below after creating OPTIONS

Body:
I've been constantly getting the "missing authentication token" error when I click the AWS API gateway POST method url through the browser. I set "AUTH" as none and it's working totally fine through Postman but not with the browser. The problem is that I'm using swift to trigger the method and it doesn't seem to be reaching the gateway at all (no log on CloudWatch) and I don't think my code is wrong (or maybe it is). If someone could point out what my mistake is or a solution to this problem I'd appreciate it so much.

P.S. My lambda function is working totally fine and I typed in the right URL (one in the code is just for example)

Here's my code:

func postNonceToServer(paymentMethodNonce: String) {

    let paymentURL = URL(string: "https://example-url.us-east-1.amazonaws.com/prod/create-transaction")!
    var request = URLRequest(url: paymentURL)
    request.httpBody = "\(paymentMethodNonce)".data(using: String.Encoding.utf8)
    request.httpMethod = "POST"
}


问:
Lift doesn't like my Web.xml
I am having trouble with a basic hello world lift application from working under tomcat 6.0.18. My web.xml looks like this

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

<!DOCTYPE web-app
        PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
    <filter>
        <filter-name>LiftFilter</filter-name>
        <display-name>Lift Filter</display-name>
        <description>The Filter that intercepts lift calls</description>
        <filter-class>net.liftweb.http.LiftFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>LiftFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>
</code>```

But when I start up the app, I get

```<code>INFO: Starting service Catalina Jan 18, 2011 7:42:44 PM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.18 Jan 18, 2011 7:42:44 PM org.apache.catalina.startup.ContextConfig defaultWebConfig
INFO: No default web.xml
Jan 18, 2011 7:42:45 PM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-9981 Jan 18, 2011 7:42:45 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1275 ms
</code>```

Which leads me to believe it doesn't like my web.xml.

Any ideas?

答:
I think it is saying that it cannot find your web.xml file.  Is it in the following location when your WAR file is expanded?

```<code>$CATALINA_HOME/webapps/yourApp/WEB-INF/web.xml
</code>```

Title: Lift doesn't like my Web.xml

Body:
I am having trouble with a basic hello world lift application from working under tomcat 6.0.18. My web.xml looks like this

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

<!DOCTYPE web-app
        PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
    <filter>
        <filter-name>LiftFilter</filter-name>
        <display-name>Lift Filter</display-name>
        <description>The Filter that intercepts lift calls</description>
        <filter-class>net.liftweb.http.LiftFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>LiftFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

But when I start up the app, I get

INFO: Starting service Catalina Jan 18, 2011 7:42:44 PM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.18 Jan 18, 2011 7:42:44 PM org.apache.catalina.startup.ContextConfig defaultWebConfig
INFO: No default web.xml
Jan 18, 2011 7:42:45 PM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-9981 Jan 18, 2011 7:42:45 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1275 ms

Which leads me to believe it doesn't like my web.xml.

Any ideas?

Body:
I think it is saying that it cannot find your web.xml file.  Is it in the following location when your WAR file is expanded?

$CATALINA_HOME/webapps/yourApp/WEB-INF/web.xml


问:
solr highlighting shows empty result
Hi I am new in Solr and using Solr 7.0.0 running in windows 7.
I created a collection and indexed folder with pdf and html files residing in a folder using the following command:

```<code>> java -jar -Dc=guidanceDoc -Dauto example\exampledocs\post.jar M:\Projects\guidance\documents\*
</code>```

If I write a query, I get results. However, if I turn the hl=on, I get a section for highlights without any text.

Here is the query:

```<code>http://localhost:8983/solr/guidanceDoc/select?hl.fl=_text_&hl=on&%20q=_text_:"Home%20Use"
</code>```

Here is the highlight part of the result:

```<code>"highlighting":{
    "M:\\Projects\\g1\\documents\\gg331681":{},
    "M:\\Projects\\g1\\documents\\gg209337":{},
    "M:\\Projects\\g1\\documents\\ggM380327":{},
    "M:\\Projects\\g1\\documents\\gg470201":{},
    "M:\\Projects\\g1\\documents\\gg507278":{},
    "M:\\Projects\\g1\\documents\\gg073767":{},
    "M:\\Projects\\g1\\documents\\gg380325":{},
    "M:\\Projects\\g1\\documents\\gg484345":{},
    "M:\\Projects\\g1\\documents\\gg259760":{}}}
</code>```

How can I make it work?

答:
Your field for a highlighting should be marked as stored=true. Since you're running Solr in cloud mode, I will recommend to use Schema API to change field definition:

```<code>curl -X POST -H 'Content-type:application/json' --data-binary '{
  "replace-field":{
     "name":"hl_field",
     "type":"text",
     "stored":true }
}' http://localhost:8983/solr/guidanceDoc/schema
</code>```

Title: solr highlighting shows empty result

Body:
Hi I am new in Solr and using Solr 7.0.0 running in windows 7.
I created a collection and indexed folder with pdf and html files residing in a folder using the following command:

> java -jar -Dc=guidanceDoc -Dauto example\exampledocs\post.jar M:\Projects\guidance\documents\*

If I write a query, I get results. However, if I turn the hl=on, I get a section for highlights without any text.

Here is the query:

http://localhost:8983/solr/guidanceDoc/select?hl.fl=_text_&hl=on&%20q=_text_:"Home%20Use"

Here is the highlight part of the result:

"highlighting":{
    "M:\\Projects\\g1\\documents\\gg331681":{},
    "M:\\Projects\\g1\\documents\\gg209337":{},
    "M:\\Projects\\g1\\documents\\ggM380327":{},
    "M:\\Projects\\g1\\documents\\gg470201":{},
    "M:\\Projects\\g1\\documents\\gg507278":{},
    "M:\\Projects\\g1\\documents\\gg073767":{},
    "M:\\Projects\\g1\\documents\\gg380325":{},
    "M:\\Projects\\g1\\documents\\gg484345":{},
    "M:\\Projects\\g1\\documents\\gg259760":{}}}

How can I make it work?

Body:
Your field for a highlighting should be marked as stored=true. Since you're running Solr in cloud mode, I will recommend to use Schema API to change field definition:

curl -X POST -H 'Content-type:application/json' --data-binary '{
  "replace-field":{
     "name":"hl_field",
     "type":"text",
     "stored":true }
}' http://localhost:8983/solr/guidanceDoc/schema


问:
Gcloud can't connect instance via SSH Port 22
nice day!

I was connected in my instance, but there was a warning that it was necessary to restart so that Ubuntu could be updated, after rebooting I can't connect, either via Putty or via Web Console.

I do not know what to do?

This error when try connect via gshell
ERROR: (gcloud.compute.ssh) [/usr/bin/ssh] exited with return code [255].

Firewall::
default-allow-ssh set 22tcp

Routes::
default-internet set 0.0.0.0/0 and Next-hop default-internet-gateway

I need help, thanks!

答:
I cannot longer SSH but I still can connect with the cloud shell. When I run the recommended command for Ubuntu:

sudo apt-get update && sudo apt-get install gce-compute-image-packages

I get:

E: Unable to locate package gce-compute-image-packages

I guess this means that the Ubuntu repository does not have yet the required version (16.04) of gce-compute-image-packages. This implies that I will not be able to SSH until Ubuntu includes that package.


问:
Is it possible for an android tv app to listen to play-stop-pause statuses?
Background: In a desire of automate things in my home, I'm using home-assistant. Even among the countless components, there's no such thing for "sensing" Android TV statuses (idle, playing, paused, which media is playing). Even without experience on creating android apps, I'm researching a way to integrate Android TV and home-assistant.

Actual question: can my android tv app, running in the background, listen to a broadcast, so that it can be notified of any playing media? Can my app know if the playing status (idle, playing, paused, which media is playing) changes?

答:
Based from this documentation, when the receiver loads a media queue item, it assigns a unique ID to the item which persists for the duration of the session (and the life of the queue). Your app can learn the status of the queue in terms of which item is currently loaded (it might not be playing), loading, or preloaded.

You app can also get an ordered list of all the items in the queue. The MediaStatus class provides this status information:

getPreloadedItemId() method - If the next item has been preloaded, returns the preloaded item ID.

getLoadingItemId() method - Returns the item ID of the item that is currently loading (but isn't active in the queue) on the receiver.

getCurrentItemId() method - Returns the item ID of the item that that was active in the queue (it might not be playing) at the time the media status change happened.

getQueueItems() method - Returns the list of MediaQueueItem instances as an unmodifiable list.

Use these methods together with the other media status methods to inform your app about the status of the queue and the items in the queue. In addition to media status updates from the receiver, your app can listen for changes to the queue by implementing RemoteMediaClient.Listener.


问:
What is "uncaught signal #9"? TextMate, Python, MacOS
I am just learning to code in python and really enjoying going through Project Euler and trying the problems. I'm on problem #3 which asks us to find the largest prime factor of 600851475143. I have written the code below to do this and it works great for smaller values, tested up to 540995, but once I try to set it loose on 600851475143, I get an error:

Program terminated by uncaught signal #9 after 50.95 seconds.

I am writing this on TextMate with Python 2.7.13 on a Mac running OS 10.12. Google has given me no help finding a solution to this. I would appreciate any insight.

Here is the code I'm executing:

```<code>n = 600851475143
fList = []
pList = []

# factor n starting with largest factor
for i in range(n-2, 2, -2):
    # if prime factor list is empty
    if len(pList) == 0:
        if n % i == 0:
            factor = i
            # as a factor is found, test for primality
            for k in range(factor-2, 2, -2):
                if factor % k == 0:
                    if factor not in fList:
                        fList.append(factor)
            if factor not in fList:
               pList.append(factor)
print(pList)
</code>```

Thank you for your insights!

答:
You are running out of memory. So your solution works up to 540995 which is relatively small number compare to 600851475143. Remember you are doing a nested loop so your algorithm's runtime is O(n)^2. In another word your loops are running for a very big number of times. you can find more about algorithmic complexity here. That being said here how I would approach the problem

```<code>n = 600851475143
i = 2
while i * i < n:
    while n % i == 0:
        n = n / i
    i = i + 1
print n
</code>```

hope that helps and good luck :)

Body:
I am just learning to code in python and really enjoying going through Project Euler and trying the problems. I'm on problem #3 which asks us to find the largest prime factor of 600851475143. I have written the code below to do this and it works great for smaller values, tested up to 540995, but once I try to set it loose on 600851475143, I get an error:

Program terminated by uncaught signal #9 after 50.95 seconds.

I am writing this on TextMate with Python 2.7.13 on a Mac running OS 10.12. Google has given me no help finding a solution to this. I would appreciate any insight.

Here is the code I'm executing:

n = 600851475143
fList = []
pList = []

# factor n starting with largest factor
for i in range(n-2, 2, -2):
    # if prime factor list is empty
    if len(pList) == 0:
        if n % i == 0:
            factor = i
            # as a factor is found, test for primality
            for k in range(factor-2, 2, -2):
                if factor % k == 0:
                    if factor not in fList:
                        fList.append(factor)
            if factor not in fList:
               pList.append(factor)
print(pList)

Thank you for your insights!

Body:
You are running out of memory. So your solution works up to 540995 which is relatively small number compare to 600851475143. Remember you are doing a nested loop so your algorithm's runtime is O(n)^2. In another word your loops are running for a very big number of times. you can find more about algorithmic complexity here. That being said here how I would approach the problem

n = 600851475143
i = 2
while i * i < n:
    while n % i == 0:
        n = n / i
    i = i + 1
print n

hope that helps and good luck :)


问:
AnyLogic: Improving computational performance of a network model
I'm working with an agent-based model of an epidemic. The idea is that individual agents make decisions based on what they observe in their networks (distance-based). I have several functions within each agent that dynamically update counts of infected contacts, contacts showing a particular behaviour etc.

The code below is for counting infected contacts within an agent's network.

```<code>int infectedConnections = 0;

if (getConnections() != null)
    for (Agent a : this.getConnections())
        {
        Person p = (Person) a;

        if (p.IsCurrentlyInfected())
            infectedConnections++;
            }

return infectedConnections ;
</code>```

There will be at least 3 more such functions that keep counts of other agents expressing other features within an agent's network. Now, this seems to run Okay when I have <500 agents, but when I increase the agent population to about 1,000 or so, the model becomes extremely slow. I'm looking to simulate at least 5,000 agents, and at this point, the model doesn't even initialise.

Is there a more computationally efficient way to track network statistics in Anylogic for larger populations?

答:
The model does not initialize since default memory amount is not enough for 5000 agents. It takes >1.300 Mb of RAM in case if each agent is connected with all other agents (4999 connections per each agent), while default simulation experiment allocates just 512 Mb of RAM. Change the memory amount in the experiment properties. Then, the code takes about 1 real sec for all 5000 agents. In other words, if I collect statistics every second, maximal execution speed is about 1 model sec per 1 real sec.

You can increase it if rewrite the code with Java Stream API:
return (int)getConnections().stream()
 .filter( a -> (Person)a).IsCurrentlyInfected())
 .count();

Then, then 1 model sec is executed in 0.5 real sec (x2 gain). In case if statistics collection is performed in parallel (with multiple threads, created by Java code), then you may get the respective gain, depending on number of cores at PC.
Anyway, this is computational complexity issue, so you need to change the approach (see @pjs answer), otherwise performance is really poor.

Body:
I'm working with an agent-based model of an epidemic. The idea is that individual agents make decisions based on what they observe in their networks (distance-based). I have several functions within each agent that dynamically update counts of infected contacts, contacts showing a particular behaviour etc.

The code below is for counting infected contacts within an agent's network.

int infectedConnections = 0;

if (getConnections() != null)
    for (Agent a : this.getConnections())
        {
        Person p = (Person) a;

        if (p.IsCurrentlyInfected())
            infectedConnections++;
            }

return infectedConnections ;

There will be at least 3 more such functions that keep counts of other agents expressing other features within an agent's network. Now, this seems to run Okay when I have <500 agents, but when I increase the agent population to about 1,000 or so, the model becomes extremely slow. I'm looking to simulate at least 5,000 agents, and at this point, the model doesn't even initialise.

Is there a more computationally efficient way to track network statistics in Anylogic for larger populations?


问:
Why no interpolation within `map` BLOCK?
This throws an error in Perl v5.20:

```<code>use strict;
use warnings;
my @a = (2,3,9);
my %b = map { "number $_" => 2*$_ } @a;
</code>```

Error:

syntax error at a.pl line 4, near "} @a"
Execution of a.pl aborted due to compilation errors.
```

<p>This doesn't:</p>

```use strict;
use warnings;
my @a = (2,3,9);
my %b = map { "number ".$_ => 2*$_ } @a;
```

Why is interpolation of $_ disallowed within the map BLOCK?

答:
map has two syntax:

```<code>map BLOCK LIST
map EXPR, LIST
</code>```

Perl must determine which syntax you are using. The problem is that both BLOCK and EXPR can start with { because { ... } can be the hash constructor (e.g. my $h = { a => 1, b => 2 };).

That means that Perl's grammar is ambiguous. When an ambiguity is encountered, perl guesses what you mean after looking ahead a little. In your situation, it guessed wrong. It guessed { was the start of a hash constructor instead of the start of a block. You will need to disambiguate explicitly.

The following are convenient ways to disambiguate blocks and hash constructors:

```<code>+{ ... }   # Not a valid block, so must be a hash constructor.
{; ... }   # Perl looks head, and sees that this must be a block.
</code>```

So in your case, you could use

```<code>my %b = map {; "number $_" => 2*$_ } @a;
</code>```

Related: Difference between returning +{} or {} in perl from a function, and return ref or value

Body:
This throws an error in Perl v5.20:

use strict;
use warnings;
my @a = (2,3,9);
my %b = map { "number $_" => 2*$_ } @a;

Error:

syntax error at a.pl line 4, near "} @a"
Execution of a.pl aborted due to compilation errors.

This doesn't:

use strict;
use warnings;
my @a = (2,3,9);
my %b = map { "number ".$_ => 2*$_ } @a;

Why is interpolation of $_ disallowed within the map BLOCK?

Body:
map has two syntax:

map BLOCK LIST
map EXPR, LIST

Perl must determine which syntax you are using. The problem is that both BLOCK and EXPR can start with { because { ... } can be the hash constructor (e.g. my $h = { a => 1, b => 2 };).

That means that Perl's grammar is ambiguous. When an ambiguity is encountered, perl guesses what you mean after looking ahead a little. In your situation, it guessed wrong. It guessed { was the start of a hash constructor instead of the start of a block. You will need to disambiguate explicitly.

The following are convenient ways to disambiguate blocks and hash constructors:

+{ ... }   # Not a valid block, so must be a hash constructor.
{; ... }   # Perl looks head, and sees that this must be a block.

So in your case, you could use

my %b = map {; "number $_" => 2*$_ } @a;

Related: Difference between returning +{} or {} in perl from a function, and return ref or value