问:
long press recyclerview android with context menu
I developing app in which there is RecyclerView. I need to call ContextMenu in which will be point for delete current item in RecyclerView.

```<code>class FavoriteQuotesHolder extends RecyclerView.ViewHolder
        implements View.OnLongClickListener, View.OnCreateContextMenuListener {

    CardView cardView;
    TextView contentOfQuote, authorQuote;
    LinearLayout linearLayout;

    FavoriteQuotesHolder(View itemView) {
        super(itemView);
        itemView.setOnCreateContextMenuListener(this);
        this.cardView = (CardView) itemView.findViewById(R.id.cardView);
        this.contentOfQuote = (TextView) itemView.findViewById(R.id.contentOfQuote);
        this.authorQuote = (TextView) itemView.findViewById(R.id.authorQuote);
        this.linearLayout = (LinearLayout) itemView.findViewById(R.id.main);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        menu.add(Menu.NONE, 0, Menu.NONE, "Edit");
        menu.add(Menu.NONE, 1, Menu.NONE, "Delete");
    }

    @Override
    public boolean onLongClick(View v) {
        return false;
    }
}
</code>```

I do not understand how I will refer to the item in the menu of the current item

```<code>@Override
public void onBindViewHolder(FavoriteQuotesHolder holder, int position) {
    LikedQuote likedQuote = getItem(position);
    holder.contentOfQuote.setText(likedQuote.getQuote());
    holder.authorQuote.setText(likedQuote.getAuthor());
    holder.itemView.????????????
}
</code>```

答:
activity need to be registered for recycler view long click:

```<code>registerForContextMenu(recyclerView);
</code>```

itemview should be long clickable:

```<code>viewHolder.itemView.setLongClickable(true);
</code>```

implement setOnlongClickListner on itemView:

```<code>itemView.setOnLongClickListener(new OnLongClickListener);
</code>```

Body:
I developing app in which there is RecyclerView. I need to call ContextMenu in which will be point for delete current item in RecyclerView.

class FavoriteQuotesHolder extends RecyclerView.ViewHolder
        implements View.OnLongClickListener, View.OnCreateContextMenuListener {

    CardView cardView;
    TextView contentOfQuote, authorQuote;
    LinearLayout linearLayout;

    FavoriteQuotesHolder(View itemView) {
        super(itemView);
        itemView.setOnCreateContextMenuListener(this);
        this.cardView = (CardView) itemView.findViewById(R.id.cardView);
        this.contentOfQuote = (TextView) itemView.findViewById(R.id.contentOfQuote);
        this.authorQuote = (TextView) itemView.findViewById(R.id.authorQuote);
        this.linearLayout = (LinearLayout) itemView.findViewById(R.id.main);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        menu.add(Menu.NONE, 0, Menu.NONE, "Edit");
        menu.add(Menu.NONE, 1, Menu.NONE, "Delete");
    }

    @Override
    public boolean onLongClick(View v) {
        return false;
    }
}

I do not understand how I will refer to the item in the menu of the current item

@Override
public void onBindViewHolder(FavoriteQuotesHolder holder, int position) {
    LikedQuote likedQuote = getItem(position);
    holder.contentOfQuote.setText(likedQuote.getQuote());
    holder.authorQuote.setText(likedQuote.getAuthor());
    holder.itemView.????????????
}

Body:
activity need to be registered for recycler view long click:

registerForContextMenu(recyclerView);

itemview should be long clickable:

viewHolder.itemView.setLongClickable(true);

implement setOnlongClickListner on itemView:

itemView.setOnLongClickListener(new OnLongClickListener);


来源: stackexchange

问:
Java Style / Best Practice - passing fields to methods vs accessing directly
In Java, given the following class:

```<code>public class MyClass {
   private final Dependency dependency;
   public MyClass(Dependency dependency)
   {
       this.dependency = dependency;
   }

   public void doWork()
   {
       // validate dependency...
   }
</code>```

The doWork method needs to invoke a method that uses dependency.

Which of the following two variations is considered "best practice", and why?

```<code>   // Access dependency directly
   void validateDependency()
   {
        this.dependency.something();
   }

   // access dependency as passed to the method
   void validateDependency(Dependency dependency)
   {
       dependency.something();
   }
</code>```

I find myself favouring the latter, passing the dependency directly to the method, as it makes the method easier to test in isolation (albeit, marginally).

However, I'm interested in the java convention / best practice here.

答: There isnt a right way to do it. I prefer just putting the variable there. </p>

ContentLicense: CC BY-SA 2.5

Body:
In Java, given the following class:

public class MyClass {
   private final Dependency dependency;
   public MyClass(Dependency dependency)
   {
       this.dependency = dependency;
   }

   public void doWork()
   {
       // validate dependency...
   }

The doWork method needs to invoke a method that uses dependency.

Which of the following two variations is considered "best practice", and why?

   // Access dependency directly
   void validateDependency()
   {
        this.dependency.something();
   }

   // access dependency as passed to the method
   void validateDependency(Dependency dependency)
   {
       dependency.something();
   }

I find myself favouring the latter, passing the dependency directly to the method, as it makes the method easier to test in isolation (albeit, marginally).

However, I'm interested in the java convention / best practice here.


问:
Unable ot get openJPA working with Tomcat 8
I'm trying to get OpenJPA working with Tomcat 8 but have been unable, it throws the error:

```<code>org.apache.openjpa.persistence.ArgumentException: The persistence provider is
attempting to use properties in the persistence.xml file to resolve the
data source. A Java Database Connectivity (JDBC) driver or data source class name
must be specified in the openjpa.ConnectionDriverName or
javax.persistence.jdbc.driver property. The following properties
are available in the configuration:
"org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl@2655aabb".
</code>```

My web.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
        version="3.1">

...servlet stuff...

    <resource-ref>
        <description>Database</description>
        <res-ref-name>jdbc/webservice</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>
</web-app>
</code>```

My context.xml (I verified this datasource works by doing a connection via InitialContext, etc in a servlet):

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

    <Resource name="jdbc/webservice" auth="Container"

            type="javax.sql.DataSource"

            maxActive="8"

            removeAbandoned="true"
            removeAbandonedTimeout="60"
            logAbandoned="true"

            validationQuery="SELECT 1"

            username="dev" password="mypass"

            url="jdbc:mysql://127.0.0.1:3306/mydb"

            driverClassName="com.mysql.jdbc.Driver">
    </Resource>

    <Resource name="BeanManager"

            auth="Container"

            type="javax.enterprise.inject.spi.BeanManager"

            factory="org.jboss.weld.resources.ManagerObjectFactory"/>

</Context>
</code>```

My persistence.xml (I also tried every diff combo of the properties and data-source elements. I also tried "RESOURCE_LOCAL"):

```<code><?xml version="1.0" encoding="UTF-8"?>
<persistence
        version="2.1"
        xmlns="http://xmlns.jcp.org/xml/ns/persistence"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">

    <persistence-unit name="TestOpenJPAPersistence" transaction-type="JTA">

        <provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
        <jta-data-source>java:comp/env/jdbc/webservice</jta-data-source>
        <non-jta-data-source>java:comp/env/jdbc/webservice</non-jta-data-source>
<

        <properties>

            <!--
                I tried leaving these out, leaving them in and all combinations.
                I also tried it with the jdbc url, username, password in properties too.
            -->
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
            <property name="openjpa.ConnectionDriverName" value="com.mysql.jdbc.Driver"/>
            <property name="openjpa.ConnectionFactoryProperties" value="MaxActive=10,MaxIdle=5,MinIdle=2,MaxWait=1800000"/>
            <property name="openjpa.Log" value="org.apache.openjpa.log, DefaultLevel=DEBUG, Runtime=INFO, Tool=INFO, SQL=TRACE"/>
            <property name="openjpa.DynamicEnhancementAgent" value="false" />
            <property name="openjpa.RuntimeUnenhancedClasses" value="unsupported" />
        </properties>

    </persistence-unit>
</persistence>
</code>```

My pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>groupId</groupId>
    <artifactId>TestWebSocket</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>war</packaging>

    <!-- Tell Maven what language version to use -->
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>

        <!-- https://mvnrepository.com/artifact/javax.enterprise/cdi-api -->
        <dependency>
            <groupId>javax.enterprise</groupId>
            <artifactId>cdi-api</artifactId>
            <version>2.0</version>
        </dependency>

        <!-- Enables the annotations, etc needed -->
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.exterprise</groupId>
                    <artifactId>cdi-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- Our jersey libs -->
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>
            <version>2.25.1</version>
        </dependency>

        <!-- CDI to JAX-RS Binding -->
        <!-- https://mvnrepository.com/artifact/org.glassfish.jersey.containers.glassfish/jersey-gf-cdi-ban-custom-hk2-binding -->
        <dependency>
            <groupId>org.glassfish.jersey.containers.glassfish</groupId>
            <artifactId>jersey-gf-cdi</artifactId>
            <version>2.14</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.jboss.weld.servlet/weld-servlet-core -->
        <dependency>
            <groupId>org.jboss.weld.servlet</groupId>
            <artifactId>weld-servlet-core</artifactId>
            <version>3.0.0.Final</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.jboss.weld/weld-core-impl -->
        <dependency>
            <groupId>org.jboss.weld</groupId>
            <artifactId>weld-core-impl</artifactId>
            <version>3.0.0.Final</version>
        </dependency>

        <dependency>
            <groupId>org.apache.openjpa</groupId>
            <artifactId>openjpa</artifactId>
            <version>2.4.2</version>
        </dependency>

    </dependencies>

</project>
</code>```

My Servlet:

```<code>package com.testjpa;

import com.testpush.TestEvent;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/jpa")
public class JPAServlet extends HttpServlet
{
    @PersistenceUnit(unitName = "TestOpenJPAPersistence")
    EntityManagerFactory persistenceFactory;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        EntityManager persistenceManager = null;
        String result = "Not found";
        try
        {
            //I need to do this as otherwise the factory is null
            persistenceFactory = Persistence.createEntityManagerFactory( "TestOpenJPAPersistence" );

            //This line throws the error
            persistenceManager = persistenceFactory.createEntityManager();
            User user = persistenceManager.find( User.class, 9 );
            if ( user != null )
            {
                result = user.getName();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if ( persistenceManager != null )
            {
                persistenceManager.close();
            }
        }
        resp.getWriter().println( result );
    }
}
</code>```

答:
Looking at your source code, I found the problem : your persistence.xml is located in src/main/webapp/META-INF instead of src/main/resources/META-INF.

Move it to src/main/resources/META-INF and remove the javax.persistence.jdbc.driver property and it will work.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to get OpenJPA working with Tomcat 8 but have been unable, it throws the error:

org.apache.openjpa.persistence.ArgumentException: The persistence provider is
attempting to use properties in the persistence.xml file to resolve the
data source. A Java Database Connectivity (JDBC) driver or data source class name
must be specified in the openjpa.ConnectionDriverName or
javax.persistence.jdbc.driver property. The following properties
are available in the configuration:
"org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl@2655aabb".

My web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
        version="3.1">

...servlet stuff...

    <resource-ref>
        <description>Database</description>
        <res-ref-name>jdbc/webservice</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>
</web-app>

My context.xml (I verified this datasource works by doing a connection via InitialContext, etc in a servlet):

<?xml version="1.0" encoding="utf-8"?>
<Context>

    <Resource name="jdbc/webservice" auth="Container"

            type="javax.sql.DataSource"

            maxActive="8"

            removeAbandoned="true"
            removeAbandonedTimeout="60"
            logAbandoned="true"

            validationQuery="SELECT 1"

            username="dev" password="mypass"

            url="jdbc:mysql://127.0.0.1:3306/mydb"

            driverClassName="com.mysql.jdbc.Driver">
    </Resource>

    <Resource name="BeanManager"

            auth="Container"

            type="javax.enterprise.inject.spi.BeanManager"

            factory="org.jboss.weld.resources.ManagerObjectFactory"/>

</Context>

My persistence.xml (I also tried every diff combo of the properties and data-source elements. I also tried "RESOURCE_LOCAL"):

<?xml version="1.0" encoding="UTF-8"?>
<persistence
        version="2.1"
        xmlns="http://xmlns.jcp.org/xml/ns/persistence"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">

    <persistence-unit name="TestOpenJPAPersistence" transaction-type="JTA">

        <provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
        <jta-data-source>java:comp/env/jdbc/webservice</jta-data-source>
        <non-jta-data-source>java:comp/env/jdbc/webservice</non-jta-data-source>
<

        <properties>

            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
            <property name="openjpa.ConnectionDriverName" value="com.mysql.jdbc.Driver"/>
            <property name="openjpa.ConnectionFactoryProperties" value="MaxActive=10,MaxIdle=5,MinIdle=2,MaxWait=1800000"/>
            <property name="openjpa.Log" value="org.apache.openjpa.log, DefaultLevel=DEBUG, Runtime=INFO, Tool=INFO, SQL=TRACE"/>
            <property name="openjpa.DynamicEnhancementAgent" value="false" />
            <property name="openjpa.RuntimeUnenhancedClasses" value="unsupported" />
        </properties>

    </persistence-unit>
</persistence>

My pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>groupId</groupId>
    <artifactId>TestWebSocket</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>war</packaging>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>

        <dependency>
            <groupId>javax.enterprise</groupId>
            <artifactId>cdi-api</artifactId>
            <version>2.0</version>
        </dependency>

        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.exterprise</groupId>
                    <artifactId>cdi-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>
            <version>2.25.1</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.containers.glassfish</groupId>
            <artifactId>jersey-gf-cdi</artifactId>
            <version>2.14</version>
        </dependency>

        <dependency>
            <groupId>org.jboss.weld.servlet</groupId>
            <artifactId>weld-servlet-core</artifactId>
            <version>3.0.0.Final</version>
        </dependency>

        <dependency>
            <groupId>org.jboss.weld</groupId>
            <artifactId>weld-core-impl</artifactId>
            <version>3.0.0.Final</version>
        </dependency>

        <dependency>
            <groupId>org.apache.openjpa</groupId>
            <artifactId>openjpa</artifactId>
            <version>2.4.2</version>
        </dependency>

    </dependencies>

</project>

My Servlet:

package com.testjpa;

import com.testpush.TestEvent;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/jpa")
public class JPAServlet extends HttpServlet
{
    @PersistenceUnit(unitName = "TestOpenJPAPersistence")
    EntityManagerFactory persistenceFactory;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        EntityManager persistenceManager = null;
        String result = "Not found";
        try
        {
            //I need to do this as otherwise the factory is null
            persistenceFactory = Persistence.createEntityManagerFactory( "TestOpenJPAPersistence" );

            //This line throws the error
            persistenceManager = persistenceFactory.createEntityManager();
            User user = persistenceManager.find( User.class, 9 );
            if ( user != null )
            {
                result = user.getName();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if ( persistenceManager != null )
            {
                persistenceManager.close();
            }
        }
        resp.getWriter().println( result );
    }
}


问:
TFS WorkItem Attachments can save but not load
I can save an Attachment to a WorkItem like this:

```<code>TfsTeamProjectCollection tfsTeamProjects = new TfsTeamProjectCollection(new Uri(tfsServerUrl));
WorkItemStore tfsWorkItemStore = tfsTeamProjects.GetService<WorkItemStore>();
WorkItem tfsWorkItem = tfsWorkItemStore.GetWorkItem(tfsWorkItemId);

FileInfo fi = new FileInfo(@"D:\\Docs\testfile.txt");
Attachment tfsAttachment = new Attachment(fi.FullName);
tfsWorkItem.Attachments.Add(tfsAttachment);
tfsWorkItem.Save();
</code>```

But when I try to get the list of Attachments for a WorkItem like this:

```<code>TfsTeamProjectCollection tfsTeamProjects = new TfsTeamProjectCollection(new Uri(tfsServerUrl));
WorkItemStore tfsWorkItemStore = tfsTeamProjects.GetService<WorkItemStore>();
WorkItem tfsWorkItem = tfsWorkItemStore.GetWorkItem(tfsWorkItemId);
foreach(Attachment tfsAttachment : tfsWorkItem.Attachments)
{
    // Do things here
}
</code>```

tfsWorkItem.Attachments is always empty, even though I can see four attachments in the Objects tab on the TFS Web UI. And the WorkItem object that I am getting is the correct one.

答:
I have tried exactly the same scenario, and it does work for me. I am able to attach the file, and afterwards get it using the AttachmentCollection as you mentioned. What you could try to do is execute it in the same context like the following and verify if the AttachementCollection is still empty in this case:

```<code>TfsTeamProjectCollection tfsTeamProjects = new TfsTeamProjectCollection(new Uri(tfsServerUrl));
WorkItemStore tfsWorkItemStore = tfsTeamProjects.GetService<WorkItemStore>();
WorkItem tfsWorkItem = tfsWorkItemStore.GetWorkItem(tfsWorkItemId);
FileInfo fi = new FileInfo(@"D:\\New Text Document.txt");
Attachment tfsAttachment = new Attachment(fi.FullName);
tfsWorkItem.Attachments.Add(tfsAttachment);
tfsWorkItem.Save();
foreach (Attachment tfsAttachment1 in tfsWorkItem.Attachments)
                {
                    // Do things here
                }
</code>```

If the collection is not empty here, most probably there is another issue with the second call in which you are trying to get the attachments.

Body:
I can save an Attachment to a WorkItem like this:

TfsTeamProjectCollection tfsTeamProjects = new TfsTeamProjectCollection(new Uri(tfsServerUrl));
WorkItemStore tfsWorkItemStore = tfsTeamProjects.GetService<WorkItemStore>();
WorkItem tfsWorkItem = tfsWorkItemStore.GetWorkItem(tfsWorkItemId);

FileInfo fi = new FileInfo(@"D:\\Docs\testfile.txt");
Attachment tfsAttachment = new Attachment(fi.FullName);
tfsWorkItem.Attachments.Add(tfsAttachment);
tfsWorkItem.Save();

But when I try to get the list of Attachments for a WorkItem like this:

TfsTeamProjectCollection tfsTeamProjects = new TfsTeamProjectCollection(new Uri(tfsServerUrl));
WorkItemStore tfsWorkItemStore = tfsTeamProjects.GetService<WorkItemStore>();
WorkItem tfsWorkItem = tfsWorkItemStore.GetWorkItem(tfsWorkItemId);
foreach(Attachment tfsAttachment : tfsWorkItem.Attachments)
{
    // Do things here
}

tfsWorkItem.Attachments is always empty, even though I can see four attachments in the Objects tab on the TFS Web UI. And the WorkItem object that I am getting is the correct one.

Body:
I have tried exactly the same scenario, and it does work for me. I am able to attach the file, and afterwards get it using the AttachmentCollection as you mentioned. What you could try to do is execute it in the same context like the following and verify if the AttachementCollection is still empty in this case:

TfsTeamProjectCollection tfsTeamProjects = new TfsTeamProjectCollection(new Uri(tfsServerUrl));
WorkItemStore tfsWorkItemStore = tfsTeamProjects.GetService<WorkItemStore>();
WorkItem tfsWorkItem = tfsWorkItemStore.GetWorkItem(tfsWorkItemId);
FileInfo fi = new FileInfo(@"D:\\New Text Document.txt");
Attachment tfsAttachment = new Attachment(fi.FullName);
tfsWorkItem.Attachments.Add(tfsAttachment);
tfsWorkItem.Save();
foreach (Attachment tfsAttachment1 in tfsWorkItem.Attachments)
                {
                    // Do things here
                }

If the collection is not empty here, most probably there is another issue with the second call in which you are trying to get the attachments.


问:
Pattern matching using information from theorems
I have the following question, look in the code.

```<code>  (* Suppose we have type A *)
  Variable A: Type.

  (* Also we have a function that returns the type (option A) *)
  Definition f_opt x: option A := ...

  (* Then, I can prove that this function always returns something: *)
  Theorem always_some: forall x, exists y, f_opt x = Some y.
  Admitted.

  (* Or, equivalently: *)
  Theorem always_not_none: forall x, f_opt x <> None.
  Admitted.
</code>```

Now I would like to get a version of f_opt that always returns a value of type A. Something like this:

```<code>  Definition f x: A :=
    match f_opt x with
      | Some y => y
    end.
</code>```

But I get the following error:

Non exhaustive pattern-matching: no clause found for pattern None.

I understand that I need to do some kind of work with types, but I do not understand what exactly i should do.

答:
In Coq's underlying theory, every pattern matching must be exhaustive -- that is, it must explicitly consider all the constructors of the inductive type in question. This is why you are getting the error message you saw.

How do we get around this restriction? There are a few solutions. First, let's see how to convince Coq that the None branch can never occur. For this, we will use your always_not_none theorem:

```<code>Definition f x : A :=
  match f_opt x as res return res <> None -> A with
  | Some y => fun _ => y
  | None => fun H => match H eq_refl with end
  end (always_not_none x).
</code>```

This code might look strange at first sight, but it almost performs the pattern match you want. To explain to Coq that the None case never arises, it combines always_not_none with the fact that f_opt x = None on that branch to derive a contradiction.  This is the H eq_refl term on that branch. Then, the match on that contradiction suffices to convince Coq that the branch is spurious. A bit more formally, because False, the contradictory proposition, is defined without any constructors, when we match on a term of type False, there are no branches to deal with, and the entire expression can return any type that we want -- in this case, A.

What is strange about this code is the type annotations on the match, and that it returns a function instead of something of type A directly. This is done because of how dependent pattern match works in Coq: whenever we want to make use of information that we obtain from being in a particular branch of a match (here, that f_opt x is equal to None in that branch), we must explicitly make the match return a function -- what Adam Chlipala calls the convoy pattern. This is done so that Coq knows where you plan to use that extra information and check that it is done correctly. Here, we use that f_opt x is None to feed the hypothesis needed by always_not_none x to derive a contradiction.

Although this will solve your problem, I would generally advise you against doing it this way. For instance, if you know that your A type is inhabited by some element a : A, then you can simply make f return a on that branch. This has the benefit of avoiding mentioning proofs inside your functions, which often gets in the way when simplifying and rewriting terms.

Body:
I have the following question, look in the code.

  (* Suppose we have type A *)
  Variable A: Type.

  (* Also we have a function that returns the type (option A) *)
  Definition f_opt x: option A := ...

  (* Then, I can prove that this function always returns something: *)
  Theorem always_some: forall x, exists y, f_opt x = Some y.
  Admitted.

  (* Or, equivalently: *)
  Theorem always_not_none: forall x, f_opt x <> None.
  Admitted.

Now I would like to get a version of f_opt that always returns a value of type A. Something like this:

  Definition f x: A :=
    match f_opt x with
      | Some y => y
    end.

But I get the following error:

Non exhaustive pattern-matching: no clause found for pattern None.

I understand that I need to do some kind of work with types, but I do not understand what exactly i should do.

Body:
In Coq's underlying theory, every pattern matching must be exhaustive -- that is, it must explicitly consider all the constructors of the inductive type in question. This is why you are getting the error message you saw.

How do we get around this restriction? There are a few solutions. First, let's see how to convince Coq that the None branch can never occur. For this, we will use your always_not_none theorem:

Definition f x : A :=
  match f_opt x as res return res <> None -> A with
  | Some y => fun _ => y
  | None => fun H => match H eq_refl with end
  end (always_not_none x).

This code might look strange at first sight, but it almost performs the pattern match you want. To explain to Coq that the None case never arises, it combines always_not_none with the fact that f_opt x = None on that branch to derive a contradiction.  This is the H eq_refl term on that branch. Then, the match on that contradiction suffices to convince Coq that the branch is spurious. A bit more formally, because False, the contradictory proposition, is defined without any constructors, when we match on a term of type False, there are no branches to deal with, and the entire expression can return any type that we want -- in this case, A.

What is strange about this code is the type annotations on the match, and that it returns a function instead of something of type A directly. This is done because of how dependent pattern match works in Coq: whenever we want to make use of information that we obtain from being in a particular branch of a match (here, that f_opt x is equal to None in that branch), we must explicitly make the match return a function -- what Adam Chlipala calls the convoy pattern. This is done so that Coq knows where you plan to use that extra information and check that it is done correctly. Here, we use that f_opt x is None to feed the hypothesis needed by always_not_none x to derive a contradiction.

Although this will solve your problem, I would generally advise you against doing it this way. For instance, if you know that your A type is inhabited by some element a : A, then you can simply make f return a on that branch. This has the benefit of avoiding mentioning proofs inside your functions, which often gets in the way when simplifying and rewriting terms.


问:
Excel does not indicate right values from HTML table from Web Query
I never 'coded' with Excel. So I do not have a code that shows my problem. But as you will see it is a very basic problem and can be reproduced very fast. I am trying right now to implement an HTML table in Excel, which should be fairly simple. But the result is not showing the right value.

Go on https://coinmarketcap.com/#EUR and copy the link.

I open an Excel file, go on Data > From Web > an insert the URL and press Ok and Load Table.

Unfortunately, the table shows now the values in US currency and not in EURO which is pre-selected in the URL. Can someone tell me why this happens and how to display the EURO values?

答: @ Andreas: Thanks for your effort!!! Unfortunately, the numbers are not really correct. The Euro rate should be around 2500 for Bitcoins but its 744 after the conversion. But regarding format everything is fine now. There was also an error message. Its called "Runtype Error '13' Type Mismatch" :(</p>


问:
Cannot stop a running docker container
I am trying to stop a running container using my compose file.

Executed docker-compose down. I am getting following error. Other containers are stopping without any issue, only this particular container is not stopping. Tried removing by force but still failed.

```<code>ERROR: for <<CONATINER_NAME>>  UnixHTTPConnectionPool(host='localhost', port=None): Read timed out. (read timeout=70)
ERROR: An HTTP request took too long to complete. Retry with --verbose to obtain debug information.
If you encounter this issue regularly because of slow network conditions, consider setting COMPOSE_HTTP_TIMEOUT to a higher value (current value: 60).
</code>```

答: Server restart fixed the issue for me</p>

Title: Cannot stop a running docker container

Body:
I am trying to stop a running container using my compose file.

Executed docker-compose down. I am getting following error. Other containers are stopping without any issue, only this particular container is not stopping. Tried removing by force but still failed.

ERROR: for <<CONATINER_NAME>>  UnixHTTPConnectionPool(host='localhost', port=None): Read timed out. (read timeout=70)
ERROR: An HTTP request took too long to complete. Retry with --verbose to obtain debug information.
If you encounter this issue regularly because of slow network conditions, consider setting COMPOSE_HTTP_TIMEOUT to a higher value (current value: 60).

Body: Server restart fixed the issue for me


问:
Check date is within one year python
I have a date string formatted like this: "2017-05-31T06:44:13Z".

I need to check whether this date is within a one year span from today's date.

Which is the best method to do it: convert it into a timestamp and check, or convert into a date format?

答:
Use the datetime package together with timedelta:

```<code>import datetime
then = datetime.datetime.strptime("2017-05-31T06:44:13Z".replace('T',' ')[:-1],'%Y-%m-%d %H:%M:%S')
now = datetime.datetime.now()
d = datetime.timedelta(days = 365)
</code>```

and simply check if now-d > then.

Title: Check date is within one year python

Body:
Use the datetime package together with timedelta:

import datetime
then = datetime.datetime.strptime("2017-05-31T06:44:13Z".replace('T',' ')[:-1],'%Y-%m-%d %H:%M:%S')
now = datetime.datetime.now()
d = datetime.timedelta(days = 365)

and simply check if now-d > then.


问:
Add Object to Hashset with Iterator
```<code> HashSet<String> set = new HashSet<String>();
 set.add("test1");
 Iterator<String> it = set.iterator();

 while(it.hasNext()){
    it.next();
    set.add("sf");
    it.remove();
 }
</code>```

Throws me the exception:

```<code>Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.remove(Unknown Source)
</code>```

If I delete the set.add("sf"); it works obviously.
But why can't I add something to my HashSet while using the iterator?

答:
Iterator does not support add while iterating .In collection iterator use expectedModCount to check if it is modified by other.When you do some add using set reference modCount  value increases and expectedModCount not changed cause exception.

```<code> if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
</code>```

public interface Iterator {

```<code>boolean hasNext();

E next();

void remove();
</code>```

}

Title: Add Object to Hashset with Iterator

Body:
 HashSet<String> set = new HashSet<String>();
 set.add("test1");
 Iterator<String> it = set.iterator();

 while(it.hasNext()){
    it.next();
    set.add("sf");
    it.remove();
 }

Throws me the exception:

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.remove(Unknown Source)

If I delete the set.add("sf"); it works obviously.
But why can't I add something to my HashSet while using the iterator?

Body:
Iterator does not support add while iterating .In collection iterator use expectedModCount to check if it is modified by other.When you do some add using set reference modCount  value increases and expectedModCount not changed cause exception.

 if (modCount != expectedModCount)
                throw new ConcurrentModificationException();

public interface Iterator {

boolean hasNext();

E next();

void remove();

}


问:
How to remove .js suffix from Angular imports
I want to remove .js suffix from Angular imports.

Not wanted (now workable): import { Example } from './whatever/example.js';

Wanted: import { Example } from './whatever/example';

I suspect I am missing a configuration in the systemjs.config.js.

```<code>(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': '/node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      'app': 'app',

      // angular bundles
      // other libraries

    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });
})(this);
</code>```

答:
Try adding this in packages:

```<code>'.': {
    defaultJSExtensions: 'js'
}
</code>```

Such that packages now looks like:

```<code>// packages tells the System loader how to load when no filename and/or no extension
packages: {
'.': {
    defaultJSExtensions: 'js'
},
app: {
    defaultExtension: 'js'
},
rxjs: {
    defaultExtension: 'js'
    }
}
</code>```

Body:
I want to remove .js suffix from Angular imports.

Not wanted (now workable): import { Example } from './whatever/example.js';

Wanted: import { Example } from './whatever/example';

I suspect I am missing a configuration in the systemjs.config.js.

(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': '/node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      'app': 'app',

      // angular bundles
      // other libraries

    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });
})(this);

Body:
Try adding this in packages:

'.': {
    defaultJSExtensions: 'js'
}

Such that packages now looks like:

// packages tells the System loader how to load when no filename and/or no extension
packages: {
'.': {
    defaultJSExtensions: 'js'
},
app: {
    defaultExtension: 'js'
},
rxjs: {
    defaultExtension: 'js'
    }
}


问:
How to specify legend position in matplotlib in graph coordinates
I am aware of the bbox_to_anchor keyword and this thread, which very helpfully suggests how to manually place the legend:

How to put the legend out of the plot

However, I'd like to use the coordinates of my x- and y-axis in the graph to specify the legend position (inside the plot), as I might need to move the figure into a large figure with a different axis environment, and I don't want to manually play around with those coordinates every time I do this. Is this possible?

Edit: A small example is here:

```<code>import numpy as n
f, axarr = plt.subplots(2,sharex=True)
axarr[1].set_ylim([0.611,0.675])
axarr[0].set_ylim([0.792,0.856])
axarr[0].plot([0, 0.04, 0.08],n.array([ 0.83333333,  0.82250521,0.81109048]), label='test1')
axarr[0].errorbar([0, 0.04, 0.08],n.array([ 0.8,  0.83,   0.82]),n.array([0.1,0.1,0.01]), label='test2')
axarr[1].plot([0, 0.04, 0.08],n.array([ 0.66666667,  0.64888304,  0.63042428]))
axarr[1].errorbar([0, 0.04, 0.08],n.array([ 0.67,  0.64,  0.62]),n.array([ 0.01,  0.05,  0.1]))
axarr[0].legend(bbox_to_anchor=(0.04, 0.82, 1., .102),labelspacing=0.1,       handlelength=0.1, handletextpad=0.1,frameon=False, ncol=4, columnspacing=0.7)
</code>```

I think what confuses me is that the legend does not actually start at 0.82, and indeed for my larger plot (with 5 subplots of this type), I need to use legend coordinates bbox_to_anchor=(0.04, 1.15, 1., .102) in order to make the legend appear on coordinates (0.02, 0.83). But maybe I am getting something else wrong?

答:
You can change location of legend using loc argument.
https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.legend.html?highlight=legend#matplotlib.axes.Axes.legend</p>
```<code>import matplotlib.pyplot as plt

plt.subplot(211)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend above this subplot, expanding itself to
# fully use the given bounding box.
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
           ncol=2, mode="expand", borderaxespad=0.)

plt.subplot(223)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend to the right of this smaller subplot.
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

plt.show()
</code>```

Body:
I am aware of the bbox_to_anchor keyword and this thread, which very helpfully suggests how to manually place the legend:

How to put the legend out of the plot

However, I'd like to use the coordinates of my x- and y-axis in the graph to specify the legend position (inside the plot), as I might need to move the figure into a large figure with a different axis environment, and I don't want to manually play around with those coordinates every time I do this. Is this possible?

Edit: A small example is here:

import numpy as n
f, axarr = plt.subplots(2,sharex=True)
axarr[1].set_ylim([0.611,0.675])
axarr[0].set_ylim([0.792,0.856])
axarr[0].plot([0, 0.04, 0.08],n.array([ 0.83333333,  0.82250521,0.81109048]), label='test1')
axarr[0].errorbar([0, 0.04, 0.08],n.array([ 0.8,  0.83,   0.82]),n.array([0.1,0.1,0.01]), label='test2')
axarr[1].plot([0, 0.04, 0.08],n.array([ 0.66666667,  0.64888304,  0.63042428]))
axarr[1].errorbar([0, 0.04, 0.08],n.array([ 0.67,  0.64,  0.62]),n.array([ 0.01,  0.05,  0.1]))
axarr[0].legend(bbox_to_anchor=(0.04, 0.82, 1., .102),labelspacing=0.1,       handlelength=0.1, handletextpad=0.1,frameon=False, ncol=4, columnspacing=0.7)

I think what confuses me is that the legend does not actually start at 0.82, and indeed for my larger plot (with 5 subplots of this type), I need to use legend coordinates bbox_to_anchor=(0.04, 1.15, 1., .102) in order to make the legend appear on coordinates (0.02, 0.83). But maybe I am getting something else wrong?

Body:
You can change location of legend using loc argument.
https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.legend.html?highlight=legend#matplotlib.axes.Axes.legend

import matplotlib.pyplot as plt

plt.subplot(211)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend above this subplot, expanding itself to
# fully use the given bounding box.
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
           ncol=2, mode="expand", borderaxespad=0.)

plt.subplot(223)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend to the right of this smaller subplot.
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

plt.show()

ContentLicense: CC BY-SA 4.0


问:
LINQ to SQL: Reusing DataContext
I have a number of static methods that perform simple operations like insert or delete a record. All these methods follow this template of using:

```<code>public static UserDataModel FromEmail(string email)
{
    using (var db = new MyWebAppDataContext())
    {
        db.ObjectTrackingEnabled = false;
        return (from u in db.UserDataModels
                where u.Email == email
                select u).Single();
    }
}
</code>```

I also have a few methods that need to perform multiple operations that use a DataContext:

```<code>public static UserPreferencesDataModel Preferences(string email)
{
    return UserDataModel.Preferences(UserDataModel.FromEmail(email));
}

private static UserPreferencesViewModel Preferences(UserDataModel user)
{
    using(var db = new MyWebAppDataContext())
    {
        var preferences = (from u in db.UserDataModels
                          where u == user
                          select u.Preferences).Single();

        return new UserPreferencesViewModel(preferences);
    }
}
</code>```

I like that I can divide simple operations into faux-stored procedures in my data models with static methods like FromEmail(), but I'm concerned about the cost of having Preferences() invoking two connections (right?) via the two using DataContext statements.

Do I need to be? Is what I'm doing less efficient than using a single using(var db = new MyWebAppDataContext()) statement?

答: Normally you should use one context for one logical unit of work. So have a look at the unit of work pattern, ex. http://dotnet.dzone.com/news/using-unit-work-pattern-entity</p>

Title: LINQ to SQL: Reusing DataContext

Body:
I have a number of static methods that perform simple operations like insert or delete a record. All these methods follow this template of using:

public static UserDataModel FromEmail(string email)
{
    using (var db = new MyWebAppDataContext())
    {
        db.ObjectTrackingEnabled = false;
        return (from u in db.UserDataModels
                where u.Email == email
                select u).Single();
    }
}

I also have a few methods that need to perform multiple operations that use a DataContext:

public static UserPreferencesDataModel Preferences(string email)
{
    return UserDataModel.Preferences(UserDataModel.FromEmail(email));
}

private static UserPreferencesViewModel Preferences(UserDataModel user)
{
    using(var db = new MyWebAppDataContext())
    {
        var preferences = (from u in db.UserDataModels
                          where u == user
                          select u.Preferences).Single();

        return new UserPreferencesViewModel(preferences);
    }
}

I like that I can divide simple operations into faux-stored procedures in my data models with static methods like FromEmail(), but I'm concerned about the cost of having Preferences() invoking two connections (right?) via the two using DataContext statements.

Do I need to be? Is what I'm doing less efficient than using a single using(var db = new MyWebAppDataContext()) statement?


问:
Deployment Assembly: The currently displayed page contains invalid values
I imported a Java Web application from Sourceforge, and I did three working weeks efforts to get rid off all red crosses attached to the project name and packages, but now I couldn't make the application run on my Eclipse & tomcat6 developing environment. In project properties when I tried to set the Deployment Assembly, the dialog box showed: the currently displayed page contains invalid values. And in the error log, I found when I click the Deployment Assembly, The following error message was showed:

Error

```<code>
Wed Jan 09 10:25:16 CST 2013
Problems occurred when invoking code from plug-in: "org.eclipse.jface".

java.lang.NullPointerException
    at org.eclipse.wst.common.componentcore.internal.resources.VirtualFolder.getFirstTaggedResource(VirtualFolder.java:185)
    at org.eclipse.jst.j2ee.componentcore.J2EEModuleVirtualComponent.getDefaultDeploymentDescriptorFolder(J2EEModuleVirtualComponent.java:542)
    at org.eclipse.jst.j2ee.internal.ui.JavaEEDeploymentAssemblyAdvancedSectionBuilder.(JavaEEDeploymentAssemblyAdvancedSectionBuilder.java:86)
    at org.eclipse.jst.j2ee.internal.ui.J2EEModuleDependenciesPropertyPage.getAdvancedSectionBuilder(J2EEModuleDependenciesPropertyPage.java:381)
    at org.eclipse.jst.j2ee.internal.ui.J2EEModuleDependenciesPropertyPage.(J2EEModuleDependenciesPropertyPage.java:65)
    at org.eclipse.jst.servlet.ui.internal.WebDependencyPropertyPage.(WebDependencyPropertyPage.java:34)
    at org.eclipse.jst.servlet.ui.internal.WebModuleDependencyPageProvider.createPages(WebModuleDependencyPageProvider.java:54)
    at org.eclipse.wst.common.componentcore.ui.propertypage.ModuleAssemblyRootPage.createContents(ModuleAssemblyRootPage.java:195)
    at org.eclipse.jface.preference.PreferencePage.createControl(PreferencePage.java:232)
    at org.eclipse.wst.common.componentcore.ui.propertypage.ModuleAssemblyRootPage.createControl(ModuleAssemblyRootPage.java:346)
    at org.eclipse.jface.preference.PreferenceDialog.createPageControl(PreferenceDialog.java:1502)
    at org.eclipse.jface.preference.PreferenceDialog$14.run(PreferenceDialog.java:1259)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
    at org.eclipse.ui.internal.JFaceUtil$1.run(JFaceUtil.java:49)
    at org.eclipse.jface.util.SafeRunnable.run(SafeRunnable.java:175)
    at org.eclipse.jface.preference.PreferenceDialog.showPage(PreferenceDialog.java:1253)
    at org.eclipse.ui.internal.dialogs.FilteredPreferenceDialog.showPage(FilteredPreferenceDialog.java:675)
    at org.eclipse.jface.preference.PreferenceDialog$10.run(PreferenceDialog.java:709)
    at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70)
    at org.eclipse.jface.preference.PreferenceDialog$9.selectionChanged(PreferenceDialog.java:705)
    at org.eclipse.jface.viewers.StructuredViewer$3.run(StructuredViewer.java:888)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
    at org.eclipse.ui.internal.JFaceUtil$1.run(JFaceUtil.java:49)
    at org.eclipse.jface.util.SafeRunnable.run(SafeRunnable.java:175)
    at org.eclipse.jface.viewers.StructuredViewer.firePostSelectionChanged(StructuredViewer.java:886)
    at org.eclipse.jface.viewers.StructuredViewer.handlePostSelect(StructuredViewer.java:1226)
    at org.eclipse.jface.viewers.StructuredViewer$5.widgetSelected(StructuredViewer.java:1251)
    at org.eclipse.jface.util.OpenStrategy.firePostSelectionEvent(OpenStrategy.java:262)
    at org.eclipse.jface.util.OpenStrategy.access$5(OpenStrategy.java:256)
    at org.eclipse.jface.util.OpenStrategy$3.run(OpenStrategy.java:433)
    at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35)
    at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:135)
    at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4144)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3761)
    at org.eclipse.jface.window.Window.runEventLoop(Window.java:825)
    at org.eclipse.jface.window.Window.open(Window.java:801)
    at org.eclipse.ui.dialogs.PropertyDialogAction.run(PropertyDialogAction.java:158)
    at org.eclipse.jface.action.Action.runWithEvent(Action.java:498)
    at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:584)
    at org.eclipse.jface.action.ActionContributionItem.access$2(ActionContributionItem.java:501)
    at org.eclipse.jface.action.ActionContributionItem$5.handleEvent(ActionContributionItem.java:411)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1053)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4169)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3758)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$9.run(PartRenderingEngine.java:1022)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:916)
    at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:86)
    at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:585)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:540)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:124)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:353)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:180)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:629)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:584)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1438)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1414)
</code>```

I googled many times , but I cannot find the solutions. Can anyone give a favor to let the Deployment Assembly work? I think this is the key why my app cannot run. Thanks in advance.

答:
Delete  .project .classpath and .settings then cleate a new(temporally) workspace
import your project in the new workspace, this will generate new  .project .classpath and .settings files. Then open the old workspace again and issue is fixed. You can delete the temporally workspace if you don't need it</p>

Body:
I imported a Java Web application from Sourceforge, and I did three working weeks efforts to get rid off all red crosses attached to the project name and packages, but now I couldn't make the application run on my Eclipse & tomcat6 developing environment. In project properties when I tried to set the Deployment Assembly, the dialog box showed: the currently displayed page contains invalid values. And in the error log, I found when I click the Deployment Assembly, The following error message was showed:

Error

Wed Jan 09 10:25:16 CST 2013
Problems occurred when invoking code from plug-in: "org.eclipse.jface".

java.lang.NullPointerException
    at org.eclipse.wst.common.componentcore.internal.resources.VirtualFolder.getFirstTaggedResource(VirtualFolder.java:185)
    at org.eclipse.jst.j2ee.componentcore.J2EEModuleVirtualComponent.getDefaultDeploymentDescriptorFolder(J2EEModuleVirtualComponent.java:542)
    at org.eclipse.jst.j2ee.internal.ui.JavaEEDeploymentAssemblyAdvancedSectionBuilder.(JavaEEDeploymentAssemblyAdvancedSectionBuilder.java:86)
    at org.eclipse.jst.j2ee.internal.ui.J2EEModuleDependenciesPropertyPage.getAdvancedSectionBuilder(J2EEModuleDependenciesPropertyPage.java:381)
    at org.eclipse.jst.j2ee.internal.ui.J2EEModuleDependenciesPropertyPage.(J2EEModuleDependenciesPropertyPage.java:65)
    at org.eclipse.jst.servlet.ui.internal.WebDependencyPropertyPage.(WebDependencyPropertyPage.java:34)
    at org.eclipse.jst.servlet.ui.internal.WebModuleDependencyPageProvider.createPages(WebModuleDependencyPageProvider.java:54)
    at org.eclipse.wst.common.componentcore.ui.propertypage.ModuleAssemblyRootPage.createContents(ModuleAssemblyRootPage.java:195)
    at org.eclipse.jface.preference.PreferencePage.createControl(PreferencePage.java:232)
    at org.eclipse.wst.common.componentcore.ui.propertypage.ModuleAssemblyRootPage.createControl(ModuleAssemblyRootPage.java:346)
    at org.eclipse.jface.preference.PreferenceDialog.createPageControl(PreferenceDialog.java:1502)
    at org.eclipse.jface.preference.PreferenceDialog$14.run(PreferenceDialog.java:1259)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
    at org.eclipse.ui.internal.JFaceUtil$1.run(JFaceUtil.java:49)
    at org.eclipse.jface.util.SafeRunnable.run(SafeRunnable.java:175)
    at org.eclipse.jface.preference.PreferenceDialog.showPage(PreferenceDialog.java:1253)
    at org.eclipse.ui.internal.dialogs.FilteredPreferenceDialog.showPage(FilteredPreferenceDialog.java:675)
    at org.eclipse.jface.preference.PreferenceDialog$10.run(PreferenceDialog.java:709)
    at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70)
    at org.eclipse.jface.preference.PreferenceDialog$9.selectionChanged(PreferenceDialog.java:705)
    at org.eclipse.jface.viewers.StructuredViewer$3.run(StructuredViewer.java:888)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
    at org.eclipse.ui.internal.JFaceUtil$1.run(JFaceUtil.java:49)
    at org.eclipse.jface.util.SafeRunnable.run(SafeRunnable.java:175)
    at org.eclipse.jface.viewers.StructuredViewer.firePostSelectionChanged(StructuredViewer.java:886)
    at org.eclipse.jface.viewers.StructuredViewer.handlePostSelect(StructuredViewer.java:1226)
    at org.eclipse.jface.viewers.StructuredViewer$5.widgetSelected(StructuredViewer.java:1251)
    at org.eclipse.jface.util.OpenStrategy.firePostSelectionEvent(OpenStrategy.java:262)
    at org.eclipse.jface.util.OpenStrategy.access$5(OpenStrategy.java:256)
    at org.eclipse.jface.util.OpenStrategy$3.run(OpenStrategy.java:433)
    at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35)
    at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:135)
    at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4144)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3761)
    at org.eclipse.jface.window.Window.runEventLoop(Window.java:825)
    at org.eclipse.jface.window.Window.open(Window.java:801)
    at org.eclipse.ui.dialogs.PropertyDialogAction.run(PropertyDialogAction.java:158)
    at org.eclipse.jface.action.Action.runWithEvent(Action.java:498)
    at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:584)
    at org.eclipse.jface.action.ActionContributionItem.access$2(ActionContributionItem.java:501)
    at org.eclipse.jface.action.ActionContributionItem$5.handleEvent(ActionContributionItem.java:411)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1053)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4169)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3758)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$9.run(PartRenderingEngine.java:1022)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:916)
    at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:86)
    at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:585)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:540)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:124)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:353)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:180)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:629)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:584)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1438)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1414)

I googled many times , but I cannot find the solutions. Can anyone give a favor to let the Deployment Assembly work? I think this is the key why my app cannot run. Thanks in advance.


问:
Read an array recursively
I am learning how to apply recursion to arrays.

For example, I usually read arrays itiratively, this way:

```<code>void read_array(int *a, int n){
        int i;
        for(i = 0; i < n; ++i)
                scanf("%d", &a[i]);
        return;
}
</code>```

I would like to read an array recursively. I wrote the following function:

```<code>void read_array(int *a, int n){
        int i = n - 1;
        if (n < 0)
                return;
        else{
                if(scanf("%d", &a[n - 1 - i]) == 1){
                        read_array(a, n - 1);
                        return;
                }
        }
}
</code>```

It compiles, but when running it trows a segmentation fault error. It confuses me since the function contemplates a base case 0 that should stop it.

答:
There is a bug in the function.

As the variable i is initialized the following way

```<code>int i = n - 1;
</code>```

then the second argument in this call

```<code>scanf("%d", &a[n - 1 - i])
</code>```

is evaluated like

```<code>scanf("%d", &a[n - 1 - (n - 1)])
</code>```

that is it is always equal to zero

```<code>scanf("%d", &a[0])
</code>```

As the recursive function is called with the same value of the pointer a then all entered values are assigned to a[0]. All other elements of the array are still uninitialized.

Though this does not serve as a reason for the abnormal execution of the function.

It is possible that there is used a big array and the stack is too small to call the function recursively.

In any case the function can be defined more simply and correctly the following way

```<code>size_t read_array( int *a, size_t n )
{
    return n && scanf( "%d", a ) == 1 ? 1 + read_array( a + 1, n - 1 ) : 0;
}
</code>```

Take into account as the input can be interrupted by the user. In this case the function returns the number of initialized elements of the array.

Here is a demonstrative program.

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

size_t read_array( int *a, size_t n )
{
    return n && scanf( "%d", a ) == 1 ? 1 + read_array( a + 1, n - 1 ) : 0;
}

#define N   10

int main(void)
{
    int a[N];

    size_t n = read_array( a, N );

    for ( size_t i = 0; i < n; i++ ) printf( "%d ", a[i] );
    putchar( '\n' );

    return 0;
}
</code>```

If to enter sequence of numbers

```<code>0 1 2 3 4 5 6 7 8 9
</code>```

then the output will be

```<code>0 1 2 3 4 5 6 7 8 9
</code>```

Title: Read an array recursively

Body:
I am learning how to apply recursion to arrays.

For example, I usually read arrays itiratively, this way:

void read_array(int *a, int n){
        int i;
        for(i = 0; i < n; ++i)
                scanf("%d", &a[i]);
        return;
}

I would like to read an array recursively. I wrote the following function:

void read_array(int *a, int n){
        int i = n - 1;
        if (n < 0)
                return;
        else{
                if(scanf("%d", &a[n - 1 - i]) == 1){
                        read_array(a, n - 1);
                        return;
                }
        }
}

It compiles, but when running it trows a segmentation fault error. It confuses me since the function contemplates a base case 0 that should stop it.

Body:
There is a bug in the function.

As the variable i is initialized the following way

int i = n - 1;

then the second argument in this call

scanf("%d", &a[n - 1 - i])

is evaluated like

scanf("%d", &a[n - 1 - (n - 1)])

that is it is always equal to zero

scanf("%d", &a[0])

As the recursive function is called with the same value of the pointer a then all entered values are assigned to a[0]. All other elements of the array are still uninitialized.

Though this does not serve as a reason for the abnormal execution of the function.

It is possible that there is used a big array and the stack is too small to call the function recursively.

In any case the function can be defined more simply and correctly the following way

size_t read_array( int *a, size_t n )
{
    return n && scanf( "%d", a ) == 1 ? 1 + read_array( a + 1, n - 1 ) : 0;
}

Take into account as the input can be interrupted by the user. In this case the function returns the number of initialized elements of the array.

Here is a demonstrative program.

#include <stdio.h>

size_t read_array( int *a, size_t n )
{
    return n && scanf( "%d", a ) == 1 ? 1 + read_array( a + 1, n - 1 ) : 0;
}

#define N   10

int main(void)
{
    int a[N];

    size_t n = read_array( a, N );

    for ( size_t i = 0; i < n; i++ ) printf( "%d ", a[i] );
    putchar( '\n' );

    return 0;
}

If to enter sequence of numbers

0 1 2 3 4 5 6 7 8 9

then the output will be

0 1 2 3 4 5 6 7 8 9


问:
SonarQube Language sonar.lang.patterns error
Our Sonar Build Environment details as follows:

```<code>* SonarQube Server Version - 5.6.6 (64-Bit).
* Sonar Client Build Operating System – Windows-7 (64-Bit).
* Sonar-scanner- Version - 3.0.3.778.
* sonar-cxx-plugin-0.9.7.jar
* sonar-csharp-plugin Version -5.11.0.1761.
* sonar-objective-c-plugin-0.5.0-SNAPSHOT.jar
* Source Code Language: C# and C++
</code>```

Our SonarQube server is centralized server, So have installed (cxx-plugin, objective-c-plugin and csharp-plugin)

Current Problem:

When we scan the code, if fails with below error. Since we have multiple language (C# and C++) code, Both the language has to be scanned at a time.

ERROR: Caused by: Language of file 'workspace/HS30/baseclasses/ametex.h' can not be decided as the file matches patterns of both sonar.lang.patterns.c++ : **/*.cxx,**/*.cpp,**/*.cc,**/*.c,**/*.hxx,**/*.hpp,**/*.hh,**/*.h and sonar.lang.patterns.objectivec : **/*.h,**/*.m

sonar.language=cs,c++ (Tried but didn't work)

So kindly help us to resolve the same.

答:
This is a question of which language "claims" .h files. Only one language can claim any given file extension and currently you have two languages claiming .h, so the scanner can't figure out which analyzer to give those files to, and gives up.

Specifically, from your error message:

```<code>the file matches patterns of both sonar.lang.patterns.c++ : **/*.cxx,**/*.cpp,**/*.cc,**/*.c,**/*.hxx,**/*.hpp,**/*.hh,**/*.h and sonar.lang.patterns.objectivec : **/*.h,**/*.m
</code>```

You have both cxx and objectivec claiming .h. You must remove the extension from one of those two lists.

Go to (Global) Administration > [Language] > [Language] file suffixes to edit the extensions claimed by each language, and remove .h from one or both languages.

Make sure that you do not leave either of these fields blank. If left blank, the default value (which includes .h) will be used.

Body:
Our Sonar Build Environment details as follows:

* SonarQube Server Version - 5.6.6 (64-Bit).
* Sonar Client Build Operating System – Windows-7 (64-Bit).
* Sonar-scanner- Version - 3.0.3.778.
* sonar-cxx-plugin-0.9.7.jar
* sonar-csharp-plugin Version -5.11.0.1761.
* sonar-objective-c-plugin-0.5.0-SNAPSHOT.jar
* Source Code Language: C# and C++

Our SonarQube server is centralized server, So have installed (cxx-plugin, objective-c-plugin and csharp-plugin)

Current Problem:

When we scan the code, if fails with below error. Since we have multiple language (C# and C++) code, Both the language has to be scanned at a time.

ERROR: Caused by: Language of file 'workspace/HS30/baseclasses/ametex.h' can not be decided as the file matches patterns of both sonar.lang.patterns.c++ : **/*.cxx,**/*.cpp,**/*.cc,**/*.c,**/*.hxx,**/*.hpp,**/*.hh,**/*.h and sonar.lang.patterns.objectivec : **/*.h,**/*.m

sonar.language=cs,c++ (Tried but didn't work)

So kindly help us to resolve the same.

Body:
This is a question of which language "claims" .h files. Only one language can claim any given file extension and currently you have two languages claiming .h, so the scanner can't figure out which analyzer to give those files to, and gives up.

Specifically, from your error message:

the file matches patterns of both sonar.lang.patterns.c++ : **/*.cxx,**/*.cpp,**/*.cc,**/*.c,**/*.hxx,**/*.hpp,**/*.hh,**/*.h and sonar.lang.patterns.objectivec : **/*.h,**/*.m

You have both cxx and objectivec claiming .h. You must remove the extension from one of those two lists.

Go to (Global) Administration > [Language] > [Language] file suffixes to edit the extensions claimed by each language, and remove .h from one or both languages.

Make sure that you do not leave either of these fields blank. If left blank, the default value (which includes .h) will be used.


问:
How to consume Web API without server side code, using only Ajax
I Added the following two host entries to my host file:

127.0.0.1 na_api.com

127.0.0.1 na_upload.com

The 127.0.0.1 na_api.com is used to retrieve some data from a database and return JSON, while the 127.0.0.1 na_upload.com is a website that consumes the API.

Currently, I have the following Ajax call, to call the API and get some data. Here is the Ajax call:

```<code>this.ajaxRetrieve = function (url, data, onSuccessCallback) {
    $.ajax({
        url: url,
        data: data,
        type: 'GET',
        crossDomain: true,
        onsuccess: function (result) {
            onSuccessCallback(result);
        }
    });
}
</code>```

The above outputs the following error:

No 'Access-Control-Allow-Origin' header is present on the requested resource

How can I work around this, without the needs of a back-end server side code like .Net or something?

答:
use JSONP</p>

```<code>$.ajax({
                                url: url,
                                type: 'GET',
                                crossDomain: true,
                                contentType: "text/json",
                                dataType: "jsonp",
                                success: function (data) { // },
                                error: function (xhr, status, error) { }
                          });
</code>```

Body:
I Added the following two host entries to my host file:

127.0.0.1 na_api.com

127.0.0.1 na_upload.com

The 127.0.0.1 na_api.com is used to retrieve some data from a database and return JSON, while the 127.0.0.1 na_upload.com is a website that consumes the API.

Currently, I have the following Ajax call, to call the API and get some data. Here is the Ajax call:

this.ajaxRetrieve = function (url, data, onSuccessCallback) {
    $.ajax({
        url: url,
        data: data,
        type: 'GET',
        crossDomain: true,
        onsuccess: function (result) {
            onSuccessCallback(result);
        }
    });
}

The above outputs the following error:

No 'Access-Control-Allow-Origin' header is present on the requested resource

How can I work around this, without the needs of a back-end server side code like .Net or something?

Body:
use JSONP

$.ajax({
                                url: url,
                                type: 'GET',
                                crossDomain: true,
                                contentType: "text/json",
                                dataType: "jsonp",
                                success: function (data) { // },
                                error: function (xhr, status, error) { }
                          });


问:
IntelliJ Idea Scala files not available in 'New' context menu
I am new to both IntelliJ and Scala. I am attending the course "Functional Programming Principles in Scala" on Coursera. I downloaded the zip file for the sample assignment, which contained a sample Scala project.

I imported the project successfully (I guess) in IntelliJ. However, when I right-click on a package in the project explorer, there are no Scala-related templates. I can only select "New Java class", XML files and some forms.

Does anyone know why this happens and if there is another way to create a new Scala class or object from a template?

Thanks.

答:
Yes, you need to make the scala directory a source directory (in Menu / Project structure / Modules ) but I also had to do the following:

Still in Project Structure goto Global libraries.

Select Scala SDK.

Right click the Scala SDK and Add to module...

Now my context menu gives me New / Scala class and so on.


问:
Change the 'option' color with the attribute 'disabled'
I would like to change the font color of an <option> with the attribute disabled.

I have tried this

```<code>option:disabled { color: red }
</code>```

and this

```<code>option[disabled] { color: red }
</code>```

Both work but the color only gets red when you CLICK on the select field. By default it is black. How can I change it?

Here is an example: http://jsfiddle.net/y0g0stbb/

答:
With a little bit of Javascript you can do something like this if there are no selected valid option:

```<code><select class="">[options]</select>
</code>```

And if there a selected valid option you simple put some class through javascript in the select element:

```<code><select class="selected">[options]</select>
</code>```

And then in your CSS:

```<code>select{
 color: [not selected color];
}
select.selected{
 color: [selected color];
}
</code>```

Body:
I would like to change the font color of an <option> with the attribute disabled.

I have tried this

option:disabled { color: red }

and this

option[disabled] { color: red }

Both work but the color only gets red when you CLICK on the select field. By default it is black. How can I change it?

Here is an example: http://jsfiddle.net/y0g0stbb/

Body:
With a little bit of Javascript you can do something like this if there are no selected valid option:

<select class="">[options]</select>

And if there a selected valid option you simple put some class through javascript in the select element:

<select class="selected">[options]</select>

And then in your CSS:

select{
 color: [not selected color];
}
select.selected{
 color: [selected color];
}


问:
Regular expression in HTML - Command OR
I have this:

```<code><input type="text" name="funkce<%=i %>" value="" size="20" data-toogle="tooltip" title="Vlož hodnoty a-z o maximální délce 3 znaky." style="width: 50px; padding: 2px" required maxlength="3"  pattern="([a-z]{1,3})|(([a-z]{1}[\s,]+)*[a-z]{1})" />
</code>```

It is not working I need control input for two types string.
I need insert example "a,b,c" or "abc", but or (|) in pattern is not working :(

答:
Your pattern is working. It is checked onsubmit, not onkeydown nor onkeypress.

However, the pattern is nondeterministic. It should be writen in such a way that every character is matched by at most one subpattern. In this case, deterministic version is: [a-z](([a-z]{1,2})|([\s,]+[a-z])*)

Also maxlength="3" will not work with input a,b,c.

Title: Regular expression in HTML - Command OR

Body:
I have this:

<input type="text" name="funkce<%=i %>" value="" size="20" data-toogle="tooltip" title="Vlož hodnoty a-z o maximální délce 3 znaky." style="width: 50px; padding: 2px" required maxlength="3"  pattern="([a-z]{1,3})|(([a-z]{1}[\s,]+)*[a-z]{1})" />

It is not working I need control input for two types string.
I need insert example "a,b,c" or "abc", but or (|) in pattern is not working :(


问:
Javascript sum of arrays and average
I have an issue with getting the sum of two arrays and combining their averages while rounding off.

I don't want to hardcode but rather pass two random arrays.
so here is the code but it keeps returning NaN

function sumAverage(arr) {
  var result = 0;
  // Your code here
  // set an array
  arr = [];
  a = [];
  b = [];
  arr[0] = a;
  arr[1] = b;

  var sum = 0;

  // compute sum of elements in the array
  for (var j = 0; j < a.length; j++) {
    sum += a[j];
  }

  // get the  average of elements in the array
  var total = 0;
  total += sum / a.length;

  var add = 0;

  for (var i = 0; i < b.length; i++)
    add += b[i];

  var math = 0;
  math += add / b.length;

  result += math + total;

  Math.round(result);

  return result;
}
console.log(sumAverage([
  [2, 3, 4, 5],
  [6, 7, 8, 9]
]));```

答:
Because you are assigning the value [] with the same name as the argument? This works, see jFiddle</p>

```<code>function sumAverage(arr) {
  var result = 0;

  //arr = [];
  //a = [];
  //b = [];
  a = arr[0];
  b = arr[1];

  var sum = 0;

  // compute sum of elements in the array
  for(var j = 0; j < a.length; j++ ){
    sum += a[j] ;
  }

// get the  average of elements in the array
var total = 0;
total += sum / a.length;

var add = 0;

for(var i = 0; i < b.length; i++)
    add += b[i];

  var math = 0;
  math += add / b.length;
  result += math + total;

Math.round(result);
  return result;
}
document.write(sumAverage([[2,3,4,5], [6,7,8,9]]));
</code>```

Title: Javascript sum of arrays and average

Body:
Because you are assigning the value [] with the same name as the argument? This works, see jFiddle

function sumAverage(arr) {
  var result = 0;

  //arr = [];
  //a = [];
  //b = [];
  a = arr[0];
  b = arr[1];

  var sum = 0;

  // compute sum of elements in the array
  for(var j = 0; j < a.length; j++ ){
    sum += a[j] ;
  }

// get the  average of elements in the array
var total = 0;
total += sum / a.length;

var add = 0;

for(var i = 0; i < b.length; i++)
    add += b[i];

  var math = 0;
  math += add / b.length;
  result += math + total;

Math.round(result);
  return result;
}
document.write(sumAverage([[2,3,4,5], [6,7,8,9]]));


问:
Twilio answering machine detection not leaving message
We are leaving a voice message (using an MP3) using Twilio's answering machine detection. We are seeing in our logs the correct calls to/from the API (answered by answering machine, post of our recorded message)...no error.

But the persons were are testing on, only 1/4 are actually getting a voicemail. The rest receive no voicemail, even though the logs show the correct API calls...? What is happening here?

Here is the code to call the twiml.

```<code> if (Request.Form["AnsweredBy"] != null)
        {
            switch (Request.Form["AnsweredBy"])
            {
                case "machine_end_beep":
                case "machine_end_silence":
                case "machine_end_other":
                    SaveTwilioMessage(transaction.Campaign.Id.ToString());
                    //var machineResponse = new VoiceResponse();
                    if (!string.IsNullOrWhiteSpace(transaction.Campaign.VoicemailMessageUrl))
                    {
                        response.Play(transaction.Campaign.VoicemailMessageUrl);
                    }
                    else
                    {
                        response.Say(transaction.Campaign.VoicemailMessage, voice: _voice);
                    }
                    return new TwiMLResult(response);
                case "human":
                case "fax":
                case "unknown":
                default:
                    break;
            }
</code>```

And here is the call that generates this:

```<code> var call = await CallResource.CreateAsync(url: callbackUrl, to: new PhoneNumber(phoneNumber), from: new PhoneNumber(fromPhone),machineDetection: "DetectMessageEnd");
        var result = new TelephonicResource(call.Sid);
        return result;
</code>```

Any thoughts?

答:
Answering my own question here. Finally got some support from Twilio after pushing up through sales - after ticket remained open and unworked for days.

Basically, if you want to pull off AMD successfully, you need to be able to respond within 150ms. On our calls, the voice mails were starting, detecting no sound, and saying "we're sorry, but you're not talking...then our message would start". The correction was to do less DB lookups in our API calls by changing programming practice, and moving our MP3 to somewhere on the East coast (AWS preferred).

We investigated this...and found that while our API response was taking ~1 second, the AMD was sometimes waiting 15+ seconds after the beep to play the message. Still confused.

Body:
We are leaving a voice message (using an MP3) using Twilio's answering machine detection. We are seeing in our logs the correct calls to/from the API (answered by answering machine, post of our recorded message)...no error.

But the persons were are testing on, only 1/4 are actually getting a voicemail. The rest receive no voicemail, even though the logs show the correct API calls...? What is happening here?

Here is the code to call the twiml.

 if (Request.Form["AnsweredBy"] != null)
        {
            switch (Request.Form["AnsweredBy"])
            {
                case "machine_end_beep":
                case "machine_end_silence":
                case "machine_end_other":
                    SaveTwilioMessage(transaction.Campaign.Id.ToString());
                    //var machineResponse = new VoiceResponse();
                    if (!string.IsNullOrWhiteSpace(transaction.Campaign.VoicemailMessageUrl))
                    {
                        response.Play(transaction.Campaign.VoicemailMessageUrl);
                    }
                    else
                    {
                        response.Say(transaction.Campaign.VoicemailMessage, voice: _voice);
                    }
                    return new TwiMLResult(response);
                case "human":
                case "fax":
                case "unknown":
                default:
                    break;
            }

And here is the call that generates this:

 var call = await CallResource.CreateAsync(url: callbackUrl, to: new PhoneNumber(phoneNumber), from: new PhoneNumber(fromPhone),machineDetection: "DetectMessageEnd");
        var result = new TelephonicResource(call.Sid);
        return result;

Any thoughts?


问:
Adding multiple SQL queries to same Datagrid c# WPF
So... I have a datagrid that I want to populate with the medication details selected in the combobox. I want to add a new row with the new medication selected from the combobox each time a button is clicked. I am running the below method in a button click event.

```<code>private void FillSalesItemGrid()
        {

            using (SqlConnection con = new SqlConnection(conn))
            {

                con.Open();

                if (!string.IsNullOrEmpty(comboBox_select_Item.Text.ToString()))
                {
                    sqlBuilder.Append("SELECT * FROM Medication WHERE MedName = @medName");
                    cParameters.Add(new SqlParameter("@medName", comboBox_select_Item.Text.ToString()));
                }

                SqlCommand cmd = new SqlCommand(sqlBuilder.ToString(), con);
                if (cParameters.Count != 0)
                {
                    cmd.Parameters.AddRange(cParameters.ToArray());
                }
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable("Medication");
                da.Fill(dt);

                dataGrid_saleItems.ItemsSource = dt.AsDataView();
                sqlBuilder.Clear();
                cParameters.Clear();

            }
</code>```

At the moment it displays the currently selected combobox item. It doesnt add a new "result" each time the button is clicked. I want it to work as if you were ringing up an item on a POS. Any help will be appreciated.

答:
Instead of creating a new Datatable each time you have to create it once and then fill it up with each function call (SqlDataAdapter.Fill does exactly that).
That way you also only set the itemsource once.

Second solution would be to retrieve the current itemsource, convert it to a DataTable.
Someething like: DataTable table = (dataGrid_saleItems.ItemsSource as DataRowView).toTable()
If you continue with your code that will fill it up aswell.

Body:
So... I have a datagrid that I want to populate with the medication details selected in the combobox. I want to add a new row with the new medication selected from the combobox each time a button is clicked. I am running the below method in a button click event.

private void FillSalesItemGrid()
        {

            using (SqlConnection con = new SqlConnection(conn))
            {

                con.Open();

                if (!string.IsNullOrEmpty(comboBox_select_Item.Text.ToString()))
                {
                    sqlBuilder.Append("SELECT * FROM Medication WHERE MedName = @medName");
                    cParameters.Add(new SqlParameter("@medName", comboBox_select_Item.Text.ToString()));
                }

                SqlCommand cmd = new SqlCommand(sqlBuilder.ToString(), con);
                if (cParameters.Count != 0)
                {
                    cmd.Parameters.AddRange(cParameters.ToArray());
                }
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable("Medication");
                da.Fill(dt);

                dataGrid_saleItems.ItemsSource = dt.AsDataView();
                sqlBuilder.Clear();
                cParameters.Clear();

            }

At the moment it displays the currently selected combobox item. It doesnt add a new "result" each time the button is clicked. I want it to work as if you were ringing up an item on a POS. Any help will be appreciated.


问:
Assigning text to a local variable in Typescript
In Typescript I am trying to read an XML file with some javascript code and add the text content to a local variable with the following code:

```<code>import { Injectable } from '@angular/core';

@Injectable()
export class JsonreaderService {

private jsonText: string;

constructor() {
  this.readTextFile("../../assets/content.json");
}

readTextFile(file)
{
  let jsonText: string;
  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", file, false);
  rawFile.onreadystatechange = function ()
  {
    if(rawFile.readyState === 4)
    {
      if(rawFile.status === 200 || rawFile.status == 0)
      {
        this.jsonText = rawFile.responseText;
      }
    }
  }
  rawFile.send(null);
}
}
</code>```

I am trying to assign the text within the json file to my private local variable jsonText: this.jsonText = rawFile.responseText; which are both of the type 'string'.

When I try this I get the error:

Property 'jsonText' does not exist on type 'XMLHttpRequest'

Does somebody know how I can do this within typescript? When I remove this. - the responseText can be defined to the jsonText variable which is within the function readTextFile(file)

答:
I guess you should hold a reference to class somewhere, like:</p>

```<code>import { Injectable } from '@angular/core';

@Injectable()
export class JsonreaderService {

private jsonText: string;

constructor() {
  this.readTextFile("../../assets/content.json");
}

readTextFile(file)
{
  var self = this;
  let jsonText: string;
  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", file, false);
  rawFile.onreadystatechange = function ()
  {
    if(rawFile.readyState === 4)
    {
      if(rawFile.status === 200 || rawFile.status == 0)
      {
        self.jsonText = rawFile.responseText;
      }
    }
  }
  rawFile.send(null);
}
}
</code>```

Body:
In Typescript I am trying to read an XML file with some javascript code and add the text content to a local variable with the following code:

import { Injectable } from '@angular/core';

@Injectable()
export class JsonreaderService {

private jsonText: string;

constructor() {
  this.readTextFile("../../assets/content.json");
}

readTextFile(file)
{
  let jsonText: string;
  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", file, false);
  rawFile.onreadystatechange = function ()
  {
    if(rawFile.readyState === 4)
    {
      if(rawFile.status === 200 || rawFile.status == 0)
      {
        this.jsonText = rawFile.responseText;
      }
    }
  }
  rawFile.send(null);
}
}

I am trying to assign the text within the json file to my private local variable jsonText: this.jsonText = rawFile.responseText; which are both of the type 'string'.

When I try this I get the error:

Property 'jsonText' does not exist on type 'XMLHttpRequest'

Does somebody know how I can do this within typescript? When I remove this. - the responseText can be defined to the jsonText variable which is within the function readTextFile(file)

Body:
I guess you should hold a reference to class somewhere, like:

import { Injectable } from '@angular/core';

@Injectable()
export class JsonreaderService {

private jsonText: string;

constructor() {
  this.readTextFile("../../assets/content.json");
}

readTextFile(file)
{
  var self = this;
  let jsonText: string;
  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", file, false);
  rawFile.onreadystatechange = function ()
  {
    if(rawFile.readyState === 4)
    {
      if(rawFile.status === 200 || rawFile.status == 0)
      {
        self.jsonText = rawFile.responseText;
      }
    }
  }
  rawFile.send(null);
}
}


问:
Know in `activate` if the navigation was due to clicking on the nav-bar
I am trying to get 3 different routing "styles" in my application.  I need to identify these in each view-model's activate method:

User clicks a button or link in my app that causes my app to call this.router.navigate()

This one is easy because I always put a parameter into the URL, so in the target View-Model, I have that param in my activate method.

The users presses the back or forward buttons or loads the application for the first time.

I can also get this by using the this.router.isExplicitNavigation variable or checking if my state is uninitalized.

The user clicks on one of the views displayed in the nav-bar (setup in the app.ts configureRouter method).

Unfortunately I cannot find a way to distinguish this one from when the user presses the back and forward buttons on the browser.

So here is my question, is there a way to know when a view-model's activate method has been called because a user selected a nav-bar route?

答:
If I understand your question correctly, you want distinguish between 1. and 3. In activate(), you receive all routing parameters (as the method's first argument), both:

from the route-template, such as /myRoute/:myparam

from the query string

So I'd suggest to put a query parameter for the menu bar, which parameter you can read in activate(). For example:

let's say your route /myRoute

from the button, simply navigate to /myRoute

from the navbar, navigate to /myRoute?from=navbar

You might know this, but you have multiple options to navigate from code:

router.navigate('compose your route manually')

router.navigateToRoute('route's name', parameters)

in template, using route-href="route: 'myRoute'; params.bind={...}" >

Your code:

```<code>//button
router.navigateToRoute('my-route');

//navbar
router.navigateToRoute('my-route', {from: 'navbar'});

//destination view-model
activate(params: Object): void {
    if (params.from === 'navbar')
        //routed from the navbar
    else
        //routed from a button
}
</code>```

Body:
If I understand your question correctly, you want distinguish between 1. and 3. In activate(), you receive all routing parameters (as the method's first argument), both:

from the route-template, such as /myRoute/:myparam

from the query string

So I'd suggest to put a query parameter for the menu bar, which parameter you can read in activate(). For example:

let's say your route /myRoute

from the button, simply navigate to /myRoute

from the navbar, navigate to /myRoute?from=navbar

You might know this, but you have multiple options to navigate from code:

router.navigate('compose your route manually')

router.navigateToRoute('route's name', parameters)

in template, using <a route-href="route: 'myRoute'; params.bind={...}" >

Your code:

//button
router.navigateToRoute('my-route');

//navbar
router.navigateToRoute('my-route', {from: 'navbar'});

//destination view-model
activate(params: Object): void {
    if (params.from === 'navbar')
        //routed from the navbar
    else
        //routed from a button
}


问:
how to convert date time to only time in c#
i want to convert datetime format to only time format.

data type - string

```<code>op- 5/31/2017 8:43:20 PM
req op - 8:43 (in 24 hours format)
</code>```

code

```<code>TankDetailsModel.UpdatedTime = TimeZoneInfo.ConvertTimeFromUtc(item.timestamp, TimeZoneInfo.FindSystemTimeZoneById("India Standard Time")).ToString();
</code>```

答:
You can get it like this.

```<code>    DateTime dt = DateTime.Now;
    var x = dt.ToString("HH:mm");
</code>```

Hope this will work.

Body:
i want to convert datetime format to only time format.

data type - string

op- 5/31/2017 8:43:20 PM
req op - 8:43 (in 24 hours format)

code

TankDetailsModel.UpdatedTime = TimeZoneInfo.ConvertTimeFromUtc(item.timestamp, TimeZoneInfo.FindSystemTimeZoneById("India Standard Time")).ToString();

Body:
You can get it like this.

    DateTime dt = DateTime.Now;
    var x = dt.ToString("HH:mm");

Hope this will work.


问:
'receiver type mismatch' with Fragment and Anko toast
I am trying to use Jetbrains' Anko library to easily display an Android toast message in my app.

Here is the relevant code snippet:

```<code>val message : CharSequence = "Recycled: ${holder.taskEditText.text}"
(tasksFragment as Fragment).toast(text = message)
</code>```

and the error:

```<code>Error:(80, 45) Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public inline fun Fragment.toast(text: CharSequence): Unit defined in org.jetbrains.anko
public inline fun Fragment.toast(textResource: Int): Unit defined in org.jetbrains.anko
public fun Context.toast(text: CharSequence): Unit defined in org.jetbrains.anko
public fun Context.toast(textResource: Int): Unit defined in org.jetbrains.anko
public inline fun AnkoContext<*>.toast(text: CharSequence): Unit defined in org.jetbrains.anko
public inline fun AnkoContext<*>.toast(textResource: Int): Unit defined in org.jetbrains.anko
</code>```

I am pretty new to Kotlin and have been searching for a solution to this issue for a while. All help is appreciated.

答:
Since the error says none are applicable you've probably imported a different Fragment class than the one defined by Android/Support Library.

Check your imports.

Body:
I am trying to use Jetbrains' Anko library to easily display an Android toast message in my app.

Here is the relevant code snippet:

val message : CharSequence = "Recycled: ${holder.taskEditText.text}"
(tasksFragment as Fragment).toast(text = message)

and the error:

Error:(80, 45) Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public inline fun Fragment.toast(text: CharSequence): Unit defined in org.jetbrains.anko
public inline fun Fragment.toast(textResource: Int): Unit defined in org.jetbrains.anko
public fun Context.toast(text: CharSequence): Unit defined in org.jetbrains.anko
public fun Context.toast(textResource: Int): Unit defined in org.jetbrains.anko
public inline fun AnkoContext<*>.toast(text: CharSequence): Unit defined in org.jetbrains.anko
public inline fun AnkoContext<*>.toast(textResource: Int): Unit defined in org.jetbrains.anko

I am pretty new to Kotlin and have been searching for a solution to this issue for a while. All help is appreciated.


答:
The problem is that you are emptying arr by saying arr = [].

Later, you are iterating over a which is empty too.
Again when you say total += sum / a.length;, sum is 0 and a.length is 0 so 0/0 becomes NaN. Similarly for math. Adding Nan to NaN is again NaN and that's what you get.

Solution is to not empty passed arr and modify your code like below:

function sumAverage(arr) {
  var result = 0;
  // Your code here
  // set an array
  //arr = [];
  //a = [];
  //b = [];
  a = arr[0];
  b = arr[1];

  var sum = 0;

  // compute sum of elements in the array
  for (var j = 0; j < a.length; j++) {
    sum += a[j];
  }

  // get the  average of elements in the array
  var total = 0;
  total = sum / a.length;

  var add = 0;

  for (var i = 0; i < b.length; i++)
    add += b[i];

  var math = 0;
  math = add / b.length;

  result = math + total;

  result = Math.round(result);

  return result;
}
console.log(sumAverage([
  [2, 3, 4, 5],
  [6, 7, 8, 9]
]));```

Title: Javascript sum of arrays and average

Body:
I have an issue with getting the sum of two arrays and combining their averages while rounding off.

I don't want to hardcode but rather pass two random arrays.
so here is the code but it keeps returning NaN

function sumAverage(arr) {
  var result = 0;
  // Your code here
  // set an array
  arr = [];
  a = [];
  b = [];
  arr[0] = a;
  arr[1] = b;

  var sum = 0;

  // compute sum of elements in the array
  for (var j = 0; j < a.length; j++) {
    sum += a[j];
  }

  // get the  average of elements in the array
  var total = 0;
  total += sum / a.length;

  var add = 0;

  for (var i = 0; i < b.length; i++)
    add += b[i];

  var math = 0;
  math += add / b.length;

  result += math + total;

  Math.round(result);

  return result;
}
console.log(sumAverage([
  [2, 3, 4, 5],
  [6, 7, 8, 9]
]));


答:
As said in comments, you reset your arguments...

Use the variable "arguments" for dynamic function parameters.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

Title: Javascript sum of arrays and average


问:
MongoDB: Is it possible to make a case-insensitive query?
Example:</p>

```<code>> db.stuff.save({"foo":"bar"});

> db.stuff.find({"foo":"bar"}).count();
1
> db.stuff.find({"foo":"BAR"}).count();
0
</code>```

答:
UPDATE:

The original answer is now obsolete. Mongodb now supports advanced full text searching, with many features.

ORIGINAL ANSWER:

It should be noted that searching with regex's case insensitive /i means that mongodb cannot search by index, so queries against large datasets can take a long time.

Even with small datasets, it's not very efficient.  You take a far bigger cpu hit than your query warrants, which could become an issue if you are trying to achieve scale.

As an alternative, you can store an uppercase copy and search against that.  For instance, I have a User table that has a username which is mixed case, but the id is an uppercase copy of the username.  This ensures case-sensitive duplication is impossible (having both "Foo" and "foo" will not be allowed), and I can search by id = username.toUpperCase() to get a case-insensitive search for username.

If your field is large, such as a message body, duplicating data is probably not a good option.  I believe using an extraneous indexer like Apache Lucene is the best option in that case.

Body:
Example:

> db.stuff.save({"foo":"bar"});

> db.stuff.find({"foo":"bar"}).count();
1
> db.stuff.find({"foo":"BAR"}).count();
0