问:
Group columns in a dataframe and subset using a condition
I have a dataframe like this

```<code>ID <- c("ID001","ID001","ID001","ID001","ID001","ID001","ID001",
        "ID002","ID002","ID002","ID002","ID002")
Type <- c("A","A","A","A","A","A","A",
          "B","B","B","B","B")
Measurement <- c("Length","Summary","Breadth","Length","Summary","Breadth","Summary",
                 "Length","Summary","Breadth","Breadth","Summary")
PassFail <- c("PASS","PASS","PASS","FAIL_PTS","FAIL","FAIL_AVG_HI","FAIL",
              "PASS","FAIL_PTS","FAIL","FAIL_AVG_LOW","FAIL")
ToolID <- c("SWP","SWP","SWP","ISP","ISP","IKS","IKS",
            "PSX","PSX","PSX","PZY","PZY")

df <- data.frame(ID,Type,Measurement,PassFail,ToolID)
df

      ID Type Measurement     PassFail ToolID
   ID001    A      Length         PASS    SWP
   ID001    A     Summary         PASS    SWP
   ID001    A     Breadth         PASS    SWP
   ID001    A      Length     FAIL_PTS    ISP
   ID001    A     Summary         FAIL    ISP
   ID001    A     Breadth  FAIL_AVG_HI    IKS
   ID001    A     Summary         FAIL    IKS
   ID002    B      Length         PASS    PSX
   ID002    B     Summary     FAIL_PTS    PSX
   ID002    B     Breadth         FAIL    PSX
   ID002    B     Breadth FAIL_AVG_LOW    PZY
   ID002    B     Summary         FAIL    PZY
</code>```

I am trying to subset this data frame using a condition like this: When the  passfail = 'FAIL_AVG_HI' or 'FAIL_AVG_LOW', I would like to remove the rows in that group (ID,Type,ToolID).

My desired output would look like this

```<code>     ID Type Measurement PassFail ToolID
  ID001    A      Length     PASS    SWP
  ID001    A     Summary     PASS    SWP
  ID001    A     Breadth     PASS    SWP
  ID001    A      Length FAIL_PTS    ISP
  ID001    A     Summary     FAIL    ISP
  ID002    B      Length     PASS    PSX
  ID002    B     Summary FAIL_PTS    PSX
  ID002    B     Breadth     FAIL    PSX
</code>```

I am messing it up with the grouping to remove the rows. I can delete the row that has the above passfail values but how to group them and delete any rows that belong to the group?

I am doing it this way to remove 1 row

```<code>df <- subset(df,df$PassFail != 'FAIL_AVG_HI' | df$PassFail != 'FAIL_AVG_LOW')
</code>```

答:
You can use group_by %>% filter:

```<code>library(dplyr)
df %>%
      group_by(ID, Type, ToolID) %>%
      filter(!any(PassFail %in% c('FAIL_AVG_HI', 'FAIL_AVG_LOW')))

#Source: local data frame [8 x 5]
#Groups: ID, Type, ToolID [3]

#      ID   Type Measurement PassFail ToolID
#  <fctr> <fctr>      <fctr>   <fctr> <fctr>
#1  ID001      A      Length     PASS    SWP
#2  ID001      A     Summary     PASS    SWP
#3  ID001      A     Breadth     PASS    SWP
#4  ID001      A      Length FAIL_PTS    ISP
#5  ID001      A     Summary     FAIL    ISP
#6  ID002      B      Length     PASS    PSX
#7  ID002      B     Summary FAIL_PTS    PSX
#8  ID002      B     Breadth     FAIL    PSX
</code>```

Body:
I have a dataframe like this

ID <- c("ID001","ID001","ID001","ID001","ID001","ID001","ID001",
        "ID002","ID002","ID002","ID002","ID002")
Type <- c("A","A","A","A","A","A","A",
          "B","B","B","B","B")
Measurement <- c("Length","Summary","Breadth","Length","Summary","Breadth","Summary",
                 "Length","Summary","Breadth","Breadth","Summary")
PassFail <- c("PASS","PASS","PASS","FAIL_PTS","FAIL","FAIL_AVG_HI","FAIL",
              "PASS","FAIL_PTS","FAIL","FAIL_AVG_LOW","FAIL")
ToolID <- c("SWP","SWP","SWP","ISP","ISP","IKS","IKS",
            "PSX","PSX","PSX","PZY","PZY")

df <- data.frame(ID,Type,Measurement,PassFail,ToolID)
df

      ID Type Measurement     PassFail ToolID
   ID001    A      Length         PASS    SWP
   ID001    A     Summary         PASS    SWP
   ID001    A     Breadth         PASS    SWP
   ID001    A      Length     FAIL_PTS    ISP
   ID001    A     Summary         FAIL    ISP
   ID001    A     Breadth  FAIL_AVG_HI    IKS
   ID001    A     Summary         FAIL    IKS
   ID002    B      Length         PASS    PSX
   ID002    B     Summary     FAIL_PTS    PSX
   ID002    B     Breadth         FAIL    PSX
   ID002    B     Breadth FAIL_AVG_LOW    PZY
   ID002    B     Summary         FAIL    PZY

I am trying to subset this data frame using a condition like this: When the  passfail = 'FAIL_AVG_HI' or 'FAIL_AVG_LOW', I would like to remove the rows in that group (ID,Type,ToolID).

My desired output would look like this

     ID Type Measurement PassFail ToolID
  ID001    A      Length     PASS    SWP
  ID001    A     Summary     PASS    SWP
  ID001    A     Breadth     PASS    SWP
  ID001    A      Length FAIL_PTS    ISP
  ID001    A     Summary     FAIL    ISP
  ID002    B      Length     PASS    PSX
  ID002    B     Summary FAIL_PTS    PSX
  ID002    B     Breadth     FAIL    PSX

I am messing it up with the grouping to remove the rows. I can delete the row that has the above passfail values but how to group them and delete any rows that belong to the group?

I am doing it this way to remove 1 row

df <- subset(df,df$PassFail != 'FAIL_AVG_HI' | df$PassFail != 'FAIL_AVG_LOW')

Body:
You can use group_by %>% filter:

library(dplyr)
df %>%
      group_by(ID, Type, ToolID) %>%
      filter(!any(PassFail %in% c('FAIL_AVG_HI', 'FAIL_AVG_LOW')))

#Source: local data frame [8 x 5]
#Groups: ID, Type, ToolID [3]

#      ID   Type Measurement PassFail ToolID
#  <fctr> <fctr>      <fctr>   <fctr> <fctr>
#1  ID001      A      Length     PASS    SWP
#2  ID001      A     Summary     PASS    SWP
#3  ID001      A     Breadth     PASS    SWP
#4  ID001      A      Length FAIL_PTS    ISP
#5  ID001      A     Summary     FAIL    ISP
#6  ID002      B      Length     PASS    PSX
#7  ID002      B     Summary FAIL_PTS    PSX
#8  ID002      B     Breadth     FAIL    PSX


来源: stackexchange

问:
C# Sql Command for Insering into a database
I am new to Visual C# programming language and recently i was trying to make a application that is supposed to insert into a local database of users some data but every times my code runs and the insertion works fine the database does not update.This is the code that i am using

```<code>try
{
    cn.Open();
    SqlCommand insert = new SqlCommand();
    insert.CommandText = "insert into Clienti (Nume,Prenume,Parola,Email) values(@Nume,@Prenume,@Parola,@Email)";
    insert.Connection = cn;
    insert.Parameters.AddWithValue("@Nume", register_nume.Text);
    insert.Parameters.AddWithValue("@Prenume", register_prenume.Text);
    insert.Parameters.AddWithValue("@Parola", register_password.Text);
    insert.Parameters.AddWithValue("@Email", register_email.Text);
    insert.ExecuteNonQuery();
    SqlDataReader reader = insert.ExecuteReader();
    while (reader.Read()) { }

    MessageBox.Show("Added succesfully");
}
catch (Exception ex)
{
    MessageBox.Show(""+ex);
}
</code>```

I already tried the property Copy to output and it doesn't seems to work.
I am sorry for any grammar mistakes that i made,I would be grateful for any help.

答:
You ar executing 2 times the query:

```<code>insert.ExecuteNonQuery();
SqlDataReader reader = insert.ExecuteReader();
</code>```

Try to get the affected rows

```<code>int rows = insert.ExecuteNonQuery();
</code>```

I would suggest creating a stored procedure in your database and just execute the SP.

It's always better to execute SP from code and leave the SQL programming in the DB.

ContentLicense: CC BY-SA 3.0

Body:
I am new to Visual C# programming language and recently i was trying to make a application that is supposed to insert into a local database of users some data but every times my code runs and the insertion works fine the database does not update.This is the code that i am using

try
{
    cn.Open();
    SqlCommand insert = new SqlCommand();
    insert.CommandText = "insert into Clienti (Nume,Prenume,Parola,Email) values(@Nume,@Prenume,@Parola,@Email)";
    insert.Connection = cn;
    insert.Parameters.AddWithValue("@Nume", register_nume.Text);
    insert.Parameters.AddWithValue("@Prenume", register_prenume.Text);
    insert.Parameters.AddWithValue("@Parola", register_password.Text);
    insert.Parameters.AddWithValue("@Email", register_email.Text);
    insert.ExecuteNonQuery();
    SqlDataReader reader = insert.ExecuteReader();
    while (reader.Read()) { }

    MessageBox.Show("Added succesfully");
}
catch (Exception ex)
{
    MessageBox.Show(""+ex);
}

I already tried the property Copy to output and it doesn't seems to work.
I am sorry for any grammar mistakes that i made,I would be grateful for any help.

Body:
You ar executing 2 times the query:

insert.ExecuteNonQuery();
SqlDataReader reader = insert.ExecuteReader();

Try to get the affected rows

int rows = insert.ExecuteNonQuery();

I would suggest creating a stored procedure in your database and just execute the SP.

It's always better to execute SP from code and leave the SQL programming in the DB.


问:
Tsql -> filter data 6 months from today, date field in table is YYYYMM
I need some help.
Currently is March 2017.
how do I extract all records 6 months ago from February 2017 until end of this year. the date format in my table is in YYYYMM

Here is my sql statement

```<code>select columns from budget
where month_number > = DATEADD(MONTH, -6, CURRENT_TIMESTAMP);
</code>```

the output I am getting is as below:

```<code>+------------+-------+--------------+
| month_name | month | month_number |
+------------+-------+--------------+
| January    |     1 |       201601 |
| February   |     2 |       201602 |
| March      |     3 |       201603 |
| April      |     4 |       201604 |
| May        |     5 |       201605 |
| June       |     6 |       201606 |
| July       |     7 |       201607 |
| August     |     8 |       201608 |
| September  |     9 |       201609 |
| October    |    10 |       201610 |
| November   |    11 |       201611 |
| December   |    12 |       201612 |
| January    |     1 |       201701 |
| February   |     2 |       201702 |
| March      |     3 |       201703 |
| April      |     4 |       201704 |
| July       |     7 |       201707 |
| December   |    12 |       201712 |
+------------+-------+--------------+
</code>```

I am not getting the right output. I am still getting data from Jan 2016 onwards. Please help

Thanks

答:
Alternatively ..</p>

```<code>declare @budget table (month_Number int)

insert @budget (month_number)
select 201601
union all
select 201602
union all
select 201702
union all
select 201705
union all
select 201709

select * from @budget
where month_number >= (YEAR(DATEADD(MONTH, -6, CURRENT_TIMESTAMP)) * 100) +  MONTH(DATEADD(MONTH, -6, CURRENT_TIMESTAMP));
</code>```

Body:
I need some help.
Currently is March 2017.
how do I extract all records 6 months ago from February 2017 until end of this year. the date format in my table is in YYYYMM

Here is my sql statement

select columns from budget
where month_number > = DATEADD(MONTH, -6, CURRENT_TIMESTAMP);

the output I am getting is as below:

+------------+-------+--------------+
| month_name | month | month_number |
+------------+-------+--------------+
| January    |     1 |       201601 |
| February   |     2 |       201602 |
| March      |     3 |       201603 |
| April      |     4 |       201604 |
| May        |     5 |       201605 |
| June       |     6 |       201606 |
| July       |     7 |       201607 |
| August     |     8 |       201608 |
| September  |     9 |       201609 |
| October    |    10 |       201610 |
| November   |    11 |       201611 |
| December   |    12 |       201612 |
| January    |     1 |       201701 |
| February   |     2 |       201702 |
| March      |     3 |       201703 |
| April      |     4 |       201704 |
| July       |     7 |       201707 |
| December   |    12 |       201712 |
+------------+-------+--------------+

I am not getting the right output. I am still getting data from Jan 2016 onwards. Please help

Thanks

Body:
Alternatively ..

declare @budget table (month_Number int)

insert @budget (month_number)
select 201601
union all
select 201602
union all
select 201702
union all
select 201705
union all
select 201709

select * from @budget
where month_number >= (YEAR(DATEADD(MONTH, -6, CURRENT_TIMESTAMP)) * 100) +  MONTH(DATEADD(MONTH, -6, CURRENT_TIMESTAMP));


问:
ActiveMQ: Transport Connector could not be registered in JMX: java.io.IOException: Transport scheme NOT recognized: [stomp]
We are updating a Java app from Java 7 to 8.  As part of this we are updating ActiveMQ from 5.7 to 5.14.4 and Apache Camel from 2.12.2 to 2.18.3.

The application builds without any errors but fails at start up.  Initially I was getting this exception:

nested exception is java.lang.ClassNotFoundException:
  org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter

So I added activemq-kahadb-store to the pom.xml & now i get this exception:

Transport Connector could not be registered in JMX:
  java.io.IOException: Transport scheme NOT recognized: [stomp]

Below are the activemq & camel config settings that works fine for Java 7 & the previous libraries. What do I need to change to get past this error?

```<code>   <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <value>classpath:xxx.properties</value>
        </property>
    </bean>

    <bean id="broker" class="org.apache.activemq.xbean.BrokerFactoryBean">
        <property name="config" value="classpath:activemq.xml" />
        <property name="start" value="true" />
    </bean>

    <bean id="ProcessManager" class="com.xxx.boot.ProcessManager" />

           <bean id="shutdown" class="org.apache.camel.impl.DefaultShutdownStrategy">
        <property name="timeout" value="30"/>
        </bean>

    <bean id="XXXService" depends-on="broker" class="com.xxx.boot.ProcessExecuter" destroy-method="shutdownProcess">
        <property name="executableArguments">
            <array>
            <value>${JAVA_JDK_LOCATION_32BIT}</value>
            <value>-Xmx512M</value>
            <value>-Djava.library.path={web.directory}\\WEB-INF\\lib</value>
            <value>-Dactivemq.url.stomp=${activemq.url.stomp}</value>
            <value>-Dactivemq.url.openwire=${activemq.url.openwire}</value>
            <value>-cp</value>
            <value>{web.directory}\\WEB-INF\\lib\\*</value>
            </array>
        </property>
        <property name="executableClass">
            <value>boot.RunnerImpl</value>
        </property>
        <property name="executableDirectory">
            <value>WEB-INF/lib</value>
        </property>
        <property name="processManager">
            <ref bean="ProcessManager" />
        </property>
    </bean>

    <camelContext xmlns="http://camel.apache.org/schema/spring" id="ProcessManagerContext" trace="false" useMDCLogging="true">

        <propertyPlaceholder id="properties" location="classpath:xxx.properties"/>

        <route id="boot.XXXService" autoStartup="true">
            <from uri="timer://XXXService?repeatCount=1&delay=5000" />
            <to uri="bean:XXXService?method=terminate" />
            <multicast parallelProcessing="true">
                <to uri="direct:startXXXService" />
                <to uri="direct:startXXXService" />
            </multicast>
        </route>

        <route id="boot.XXXService.start">
            <from uri="direct:startXXXService" />
            <to uri="bean:XXXService?method=start" />
        </route>

        <route id="JMS.ProcessManager">
            <from uri="ir.activemq.broker.client:topic:xxx.ProcessManager?concurrentConsumers=1&exchangePattern=InOnly"/>
            <filter>
                <method ref="ProcessManager" method="destinationFilter" />
                <to uri="bean:ProcessManager?method=doProcess&cache=true" />
            </filter>
        </route>
    </camelContext>
</code>```

答:
This article explains the issue: http://activemq.apache.org/activemq-580-release.html.  I already had the 1st two activemq dependencies.  I needed to add dependencies for activemq-kahadb-store & activemq-stomp</p>

```<code>    <!-- ActiveMQ -->
    <dependency>
        <groupId>org.apache.activemq</groupId>
        <artifactId>activemq-pool</artifactId>
        <version>${org.apache.activemq.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.activemq</groupId>
        <artifactId>activemq-camel</artifactId>
        <version>${org.apache.activemq.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.activemq</groupId>
        <artifactId>activemq-kahadb-store</artifactId>
        <version>${org.apache.activemq.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.activemq</groupId>
        <artifactId>activemq-stomp</artifactId>
        <version>${org.apache.activemq.version}</version>
    </dependency>
</code>```

Body:
We are updating a Java app from Java 7 to 8.  As part of this we are updating ActiveMQ from 5.7 to 5.14.4 and Apache Camel from 2.12.2 to 2.18.3.

The application builds without any errors but fails at start up.  Initially I was getting this exception:

nested exception is java.lang.ClassNotFoundException:
  org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter

So I added activemq-kahadb-store to the pom.xml & now i get this exception:

Transport Connector could not be registered in JMX:
  java.io.IOException: Transport scheme NOT recognized: [stomp]

Below are the activemq & camel config settings that works fine for Java 7 & the previous libraries. What do I need to change to get past this error?

   <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <value>classpath:xxx.properties</value>
        </property>
    </bean>

    <bean id="broker" class="org.apache.activemq.xbean.BrokerFactoryBean">
        <property name="config" value="classpath:activemq.xml" />
        <property name="start" value="true" />
    </bean>

    <bean id="ProcessManager" class="com.xxx.boot.ProcessManager" />

           <bean id="shutdown" class="org.apache.camel.impl.DefaultShutdownStrategy">
        <property name="timeout" value="30"/>
        </bean>

    <bean id="XXXService" depends-on="broker" class="com.xxx.boot.ProcessExecuter" destroy-method="shutdownProcess">
        <property name="executableArguments">
            <array>
            <value>${JAVA_JDK_LOCATION_32BIT}</value>
            <value>-Xmx512M</value>
            <value>-Djava.library.path={web.directory}\\WEB-INF\\lib</value>
            <value>-Dactivemq.url.stomp=${activemq.url.stomp}</value>
            <value>-Dactivemq.url.openwire=${activemq.url.openwire}</value>
            <value>-cp</value>
            <value>{web.directory}\\WEB-INF\\lib\\*</value>
            </array>
        </property>
        <property name="executableClass">
            <value>boot.RunnerImpl</value>
        </property>
        <property name="executableDirectory">
            <value>WEB-INF/lib</value>
        </property>
        <property name="processManager">
            <ref bean="ProcessManager" />
        </property>
    </bean>

    <camelContext xmlns="http://camel.apache.org/schema/spring" id="ProcessManagerContext" trace="false" useMDCLogging="true">

        <propertyPlaceholder id="properties" location="classpath:xxx.properties"/>

        <route id="boot.XXXService" autoStartup="true">
            <from uri="timer://XXXService?repeatCount=1&delay=5000" />
            <to uri="bean:XXXService?method=terminate" />
            <multicast parallelProcessing="true">
                <to uri="direct:startXXXService" />
                <to uri="direct:startXXXService" />
            </multicast>
        </route>

        <route id="boot.XXXService.start">
            <from uri="direct:startXXXService" />
            <to uri="bean:XXXService?method=start" />
        </route>

        <route id="JMS.ProcessManager">
            <from uri="ir.activemq.broker.client:topic:xxx.ProcessManager?concurrentConsumers=1&exchangePattern=InOnly"/>
            <filter>
                <method ref="ProcessManager" method="destinationFilter" />
                <to uri="bean:ProcessManager?method=doProcess&cache=true" />
            </filter>
        </route>
    </camelContext>

Body:
This article explains the issue: http://activemq.apache.org/activemq-580-release.html.  I already had the 1st two activemq dependencies.  I needed to add dependencies for activemq-kahadb-store & activemq-stomp

    <!-- ActiveMQ -->
    <dependency>
        <groupId>org.apache.activemq</groupId>
        <artifactId>activemq-pool</artifactId>
        <version>${org.apache.activemq.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.activemq</groupId>
        <artifactId>activemq-camel</artifactId>
        <version>${org.apache.activemq.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.activemq</groupId>
        <artifactId>activemq-kahadb-store</artifactId>
        <version>${org.apache.activemq.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.activemq</groupId>
        <artifactId>activemq-stomp</artifactId>
        <version>${org.apache.activemq.version}</version>
    </dependency>


问:
.htaccess file causing too many redirects error
I have the following redirect rules in my .htaccess file:

```<code>RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule !^(.*)$ /index.php/$1 [L]
</code>```

This is causing a too many redirects error on my site. Moreover, this problem is occurring only on my local machine and the site is working just fine on the remote server.

Please help!

答:
Just follow following steps:

Go to application/config/config.php and Change $config['index_page'] = 'index.php'; to $config['index_page'] = ''; // remove index.php

Add base url in same file application/config/config.php as: $config['base_url'] = 'http://localhost/yourapp';

Check your apache server has Rewrite module enabled.

add .htaccess file in your root directory

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

Body:
I have the following redirect rules in my .htaccess file:

RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule !^(.*)$ /index.php/$1 [L]

This is causing a too many redirects error on my site. Moreover, this problem is occurring only on my local machine and the site is working just fine on the remote server.

Please help!


问:
dc.js: How can I calculate averages from reduced sub-bins?
I have information from a cluster of virtual machines that I am trying to plot by day on a dc.js composite line chart.

Here is the JSON format:

```<code>[{
Date: "Feb 15 14:25:53 2017",
Institution: "institution x",
Memory: 57777556,
Nodes: 1,
Processors: 4,
Queue: "workq",
TotalCpus: 81600,
TotalMemory: 64172851200,
TotalNodes: 300
},
{
Date: "Feb 15 14:26:09 2017",
Institution: "institution y",
Memory: 57542224,
Nodes: 1,
Processors: 4,
Queue: "workq",
TotalCpus: 81600,
TotalMemory: 64172851200,
TotalNodes: 300
}]
</code>```

I am able to plot total memory consumed over time per institution by reducing with reduceSum().  Here is my fiddle:  https://jsfiddle.net/catkinso/cxr1L6fq/

However, I have not been able to figure out how to calculate average memory consumed per day per institution.

I know that I need to implement a custom reduction, one that uses sub-bins like this:

```<code>var usedMemoryGroup = dateDimension.group().reduce(
function (p, v)
{
    // add
    if (v.Queue === queue)
    {
        p[v.Institution] = (p[v.Institution] || 0) + (v.Memory / v.TotalMemory);
    }
    return p;
},
function (p, v)
{
    // remove
    if (v.Queue === queue)
    {
        p[v.Institution] -= (v.Memory / v.TotalMemory);
    }
    return p;
},
function ()
{
// init
    return {};
});
</code>```

But I am unsure how to create a custom reduction that creates sub-bins while also calculating an average per day.  Ultimately I hope to plot that reduction across a composite time chart with lines for each institution.

Any help would be greatly appreciated!

答:
For anyone interested, here is what I did...

Create a dimension for institution names:

```<code>institutionDimension = ndx.dimension(function (d) {
                                    if (d.Queue === queue) {
                                        return d.Institution;
                                    }
                                })
</code>```

Then create an array of all institution names:

```<code> var institutions = [];
 var names = institutionDimension.group().all();

 names.forEach(function (x) {
      if (institutions.indexOf(x.key) === -1) {
           institutions.push(x.key);
       }
 });

 institutions.sort();
</code>```

Then for each institution create a group:

```<code>var institutionGroups = [];
institutions.forEach(function (institution)
{
     institutionGroups.push(createAverageMemoryGroup(dateDimension,queue,institution));
});

function createAverageMemoryGroup(dimension, queue, institution)
{
    var group = dimension.group()
        .reduce(
            function (p, v) {
                if (v.Queue === queue && v.Institution === institution) {
                    ++p.count;
                    p.queue = queue;
                    p.aggregateMemory += v.Memory/1000000;
                    p.averageMemoryUsed = p.count ? d3.round((p.aggregateMemory / p.count), 2) : 0;
                }
                return p;
            },
            function (p, v) {
                if (v.Queue === queue && v.Institution === institution) {
                    --p.count;
                    p.aggregateMemory -= v.Memory/1000000;
                    p.averageMemoryUsed = p.count ? d3.round((p.aggregateMemory / p.count), 2) : 0;
                }
                return p;
            },
            function () {
                return {
                    count: 0,
                    aggregateMemory: 0,
                    averageMemoryUsed: 0,
                    queue
                };
            });

    return group;
}
</code>```

Then for each group, create a composition:

```<code>var composition = createComposition(usedMemoryTimeChart, dateDimension, institutionGroups, institutions);
function createComposition(chart, dimension, groups, institutions)
    {
        var composition = [];
        for (var i = 0; i < institutions.length; i++) {
            composition.push(
                dc.lineChart(chart)
                .dimension(dimension)
                .colors(getColor(i))
                .group(groups[i], institutions[i])
                .dashStyle([2, 2])
                .valueAccessor(function (x) {
                    return x.value.averageMemoryUsed;
                })
                );
        }

        return composition;
    }
</code>```

And lastly, apply the composition to the chart:

```<code>usedMemoryTimeChart.compose(composition);
</code>```

Body:
I have information from a cluster of virtual machines that I am trying to plot by day on a dc.js composite line chart.

Here is the JSON format:

[{
Date: "Feb 15 14:25:53 2017",
Institution: "institution x",
Memory: 57777556,
Nodes: 1,
Processors: 4,
Queue: "workq",
TotalCpus: 81600,
TotalMemory: 64172851200,
TotalNodes: 300
},
{
Date: "Feb 15 14:26:09 2017",
Institution: "institution y",
Memory: 57542224,
Nodes: 1,
Processors: 4,
Queue: "workq",
TotalCpus: 81600,
TotalMemory: 64172851200,
TotalNodes: 300
}]

I am able to plot total memory consumed over time per institution by reducing with reduceSum().  Here is my fiddle:  https://jsfiddle.net/catkinso/cxr1L6fq/

However, I have not been able to figure out how to calculate average memory consumed per day per institution.

I know that I need to implement a custom reduction, one that uses sub-bins like this:

var usedMemoryGroup = dateDimension.group().reduce(
function (p, v)
{
    // add
    if (v.Queue === queue)
    {
        p[v.Institution] = (p[v.Institution] || 0) + (v.Memory / v.TotalMemory);
    }
    return p;
},
function (p, v)
{
    // remove
    if (v.Queue === queue)
    {
        p[v.Institution] -= (v.Memory / v.TotalMemory);
    }
    return p;
},
function ()
{
// init
    return {};
});

But I am unsure how to create a custom reduction that creates sub-bins while also calculating an average per day.  Ultimately I hope to plot that reduction across a composite time chart with lines for each institution.

Any help would be greatly appreciated!

Body:
For anyone interested, here is what I did...

Create a dimension for institution names:

institutionDimension = ndx.dimension(function (d) {
                                    if (d.Queue === queue) {
                                        return d.Institution;
                                    }
                                })

Then create an array of all institution names:

 var institutions = [];
 var names = institutionDimension.group().all();

 names.forEach(function (x) {
      if (institutions.indexOf(x.key) === -1) {
           institutions.push(x.key);
       }
 });

 institutions.sort();

Then for each institution create a group:

var institutionGroups = [];
institutions.forEach(function (institution)
{
     institutionGroups.push(createAverageMemoryGroup(dateDimension,queue,institution));
});

function createAverageMemoryGroup(dimension, queue, institution)
{
    var group = dimension.group()
        .reduce(
            function (p, v) {
                if (v.Queue === queue && v.Institution === institution) {
                    ++p.count;
                    p.queue = queue;
                    p.aggregateMemory += v.Memory/1000000;
                    p.averageMemoryUsed = p.count ? d3.round((p.aggregateMemory / p.count), 2) : 0;
                }
                return p;
            },
            function (p, v) {
                if (v.Queue === queue && v.Institution === institution) {
                    --p.count;
                    p.aggregateMemory -= v.Memory/1000000;
                    p.averageMemoryUsed = p.count ? d3.round((p.aggregateMemory / p.count), 2) : 0;
                }
                return p;
            },
            function () {
                return {
                    count: 0,
                    aggregateMemory: 0,
                    averageMemoryUsed: 0,
                    queue
                };
            });

    return group;
}

Then for each group, create a composition:

var composition = createComposition(usedMemoryTimeChart, dateDimension, institutionGroups, institutions);
function createComposition(chart, dimension, groups, institutions)
    {
        var composition = [];
        for (var i = 0; i < institutions.length; i++) {
            composition.push(
                dc.lineChart(chart)
                .dimension(dimension)
                .colors(getColor(i))
                .group(groups[i], institutions[i])
                .dashStyle([2, 2])
                .valueAccessor(function (x) {
                    return x.value.averageMemoryUsed;
                })
                );
        }

        return composition;
    }

And lastly, apply the composition to the chart:

usedMemoryTimeChart.compose(composition);


问:
assembly take in input number without echo(emu8086)
I'm using emu8086 to code

So

```<code>str01 db "Enter a number $"

Number db ?

Lea dx,str01
Mov ah,9
Int 21h

Mov ah,1
Int 21h
</code>```

So how can i take that number without showing it ?

答:
I haven't tested it, but according to Ralph Brown's interrupt list of INT 21h your code

```<code>mov ah, 01h
int 21h
</code>```

calls the

INT 21h/AH=01h function

READ CHARACTER FROM STANDARD INPUT, WITH ECHO.

So, to avoid console output, you probably should call the

INT21h/AH=07h function

DIRECT CHARACTER INPUT, WITHOUT ECHO.

So your code should probably look like this:

```<code>mov ah, 07
int 21h
</code>```

Body:
I'm using emu8086 to code

So

str01 db "Enter a number $"

Number db ?

Lea dx,str01
Mov ah,9
Int 21h

Mov ah,1
Int 21h

So how can i take that number without showing it ?

Body:
I haven't tested it, but according to Ralph Brown's interrupt list of INT 21h your code

mov ah, 01h
int 21h

calls the

INT 21h/AH=01h function

READ CHARACTER FROM STANDARD INPUT, WITH ECHO.

So, to avoid console output, you probably should call the

INT21h/AH=07h function

DIRECT CHARACTER INPUT, WITHOUT ECHO.

So your code should probably look like this:

mov ah, 07
int 21h


问:
Plot surface from irregular data
I'm make a filled contour or surface plot from a scattered dataset.

A major difference from other Qs is that the data are not convex.

```<code>[r,th] = meshgrid(10:15,0:180);
[x,y] = deal(r.*sind(th), r.*cosd(th));
z = x.^2+y.^2;
scatter(x(:),y(:),[],z(:),'fill'); axis equal off;
</code>```

The inner circle is null.

I use

```<code>tri = delaunay(x,y);
trisurf(tri,x,y,z);  view(2); axis equal off;
</code>```

to make a surface plot.

However, as you can see, the inner circle is filled.

答:
Rather than using the Delaunay triangulation which results in the convex hull, you're going to want to use an alphaShape with which you can impose a limit on the length of the resulting surfaces edges.

You can specify the Alpha property (by specifying a third input) which is the inverse of the maximum edge length. For your example, I've chosen an Alpha of  1.

```<code>A = alphaShape(x(:), y(:), 1);
</code>```

You can then get the triangulation out using the alphaTriangulation method of your alphaSurface object.

```<code>[faces, vertices] = A.alphaTriangulation();
zvalue = sum(vertices.^2, 2);
</code>```

Or you can use the plot method of the alphaShape object

```<code>plot(A, 'FaceColor', 'interp', 'CData', zvalue)
</code>```

Title: Plot surface from irregular data

Body:
I'm make a filled contour or surface plot from a scattered dataset.

A major difference from other Qs is that the data are not convex.

[r,th] = meshgrid(10:15,0:180);
[x,y] = deal(r.*sind(th), r.*cosd(th));
z = x.^2+y.^2;
scatter(x(:),y(:),[],z(:),'fill'); axis equal off;

The inner circle is null.

I use

tri = delaunay(x,y);
trisurf(tri,x,y,z);  view(2); axis equal off;

to make a surface plot.

However, as you can see, the inner circle is filled.

Body:
Rather than using the Delaunay triangulation which results in the convex hull, you're going to want to use an alphaShape with which you can impose a limit on the length of the resulting surfaces edges.

You can specify the Alpha property (by specifying a third input) which is the inverse of the maximum edge length. For your example, I've chosen an Alpha of  1.

A = alphaShape(x(:), y(:), 1);

You can then get the triangulation out using the alphaTriangulation method of your alphaSurface object.

[faces, vertices] = A.alphaTriangulation();
zvalue = sum(vertices.^2, 2);

Or you can use the plot method of the alphaShape object

plot(A, 'FaceColor', 'interp', 'CData', zvalue)


问:
How do I use OpenCover and ReportGenerator to view Unit Test Coverage Results?
I'm a noob to using both OpenCover and ReportGenerator and I'm struggling a bit in understanding how to get them working. I'm using VS.NET 2012 'Professional' which means I don't have access to the built in unit test coverage tooling. I also have ReSharper installed, but don't want to pay for another utility in 'dotCover'

It looks like OpenCover and ReportGenerator will do what I need and I see the documentation that was downloaded alongside, but am missing some understanding. 1st off, when I download the nuget packges for both, what should my target project be? I have a multi layer app, so I'm assuming my unit test project correct, or does it even matter? I see in the documentation, I'm just pointing at the /bin (I think) of a solution using command line commands, so maybe I didn't even need to add these downloads to any particular project (could have been a test harness). Can someone tell me if I have this correct?

Once I have them installed, I'm trying to get unit test coverage metrics, and the docs that came with the package are not as clear as I hoped. Are there any good blog posts or links that walk through using these tool together to get the metrics?

答:
Thanks @atconway for your tutorial.
I've updated your .bat script a little, to ease future upgrades, and project changes.

Summarizing, to use OpenCover with NUnit you have to add to your project these nugets:

OpenCover

NUnit.ConsoleRunner

ReportGenerator by Daniel Palme

and here is updated .bat file.
To run it just edit "settings" and save script as .bat file in root of your project.

```<code>@echo off
REM ** Be sure to install these nugets:
REM ** NUnit.ConsoleRunner
REM ** OpenCover
REM ** ReportGenerator
REM **
REM ** All paths should be entered without quotes

REM ** SET TestResultsFileProjectName=CalculatorResults
SET TestResultsFileProjectName=<ANY_NAME>

REM ** SET DLLToTestRelativePath=Calculator\bin\Debug\MyCalc.dll
SET DLLToTestRelativePath=<VALID_PATH>

REM ** Filters Wiki https://github.com/opencover/opencover/wiki/Usage
REM ** SET Filters=+[Calculator]* -[Calculator]CalculatorTests.*
SET Filters=<VALID_FILTERS>

SET OpenCoverFolderName=OpenCover.4.6.519
SET NUnitConsoleRunnerFolderName=NUnit.ConsoleRunner.3.6.1
SET ReportGeneratorFolderName=ReportGenerator.2.5.6

REM *****************************************************************

REM Create a 'GeneratedReports' folder if it does not exist
if not exist "%~dp0GeneratedReports" mkdir "%~dp0GeneratedReports"

REM Remove any previous test execution files to prevent issues overwriting
IF EXIST "%~dp0%TestResultsFileProjectName%.trx" del "%~dp0%TestResultsFileProjectName%.trx%"

REM Remove any previously created test output directories
CD %~dp0
FOR /D /R %%X IN (%USERNAME%*) DO RD /S /Q "%%X"

REM Run the tests against the targeted output
call :RunOpenCoverUnitTestMetrics

REM Generate the report output based on the test results
if %errorlevel% equ 0 (
 call :RunReportGeneratorOutput
)

REM Launch the report
if %errorlevel% equ 0 (
 call :RunLaunchReport
)
exit /b %errorlevel%

:RunOpenCoverUnitTestMetrics
"%~dp0packages\%OpenCoverFolderName%\tools\OpenCover.Console.exe" ^
-register:user ^
-target:"%~dp0packages\%NUnitConsoleRunnerFolderName%\tools\nunit3-console.exe" ^
-targetargs:"--noheader \"%~dp0%DLLToTestRelativePath%\"" ^
-filter:"%Filters%" ^
-mergebyhash ^
-skipautoprops ^
-excludebyattribute:"System.CodeDom.Compiler.GeneratedCodeAttribute" ^
-output:"%~dp0GeneratedReports\%TestResultsFileProjectName%.xml"
exit /b %errorlevel%

:RunReportGeneratorOutput
"%~dp0packages\%ReportGeneratorFolderName%\tools\ReportGenerator.exe" ^
-reports:"%~dp0GeneratedReports\%TestResultsFileProjectName%.xml" ^
-targetdir:"%~dp0GeneratedReports\ReportGenerator Output"
exit /b %errorlevel%

:RunLaunchReport
start "report" "%~dp0GeneratedReports\ReportGenerator Output\index.htm"
exit /b %errorlevel%
</code>```

Body:
Thanks @atconway for your tutorial.
I've updated your .bat script a little, to ease future upgrades, and project changes.

Summarizing, to use OpenCover with NUnit you have to add to your project these nugets:

OpenCover

NUnit.ConsoleRunner

ReportGenerator by Daniel Palme

and here is updated .bat file.
To run it just edit "settings" and save script as .bat file in root of your project.

@echo off
REM ** Be sure to install these nugets:
REM ** NUnit.ConsoleRunner
REM ** OpenCover
REM ** ReportGenerator
REM **
REM ** All paths should be entered without quotes

REM ** SET TestResultsFileProjectName=CalculatorResults
SET TestResultsFileProjectName=<ANY_NAME>

REM ** SET DLLToTestRelativePath=Calculator\bin\Debug\MyCalc.dll
SET DLLToTestRelativePath=<VALID_PATH>

REM ** Filters Wiki https://github.com/opencover/opencover/wiki/Usage
REM ** SET Filters=+[Calculator]* -[Calculator]CalculatorTests.*
SET Filters=<VALID_FILTERS>

SET OpenCoverFolderName=OpenCover.4.6.519
SET NUnitConsoleRunnerFolderName=NUnit.ConsoleRunner.3.6.1
SET ReportGeneratorFolderName=ReportGenerator.2.5.6

REM *****************************************************************

REM Create a 'GeneratedReports' folder if it does not exist
if not exist "%~dp0GeneratedReports" mkdir "%~dp0GeneratedReports"

REM Remove any previous test execution files to prevent issues overwriting
IF EXIST "%~dp0%TestResultsFileProjectName%.trx" del "%~dp0%TestResultsFileProjectName%.trx%"

REM Remove any previously created test output directories
CD %~dp0
FOR /D /R %%X IN (%USERNAME%*) DO RD /S /Q "%%X"

REM Run the tests against the targeted output
call :RunOpenCoverUnitTestMetrics

REM Generate the report output based on the test results
if %errorlevel% equ 0 (
 call :RunReportGeneratorOutput
)

REM Launch the report
if %errorlevel% equ 0 (
 call :RunLaunchReport
)
exit /b %errorlevel%

:RunOpenCoverUnitTestMetrics
"%~dp0packages\%OpenCoverFolderName%\tools\OpenCover.Console.exe" ^
-register:user ^
-target:"%~dp0packages\%NUnitConsoleRunnerFolderName%\tools\nunit3-console.exe" ^
-targetargs:"--noheader \"%~dp0%DLLToTestRelativePath%\"" ^
-filter:"%Filters%" ^
-mergebyhash ^
-skipautoprops ^
-excludebyattribute:"System.CodeDom.Compiler.GeneratedCodeAttribute" ^
-output:"%~dp0GeneratedReports\%TestResultsFileProjectName%.xml"
exit /b %errorlevel%

:RunReportGeneratorOutput
"%~dp0packages\%ReportGeneratorFolderName%\tools\ReportGenerator.exe" ^
-reports:"%~dp0GeneratedReports\%TestResultsFileProjectName%.xml" ^
-targetdir:"%~dp0GeneratedReports\ReportGenerator Output"
exit /b %errorlevel%

:RunLaunchReport
start "report" "%~dp0GeneratedReports\ReportGenerator Output\index.htm"
exit /b %errorlevel%


问:
ASP.NET Core 1.1 and EF 6 exception in unmanaged code
For some reason, I'm getting a fatal error somewhere in EF 6, but this has only happened since I've converted to .NET Core 1.1. This application ran without issue on ASP.NET MVC 4.

For the search engines:

Managed Debugging Assistant 'FatalExecutionEngineError' : 'The runtime has encountered a fatal error. The address of the error was at 0x77c81a09, on thread 0x2520. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.'

From what I can find online, this is a problem outside the managed environment of .NET... Which means that I'm just shy of clueless.

The first time I was hit with this error, a simple Clean and Build fixed it for a little while, and then it cropped up again in the same place.

I've seen this error in two places so far:

```<code>var vm = new ManagerLogIndexViewModel()
{
    Locations = await _db.Locations.ToListAsync(),
};
</code>```

And the (albeit more complicated):

```<code>var results = await _db.InvolvedPersons
    .Where(
        x =>
            x.LastName.ToUpper().Contains(q) || x.FirstName.ToUpper().Contains(q) ||
            (x.FirstName + " " + x.LastName).ToUpper().Contains(q))
    .Select(x => new {x.FirstName, x.LastName, x.Id})
    .GroupBy(x => x.LastName + " " + x.LastName)
    .Select(x => x.FirstOrDefault())
    .ToDictionaryAsync(x => x.FirstName + " " + x.LastName, x => x.Id.ToString());
</code>```

Could it have something to do with async?

There are other Entity Framework calls where everything works fine, even with the async operator.

Even the first example worked after a Clean and Build.

I'm really at a loss for what to do. I've read that it might have something to do with the environment. At the moment, I have no alternative environments to test on, just my development machine. I'll attempt to update later if I get this spun up on an alternate machine.

I just did another test before posting:

If I step through the code (first example), everything works as intended.

Stop. Remove breakpoint. Start. Crash.

This is driving me up a wall.

As if this couldn't get much stranger, this error doesn't happen every time I launch.

I'd say it’s about 60/40 in favor of crashing. When it runs (and the first query goes through) I have no issues for the lifetime of the process.

It looks like this is isolated to running under IIS Express. If I run the application in a stand-alone fashion, I have not been able to produce a crash.

Some more technical bits:

ASP.Net Core 1.1

.NET 4.5.2

Windows 7 SP1

EF 6.1.3

For the sake of completeness (since there are a few threads at this point), the workaround provided by @gregg-miskelly (and submitted to Stack Overflow by @SwampyFox) does indeed work. The bug has been submitted to Microsoft and should be fixed in a future .NET Framework release.

The discussion took place on the coreclr GitHub page.

答:
I'm experiencing the same issue with .NET 4.62 and ASP.NET 1.1 with an EF 6.1.3 project:

<PropertyGroup>
  <TargetFramework>net462</TargetFramework>
</PropertyGroup>

<ItemGroup>
  <Folder Include="wwwroot\" />
</ItemGroup>

<ItemGroup>
  <PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
  <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
  <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" />
  <PackageReference Include="EntityFramework" Version="6.1.3" />
</ItemGroup>
```
<p>I receive the following exception much (but not all) of the time when I run in IIS Express:</p>
<blockquote>
<p>Managed Debugging Assistant 'FatalExecutionEngineError' : 'The runtime
has encountered a fatal error. The address of the error was at
0x709a1a09, on thread 0x5020. The error code is 0xc0000005. This error
may be a bug in the CLR or in the unsafe or non-verifiable portions of
user code. Common sources of this bug include user marshaling errors
for COM-interop or PInvoke, which may corrupt the stack.'</p>
</blockquote>
<p>It happens if I call async or synchronous or even if I call my DbContext from Main:</p>
```    public static void Main(string[] args)
    {
        using (var db = new MyDbContext())
        {
            var WorkOrders = db.WorkOrders.ToList();
        }

            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

        host.Run();
    }
```

This never happens if I run my app directly (outside of IIS Express).

So apparently this is still an issue.

ContentLicense: CC BY-SA 4.0

Body:
For some reason, I'm getting a fatal error somewhere in EF 6, but this has only happened since I've converted to .NET Core 1.1. This application ran without issue on ASP.NET MVC 4.

For the search engines:

Managed Debugging Assistant 'FatalExecutionEngineError' : 'The runtime has encountered a fatal error. The address of the error was at 0x77c81a09, on thread 0x2520. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.'

From what I can find online, this is a problem outside the managed environment of .NET... Which means that I'm just shy of clueless.

The first time I was hit with this error, a simple Clean and Build fixed it for a little while, and then it cropped up again in the same place.

I've seen this error in two places so far:

var vm = new ManagerLogIndexViewModel()
{
    Locations = await _db.Locations.ToListAsync(),
};

And the (albeit more complicated):

var results = await _db.InvolvedPersons
    .Where(
        x =>
            x.LastName.ToUpper().Contains(q) || x.FirstName.ToUpper().Contains(q) ||
            (x.FirstName + " " + x.LastName).ToUpper().Contains(q))
    .Select(x => new {x.FirstName, x.LastName, x.Id})
    .GroupBy(x => x.LastName + " " + x.LastName)
    .Select(x => x.FirstOrDefault())
    .ToDictionaryAsync(x => x.FirstName + " " + x.LastName, x => x.Id.ToString());

Could it have something to do with async?

There are other Entity Framework calls where everything works fine, even with the async operator.

Even the first example worked after a Clean and Build.

I'm really at a loss for what to do. I've read that it might have something to do with the environment. At the moment, I have no alternative environments to test on, just my development machine. I'll attempt to update later if I get this spun up on an alternate machine.

I just did another test before posting:

If I step through the code (first example), everything works as intended.

Stop. Remove breakpoint. Start. Crash.

This is driving me up a wall.

As if this couldn't get much stranger, this error doesn't happen every time I launch.

I'd say it’s about 60/40 in favor of crashing. When it runs (and the first query goes through) I have no issues for the lifetime of the process.

It looks like this is isolated to running under IIS Express. If I run the application in a stand-alone fashion, I have not been able to produce a crash.

Some more technical bits:

ASP.Net Core 1.1

.NET 4.5.2

Windows 7 SP1

EF 6.1.3

For the sake of completeness (since there are a few threads at this point), the workaround provided by @gregg-miskelly (and submitted to Stack Overflow by @SwampyFox) does indeed work. The bug has been submitted to Microsoft and should be fixed in a future .NET Framework release.

The discussion took place on the coreclr GitHub page.

Body:
I'm experiencing the same issue with .NET 4.62 and ASP.NET 1.1 with an EF 6.1.3 project:

<PropertyGroup>
  <TargetFramework>net462</TargetFramework>
</PropertyGroup>

<ItemGroup>
  <Folder Include="wwwroot\" />
</ItemGroup>

<ItemGroup>
  <PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
  <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
  <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" />
  <PackageReference Include="EntityFramework" Version="6.1.3" />
</ItemGroup>

I receive the following exception much (but not all) of the time when I run in IIS Express:

Managed Debugging Assistant 'FatalExecutionEngineError' : 'The runtime
has encountered a fatal error. The address of the error was at
0x709a1a09, on thread 0x5020. The error code is 0xc0000005. This error
may be a bug in the CLR or in the unsafe or non-verifiable portions of
user code. Common sources of this bug include user marshaling errors
for COM-interop or PInvoke, which may corrupt the stack.'

It happens if I call async or synchronous or even if I call my DbContext from Main:

    public static void Main(string[] args)
    {
        using (var db = new MyDbContext())
        {
            var WorkOrders = db.WorkOrders.ToList();
        }

            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

        host.Run();
    }

This never happens if I run my app directly (outside of IIS Express).

So apparently this is still an issue.


问:
How to extract text between matching strings including match strings and lines
I am working on python to extract certain string between match strings. These strings are generated from a list which is again generated dynamically by a separate python function. The list I am working on looks like this:-

```<code>sample_list = ['line1 this line a first line',
        'line1 this line is also considered as line one...',
        'line1 this line is the first line',
        'line2 this line is second line to be included in output',
        'line3 this should also be included in output',
        'line1 this contain other strings',
        'line1 this may contain other strings as well',
        'line2 this line is second line to be included in output',
        'line3 this should also be included in output',
        'line1 what the heck is it...'
        ]
</code>```

The output I want is similar to this:-

```<code>line1 this line is the first line
line2 this line is second line to be included in output
line3 this should also be included in output
line1 this may contain other strings as well
line2 this line is second line to be included in output
line3 this should also be included in output
</code>```

As you can see, I want to extract the text/lines which are starting as line1 and ending with line3 (up to line ending). The final output includes both the matching words (ie. line1 and line3).

The code I have tried is:-

```<code># Convert list to string first
list_to_str = '\n'.join(sample_list)
# Get desired output
print(re.findall('\nline1(.*?)\nline2(.*?)\nline3($)', list_to_str, re.DOTALL))
</code>```

This is what I am getting as an output ():-

```<code>[]
</code>```

Any help is appreciated.

Edit1:-
I have done some work and found this nearest solution:-

```<code>matches = (re.findall(r"^line1(.*)\nline2(.*)\nline3(.*)$", list_to_str, re.MULTILINE))

for match in matches:
    print('\n'.join(match))
</code>```

It gives me this output:-

```<code> this line is the first line
 this line is second line to be included in output
 this is the third and it should also be included in output
 this may contain other strings as well
 this line is second line to be included in output...
 this is the third should also be included in output
</code>```

The output is almost correct but it does not include the match text.

答:
If you're looking for a sequence of line 1,2, and 3 with no duplicates

it is this

line1.*\s*(?!\s|line[13])line2.*\s*(?!\s|line[12])line3.*

Explained

```<code> line1 .* \s*             # line 1 plus newline(s)
 (?! \s | line [13] )     # Next cannot be line 1 or 3 (or whitespace)
 line2 .* \s*             # line 2 plus newline(s)
 (?! \s | line [12] )     # Next cannot be line 1 or 2 (or whitespace)
 line3 .*                 # line 3
</code>```

If you want to capture the line content, just put capture groups around (.*)

Body:
I am working on python to extract certain string between match strings. These strings are generated from a list which is again generated dynamically by a separate python function. The list I am working on looks like this:-

sample_list = ['line1 this line a first line',
        'line1 this line is also considered as line one...',
        'line1 this line is the first line',
        'line2 this line is second line to be included in output',
        'line3 this should also be included in output',
        'line1 this contain other strings',
        'line1 this may contain other strings as well',
        'line2 this line is second line to be included in output',
        'line3 this should also be included in output',
        'line1 what the heck is it...'
        ]

The output I want is similar to this:-

line1 this line is the first line
line2 this line is second line to be included in output
line3 this should also be included in output
line1 this may contain other strings as well
line2 this line is second line to be included in output
line3 this should also be included in output

As you can see, I want to extract the text/lines which are starting as line1 and ending with line3 (up to line ending). The final output includes both the matching words (ie. line1 and line3).

The code I have tried is:-

# Convert list to string first
list_to_str = '\n'.join(sample_list)
# Get desired output
print(re.findall('\nline1(.*?)\nline2(.*?)\nline3($)', list_to_str, re.DOTALL))

This is what I am getting as an output ():-

[]

Any help is appreciated.

Edit1:-
I have done some work and found this nearest solution:-

matches = (re.findall(r"^line1(.*)\nline2(.*)\nline3(.*)$", list_to_str, re.MULTILINE))

for match in matches:
    print('\n'.join(match))

It gives me this output:-

 this line is the first line
 this line is second line to be included in output
 this is the third and it should also be included in output
 this may contain other strings as well
 this line is second line to be included in output...
 this is the third should also be included in output

The output is almost correct but it does not include the match text.

Body:
If you're looking for a sequence of line 1,2, and 3 with no duplicates

it is this

line1.*\s*(?!\s|line[13])line2.*\s*(?!\s|line[12])line3.*

Explained

 line1 .* \s*             # line 1 plus newline(s)
 (?! \s | line [13] )     # Next cannot be line 1 or 3 (or whitespace)
 line2 .* \s*             # line 2 plus newline(s)
 (?! \s | line [12] )     # Next cannot be line 1 or 2 (or whitespace)
 line3 .*                 # line 3

If you want to capture the line content, just put capture groups around (.*)


问:
What common patterns/solutions have been established in Scala for frequently-encountered problems
I'll start the ball rolling.

Given a sequence of elements, some of which can be contained multiple times, one typical requirement is to count them - in the form of a tally or histogram.

The oft-quoted solution is:

```<code>ss.groupBy(identity).mapValues(_.size)
</code>```

So what other solutions exist for similar commonly encountered problems in Scala?

答:
Sometimes you have to use while instead of for, and often you are collecting results:

```<code>val buf = new Listbuffer[Int]
while(cond()) {
  val x = fancyStuff()
  buf += calculation(x)
}
</code>```

I think it would be very helpful to have for while the same possibility to "yield" something as for for, removing some burr on the edge between imperative and functional style:

```<code>val buf = while(cond()) {
  val x = fancyStuff()
} yield calculation(x)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'll start the ball rolling.

Given a sequence of elements, some of which can be contained multiple times, one typical requirement is to count them - in the form of a tally or histogram.

The oft-quoted solution is:

ss.groupBy(identity).mapValues(_.size)

So what other solutions exist for similar commonly encountered problems in Scala?

Body:
Sometimes you have to use while instead of for, and often you are collecting results:

val buf = new Listbuffer[Int]
while(cond()) {
  val x = fancyStuff()
  buf += calculation(x)
}

I think it would be very helpful to have for while the same possibility to "yield" something as for for, removing some burr on the edge between imperative and functional style:

val buf = while(cond()) {
  val x = fancyStuff()
} yield calculation(x)


问:
Skipped 524 frames! The application may be doing too much work on its main thread
I'm coding for Android app with this function:

```<code>protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.conversation_list_activity);
        listViewConversationList = FindViewById<ListView>(Resource.Id.listViewConversationPreview);

        string url = ConstantManager.HOST;
        HttpClient oHttpClient = new HttpClient();

        var oTaskGetAsync = oHttpClient.GetAsync(new Uri(url));
        oTaskGetAsync.ContinueWith((oHttpResponseMessage) =>
        {
            var result = oHttpResponseMessage.Result.Content.ReadAsStringAsync().Result;
            listConversationPreview = Newtonsoft.Json.JsonConvert.DeserializeObject<List<ConversationPreview>>(result);
            ConversationAdapter adapter = new ConversationAdapter(this, listConversationPreview);
            RunOnUiThread(() => listViewConversationList.Adapter = adapter);
            listViewConversationList.ItemClick += listViewConversationList_ItemClick;
        });

    }
</code>```

I run it successfully but after I import some Nuget Packae for Android Support Design, now it throw a message like this.

I/Choreographer( 1962): Skipped 524 frames!  The application may be
  doing too much work on its main thread.

Could you please tell me what I've done wrong?

答:
You can perform an async operation in an Android Activity by using Handler and Action, so they will not use the UI Thread.

Example:

```<code>protected override void OnResume()
{
    base.OnResume();
    Handler handler = new Handler();
    Action action = async delegate { await UpdateListView(); };
    handler.Post(action);
}

private async Task UpdateListView()
{
    //Get data from internet with async methods here and update the ListView
}
</code>```

Body:
I'm coding for Android app with this function:

protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.conversation_list_activity);
        listViewConversationList = FindViewById<ListView>(Resource.Id.listViewConversationPreview);

        string url = ConstantManager.HOST;
        HttpClient oHttpClient = new HttpClient();

        var oTaskGetAsync = oHttpClient.GetAsync(new Uri(url));
        oTaskGetAsync.ContinueWith((oHttpResponseMessage) =>
        {
            var result = oHttpResponseMessage.Result.Content.ReadAsStringAsync().Result;
            listConversationPreview = Newtonsoft.Json.JsonConvert.DeserializeObject<List<ConversationPreview>>(result);
            ConversationAdapter adapter = new ConversationAdapter(this, listConversationPreview);
            RunOnUiThread(() => listViewConversationList.Adapter = adapter);
            listViewConversationList.ItemClick += listViewConversationList_ItemClick;
        });

    }

I run it successfully but after I import some Nuget Packae for Android Support Design, now it throw a message like this.

I/Choreographer( 1962): Skipped 524 frames!  The application may be
  doing too much work on its main thread.

Could you please tell me what I've done wrong?

Body:
You can perform an async operation in an Android Activity by using Handler and Action, so they will not use the UI Thread.

Example:

protected override void OnResume()
{
    base.OnResume();
    Handler handler = new Handler();
    Action action = async delegate { await UpdateListView(); };
    handler.Post(action);
}

private async Task UpdateListView()
{
    //Get data from internet with async methods here and update the ListView
}


问:
What's the Bug in this code ?
I have initialized the root to NULL at the starting and the same will go to the first insert function. As i have sent the address of root, it should be changed, but its not, again in the second insert statement NULL vakue for root is going inside the insert function.

Please let me know, where I have missed it.

```<code>#include <stdio.h>
#include <stdlib.h>
typedef struct bst{
    struct bst *left;
    int data;
    struct bst *right;
}bst_t;

void insert(struct bst**, int);
void print(struct bst*);

int main() {
    struct bst *root;
    root = NULL;

    insert(&root, 45);
    insert(&root, 75);
    insert(&root, 5);
    insert(&root, 76);
    insert(&root, 25);
    insert(&root, 56);
    insert(&root, 89);
    insert(&root, 99);
    insert(&root, 98);

    print(root);

    printf("Print Any Char...\n");
    getch();
    return 0;
}

void insert(struct bst **root, int num)
{
    struct bst *node = *root;

    if(node == NULL)
    {
        node = (struct bst*)malloc(sizeof(struct bst));
        node->left  = NULL;
        node->data  =   num;
        node->right = NULL;
        return;
    }
    else
    {
        if(num < node->data)
        {
            insert(&(node->left), num);
        }
        else
        {
            insert(&(node->right), num);
        }
    }
    return;
}

void print(struct bst *root)
{
    struct bst *temp = root;

    if(temp != NULL)
    {
        printf("%d --> ", temp->data);
        print(temp->left);
        print(temp->right);
    }
    else
    return;
}
</code>```

答:
You make a local copy of the root pointer:

```<code>struct bst *node = *root;
</code>```

You then may modify it:

```<code>node = (struct bst*)malloc(sizeof(struct bst));
</code>```

Unfortunately, you don't propagate this change back to the caller, and so the change is lost:(

Try:

```<code>*root=node;
</code>```

at the end.

I strongly suspect that this is what @ Some programmer dude was hinting at in his comment:)

Title: What's the Bug in this code ?

Body:
I have initialized the root to NULL at the starting and the same will go to the first insert function. As i have sent the address of root, it should be changed, but its not, again in the second insert statement NULL vakue for root is going inside the insert function.

Please let me know, where I have missed it.

#include <stdio.h>
#include <stdlib.h>
typedef struct bst{
    struct bst *left;
    int data;
    struct bst *right;
}bst_t;

void insert(struct bst**, int);
void print(struct bst*);

int main() {
    struct bst *root;
    root = NULL;

    insert(&root, 45);
    insert(&root, 75);
    insert(&root, 5);
    insert(&root, 76);
    insert(&root, 25);
    insert(&root, 56);
    insert(&root, 89);
    insert(&root, 99);
    insert(&root, 98);

    print(root);

    printf("Print Any Char...\n");
    getch();
    return 0;
}

void insert(struct bst **root, int num)
{
    struct bst *node = *root;

    if(node == NULL)
    {
        node = (struct bst*)malloc(sizeof(struct bst));
        node->left  = NULL;
        node->data  =   num;
        node->right = NULL;
        return;
    }
    else
    {
        if(num < node->data)
        {
            insert(&(node->left), num);
        }
        else
        {
            insert(&(node->right), num);
        }
    }
    return;
}

void print(struct bst *root)
{
    struct bst *temp = root;

    if(temp != NULL)
    {
        printf("%d --> ", temp->data);
        print(temp->left);
        print(temp->right);
    }
    else
    return;
}

Body:
You make a local copy of the root pointer:

struct bst *node = *root;

You then may modify it:

node = (struct bst*)malloc(sizeof(struct bst));

Unfortunately, you don't propagate this change back to the caller, and so the change is lost:(

Try:

*root=node;

at the end.

I strongly suspect that this is what @ Some programmer dude was hinting at in his comment:)


问:
Spring MVC @Controller to intercept own requests
Imagine we have a controller like this:

```<code>@RestController
@RequestMapping("/{parameter}")
public class MyController {

    @ExceptionHandler(SomeException.class)
    public Object handleSomeException() { /* handle */ }

    @RequestMapping("/something")
    public Object handleSomething(@PathVariable("parameter") String parameter) {
        /* handle */
    }

    @RequestMapping("/somethingElse")
    public Object handleSomethingElse(@PathVariable("parameter") String parameter) {
        /* handle */
    }
}
</code>```

The question is, how to implement some common pre-\post-handling for this particular controller in similar way as @ExceptionHandler is working? E.g. I want to have a method in controller which receives request prior to handler methods, but only requests for this particular controller.

I'm aware of RequestBodyAdvice and ResponseBodyAdvice interfaces, but want something local to controller.

As a usage example - I want to do some validation for common parameter variable before each handler.

答:
You will need to write you own HandlerInterceptor. You can do it easily by extending HandlerInterceptorAdapter. And then you can override preHandle() and/or postHandle().

preHandle() is called after HandlerMapping determined an appropriate
  handler object, but before HandlerAdapter invokes the handler.

postHandle() is called after HandlerAdapter actually invoked the
  handler, but before the DispatcherServlet renders the view.

You can use the getRequestURI() method of HttpServletRequest to add logics for different handlers in preHandle().

Example:

```<code>public class ValidationInterceptor extends HandlerInterceptorAdapter {

    public static final String FOO_URL = "foo";
    public static final String BAR_URL = "bar";

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        String uri = request.getRequestURI();

        if (FOO_URL.equals(uri)) {
            // for example - validation failed
            response.sendRedirect("/to/some/url");
            return false;
        } else if (BAR_URL.equals(uri)) {
            // for example - validation successful
        }
        return true;
    }
}
</code>```

Then register this HandlerInterceptor in your dispatcher-servlet.xml.

```<code><mvc:interceptors>
    <bean class="your.package.ValidationInterceptor"/>
</mvc:interceptors>
</code>```

You can configure this to be more url-specific. See 22.16.5 Interceptors section of Spring Reference.

Body:
Imagine we have a controller like this:

@RestController
@RequestMapping("/{parameter}")
public class MyController {

    @ExceptionHandler(SomeException.class)
    public Object handleSomeException() { /* handle */ }

    @RequestMapping("/something")
    public Object handleSomething(@PathVariable("parameter") String parameter) {
        /* handle */
    }

    @RequestMapping("/somethingElse")
    public Object handleSomethingElse(@PathVariable("parameter") String parameter) {
        /* handle */
    }
}

The question is, how to implement some common pre-\post-handling for this particular controller in similar way as @ExceptionHandler is working? E.g. I want to have a method in controller which receives request prior to handler methods, but only requests for this particular controller.

I'm aware of RequestBodyAdvice and ResponseBodyAdvice interfaces, but want something local to controller.

As a usage example - I want to do some validation for common parameter variable before each handler.

Body:
You will need to write you own HandlerInterceptor. You can do it easily by extending HandlerInterceptorAdapter. And then you can override preHandle() and/or postHandle().

preHandle() is called after HandlerMapping determined an appropriate
  handler object, but before HandlerAdapter invokes the handler.

postHandle() is called after HandlerAdapter actually invoked the
  handler, but before the DispatcherServlet renders the view.

You can use the getRequestURI() method of HttpServletRequest to add logics for different handlers in preHandle().

Example:

public class ValidationInterceptor extends HandlerInterceptorAdapter {

    public static final String FOO_URL = "foo";
    public static final String BAR_URL = "bar";

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        String uri = request.getRequestURI();

        if (FOO_URL.equals(uri)) {
            // for example - validation failed
            response.sendRedirect("/to/some/url");
            return false;
        } else if (BAR_URL.equals(uri)) {
            // for example - validation successful
        }
        return true;
    }
}

Then register this HandlerInterceptor in your dispatcher-servlet.xml.

<mvc:interceptors>
    <bean class="your.package.ValidationInterceptor"/>
</mvc:interceptors>

You can configure this to be more url-specific. See 22.16.5 Interceptors section of Spring Reference.


问:
Getting the id of the last record inserted into a MySQL database
I'm trying to get the id of the last record inserted into a MySQL database using MAX(id).
I can't figure out why my query is not returning any results. Is there something wrong with my PHP?Tthe query works if I try it inside phpmyadmin.

```<code>include("db_conx.php"); //Connect to db mysqli
$sql = "SELECT MAX(id) FROM tbl_uploads";
$result = $db_conx->query($sql);
$row = $result->fetch_assoc();
echo 'last_id: '.$row['id'];
</code>```

答:
Use MAX(id) as id in select query

```<code>include("db_conx.php"); //Connect to db mysqli
$sql = "SELECT MAX(id) as id FROM tbl_uploads";
$result = $db_conx->query($sql);
$row = $result->fetch_assoc();
echo 'last_id: '.$row['id'];
</code>```

Body:
I'm trying to get the id of the last record inserted into a MySQL database using MAX(id).
I can't figure out why my query is not returning any results. Is there something wrong with my PHP?Tthe query works if I try it inside phpmyadmin.

include("db_conx.php"); //Connect to db mysqli
$sql = "SELECT MAX(id) FROM tbl_uploads";
$result = $db_conx->query($sql);
$row = $result->fetch_assoc();
echo 'last_id: '.$row['id'];

Body:
Use MAX(id) as id in select query

include("db_conx.php"); //Connect to db mysqli
$sql = "SELECT MAX(id) as id FROM tbl_uploads";
$result = $db_conx->query($sql);
$row = $result->fetch_assoc();
echo 'last_id: '.$row['id'];


问:
Convert UTC Time with offset to LocalTime
I am using joda 2.7, I want to convert

```<code>      UTC Time= 09:30:10-06:00
   to Local Time= 03:30:10
         and
      UTC Time=10:45:00+07:30
   to Local Time = 18:15:00
</code>```

I tried different formats both joda's and my own and methods to handle the offset part, but I am not able to get the required output. What is the best approach.

答:
You can do:

DateTimeFormatter fmt = DateTimeFormat.forPattern("HH:mm:ssZ");
String utcTime = "09:30:10-06:00";
DateTime localTime = fmt.parseDateTime(utcTime);
String localTimeString = localTime.toString("HH:mm:ss");
```

<p>This will convert it to your local time, according to your default timezone (do <code>System.out.println(DateTimeZone.getDefault())</code> to check what's your default timezone).</p>

<p>If you want to convert to a different timezone, you need to do something like:</p>

<pre class="lang-java prettyprint-override"><code>DateTimeFormatter fmt = DateTimeFormat.forPattern("HH:mm:ssZ").withZone(/*DateTimeZone you want*/);
</code>```

In your specific cases, to get the output you want, you just need to use the timezone in which you have the desired outputs:

DateTimeFormatter fmt = DateTimeFormat.forPattern("HH:mm:ssZ").withZone(DateTimeZone.forOffsetHours(-12));

String utcTime = "09:30:10-06:00";
DateTime localTime = fmt.parseDateTime(utcTime);
System.out.println(localTime.toString("HH:mm:ss"));

utcTime = "10:45:00+07:30";
localTime = fmt.withZone(DateTimeZone.forOffsetHours(15)).parseDateTime(utcTime);
System.out.println(localTime.toString("HH:mm:ss"));
```

<p>Output is:</p>

<pre class="lang-java prettyprint-override"><code>03:30:10
18:15:00
</code>```

Body:
I am using joda 2.7, I want to convert

      UTC Time= 09:30:10-06:00
   to Local Time= 03:30:10
         and
      UTC Time=10:45:00+07:30
   to Local Time = 18:15:00

I tried different formats both joda's and my own and methods to handle the offset part, but I am not able to get the required output. What is the best approach.

Body:
You can do:

DateTimeFormatter fmt = DateTimeFormat.forPattern("HH:mm:ssZ");
String utcTime = "09:30:10-06:00";
DateTime localTime = fmt.parseDateTime(utcTime);
String localTimeString = localTime.toString("HH:mm:ss");

This will convert it to your local time, according to your default timezone (do System.out.println(DateTimeZone.getDefault()) to check what's your default timezone).

If you want to convert to a different timezone, you need to do something like:

DateTimeFormatter fmt = DateTimeFormat.forPattern("HH:mm:ssZ").withZone(/*DateTimeZone you want*/);

In your specific cases, to get the output you want, you just need to use the timezone in which you have the desired outputs:

DateTimeFormatter fmt = DateTimeFormat.forPattern("HH:mm:ssZ").withZone(DateTimeZone.forOffsetHours(-12));

String utcTime = "09:30:10-06:00";
DateTime localTime = fmt.parseDateTime(utcTime);
System.out.println(localTime.toString("HH:mm:ss"));

utcTime = "10:45:00+07:30";
localTime = fmt.withZone(DateTimeZone.forOffsetHours(15)).parseDateTime(utcTime);
System.out.println(localTime.toString("HH:mm:ss"));

Output is:

03:30:10
18:15:00


问:
What is the difference between session_unset() and session_destroy() in PHP?
From the php.net documentation:

session_destroy — Destroys all data registered to a session

session_unset — Free all session variables

My three part question is:

The two functions seem very similar.

What is really the difference between the two?

Both seem to delete all variables registered to a session. Does any of them actually destroy the session itself? If not, how do you accomplish this (destroy the session itself).

Is it correct that neither of the two functions deletes the session cookie at the client?

答:
session_unset just clears the $_SESSION variable. It’s equivalent to doing:

```<code>$_SESSION = array();
</code>```

So this does only affect the local $_SESSION variable instance but not the session data in the session storage.

In contrast to that, session_destroy destroys the session data that is stored in the session storage (e.g. the session file in the file system).

Everything else remains unchanged.

Body:
session_unset just clears the $_SESSION variable. It’s equivalent to doing:

$_SESSION = array();

So this does only affect the local $_SESSION variable instance but not the session data in the session storage.

In contrast to that, session_destroy destroys the session data that is stored in the session storage (e.g. the session file in the file system).

Everything else remains unchanged.


问:
Javascript method always returns same value
I have two methods in my class. One method randomizes values, another one returns those values in a string that represents CSS color. Yet after randomization it still returns same string all the time, even though values in created object are changed. Can you please explain why?

Here's jsfiddle: https://jsfiddle.net/wpem1j9e/

```<code>function Color(r, g, b) {
    this.r = r;
    this.g = g;
    this.b = b;
    this.randomize = function(){
        this.r = Math.floor(Math.random() * 100);
        this.g = Math.floor(Math.random() * 100);
        this.b = Math.floor(Math.random() * 100);
        return this;
    }
    this.toString = function(){
        var cssColor = "rgb(" + r + "%," + g + "%," + b + "%)";
        return cssColor;
    }
}
var color1 = new Color (1, 1, 1);
color1.randomize().toString(); // still returns "rgb(1%,1%,1%)";
</code>```

答:
You can alleviate a whole lot of confusion by just ditching the use of this. It provides no benefit here.

function color(r, g, b) {
  var me = {
    randomize: function() {
      r = Math.floor(Math.random() * 100);
      g = Math.floor(Math.random() * 100);
      b = Math.floor(Math.random() * 100);
      return me;
    },
    toString: function() {
      var cssColor = "rgb(" + r + "%," + g + "%," + b + "%)";
      return cssColor;
    }
  };

  return me;
}
var color1 = color(1, 1, 1);
console.log(color1.randomize().toString());```

Body:
I have two methods in my class. One method randomizes values, another one returns those values in a string that represents CSS color. Yet after randomization it still returns same string all the time, even though values in created object are changed. Can you please explain why?

Here's jsfiddle: https://jsfiddle.net/wpem1j9e/

function Color(r, g, b) {
    this.r = r;
    this.g = g;
    this.b = b;
    this.randomize = function(){
        this.r = Math.floor(Math.random() * 100);
        this.g = Math.floor(Math.random() * 100);
        this.b = Math.floor(Math.random() * 100);
        return this;
    }
    this.toString = function(){
        var cssColor = "rgb(" + r + "%," + g + "%," + b + "%)";
        return cssColor;
    }
}
var color1 = new Color (1, 1, 1);
color1.randomize().toString(); // still returns "rgb(1%,1%,1%)";


问:
Nginx 403 forbidden using Location directive on PHP file
Here's my server block:

```<code>server {
    listen       80;
    server_name  localhost;

    root /www/html;
    index index.php;

    location = / {
        autoindex on;
        index index.php;
        try_files $uri $uri/ =404;
    }

    location ~*\.(css|js|gif|jpe?g|png)$ {
        root /www/html/shared;
        rewrite ^/releases(.*)$ $1 last;
        expires 5m;
    }

    location ~* \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
}
</code>```

Right now, doing this will just spit out a "403 Forbidden" error when I attempt to access "localhost/". However, the page works perfectly fine if I access it directly-- "localhost/index.php". I can't for the life of me figure out why. The error.log doesn't give me any helpful info nor an error code either--only that the page is "forbidden".
Here's the thrown error:

```<code>2017/03/29 14:37:35 [error] 11980#8840: *94 directory index of "C:/www/html/" is forbidden, client: 127.0.0.1, server: localhost, request: "GET / HTTP/1.1", host: "localhost"
</code>```

This is a windows-based nginx server.

答:
the answer was kind of disappointing to discover, but i'm gonna answer it so if anyone encounters this goofy issue they can fix it.

php was lookng for files with the prefix "/www/html", NOT "/www/html/", as a result when it wanted my index it was trying to load "/www/htmlindex.php" instead of "/www/html/index.php".

you can fix this by doing either

```<code> fastcgi_index /index.php;
</code>```

or adding a / to the end of your root.

Body:
Here's my server block:

server {
    listen       80;
    server_name  localhost;

    root /www/html;
    index index.php;

    location = / {
        autoindex on;
        index index.php;
        try_files $uri $uri/ =404;
    }

    location ~*\.(css|js|gif|jpe?g|png)$ {
        root /www/html/shared;
        rewrite ^/releases(.*)$ $1 last;
        expires 5m;
    }

    location ~* \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
}

Right now, doing this will just spit out a "403 Forbidden" error when I attempt to access "localhost/". However, the page works perfectly fine if I access it directly-- "localhost/index.php". I can't for the life of me figure out why. The error.log doesn't give me any helpful info nor an error code either--only that the page is "forbidden".
Here's the thrown error:

2017/03/29 14:37:35 [error] 11980#8840: *94 directory index of "C:/www/html/" is forbidden, client: 127.0.0.1, server: localhost, request: "GET / HTTP/1.1", host: "localhost"

This is a windows-based nginx server.

Body:
the answer was kind of disappointing to discover, but i'm gonna answer it so if anyone encounters this goofy issue they can fix it.

php was lookng for files with the prefix "/www/html", NOT "/www/html/", as a result when it wanted my index it was trying to load "/www/htmlindex.php" instead of "/www/html/index.php".

you can fix this by doing either

 fastcgi_index /index.php;

or adding a / to the end of your root.


问:
JQuery & PHP: How to pass appended button value to jquery? Is it possible?
I am appending items (articles) to a content with some originally existing articles, each article has a button for its deleting, editing, opening. I use jquery & ajax.
I want these appended articles' buttons to be able to pass each of their values to jquery click function, as well as produce all the logic there (same way as original articles' buttons do).
Is it possible to do something that way?</p>

```<code><!DOCTYPE html>
<html>
<head>
    <title>Infinite Software Blog</title>
    <meta name="viewport" content="width=device-width, scale=1.0">
    <script type="text/javascript" src="/blog/jquery/jquery-3.2.0.min.js"></script>
    <script>
        $(document).ready(function () {
            $('.del_btn').click(function () {
                var clickBtnValue = $(this).val();
                var ajaxurl = '/blog/helpers/delete_post.php',
                    data = {'action': clickBtnValue};
                $.post(ajaxurl, data, function () {
                    alert("Post was successfully deleted");
                });
            });
            $('.edit_btn').click(function () {
                var clickBtnValue = $(this).val();
                console.log(clickBtnValue);
                var ajaxurl = '/blog/edit_post.php',
                    data = {'action': clickBtnValue};
                $.post(ajaxurl, data, function () {
                    window.location.assign("/blog/helpers/updatePost.php");
                });
            });
            $('.post_content_btn').click(function () {
                var clickBtnValue = $(this).val();
                var ajaxurl = '/blog/view/post.php',
                    data = {'action': clickBtnValue};
                $.post(ajaxurl, data, function () {
                    window.location.assign("/blog/post.php");
                });
            });
            $('.more_posts_btn').click(function () {
                var clickBtnValue = $(this).val();
                var ajaxurl = '/blog/helpers/show_more_posts.php',
                    data = {'action': clickBtnValue};
                $.post(ajaxurl, data, function (output) {
                    $(".content").append(output);
                });
            });
        });
    </script>
    <link rel="stylesheet" href="/blog/styles/style.css" type="text/css"/>
</head>

show_more_post.php
<?php
if (isset($_POST['action'])) {
    include($_SERVER['DOCUMENT_ROOT'] . "/blog/model/classes.php");
    $post = new posts();
    $postsToDisplay = $post->getPostsQty($_POST['action']);
    $newRecordsIndex = $_POST['action'];
    for ($i = 1; $i <= $postsToDisplay; $i++) {
        $record = $post->getPost($newRecordsIndex);
        $newRecordsIndex++;
        $elementToAdd = '<article class="topContent"><header><h2><a href="#" title="' . $record[1] . '">' .
            $record[1] . '</a></h2></header><footer><p class="post-author">Author: ' . $record[2] . '</p>' .
            '</footer><content>' . $record[6] . '</content><footer><p class="post-date">Publish date: ' .
            $record[3] . '</p>' . '<p class="post-time">Publish time: ' . $record[4] . '</p><form><button type="submit"
            title="Delete post"' . ' value="' . $record[0] . '" class="del_btn">Delete post</button><button type="submit"
            title="Edit post"' . ' value="' . $record[0] . '" class="edit_btn">Edit post</button><button type="submit"
            title="Open post in a new tab" value="' . $record[0] . '" class="post_content_btn">Open Post</button>
            </form></footer></article>';
        echo($elementToAdd);
    }
}
</code>```

答: Use <code>$(document).on('<event>', '<selector>', function() {});</code> to make available events on dom elements, that creates after script init. </p>

Body:
I am appending items (articles) to a content with some originally existing articles, each article has a button for its deleting, editing, opening. I use jquery & ajax.
I want these appended articles' buttons to be able to pass each of their values to jquery click function, as well as produce all the logic there (same way as original articles' buttons do).
Is it possible to do something that way?

<!DOCTYPE html>

    <title>Infinite Software Blog</title>
    <meta name="viewport" content="width=device-width, scale=1.0">

    <link rel="stylesheet" href="/blog/styles/style.css" type="text/css"/>

show_more_post.php
<?php
if (isset($_POST['action'])) {
    include($_SERVER['DOCUMENT_ROOT'] . "/blog/model/classes.php");
    $post = new posts();
    $postsToDisplay = $post->getPostsQty($_POST['action']);
    $newRecordsIndex = $_POST['action'];
    for ($i = 1; $i <= $postsToDisplay; $i++) {
        $record = $post->getPost($newRecordsIndex);
        $newRecordsIndex++;
        $elementToAdd = '

' .
            $record[1] . '

Author: ' . $record[2] . '
' .
            '<content>' . $record[6] . '</content>
Publish date: ' .
            $record[3] . '
' . '
Publish time: ' . $record[4] . '
<form><button type="submit"
            title="Delete post"' . ' value="' . $record[0] . '" class="del_btn">Delete post</button><button type="submit"
            title="Edit post"' . ' value="' . $record[0] . '" class="edit_btn">Edit post</button><button type="submit"
            title="Open post in a new tab" value="' . $record[0] . '" class="post_content_btn">Open Post</button>
            </form>
';
        echo($elementToAdd);
    }
}

Body: Use $(document).on('<event>', '<selector>', function() {}); to make available events on dom elements, that creates after script init.


问:
Error:(137, 20) error: unreachable statement
```<code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
  //return true;
  return super.onCreateOptionsMenu(menu);
  MenuInflater mif = getMenuInflater();
  mif.inflate(R.menu.mainmenu,menu);
}
</code>```

答:
Because return is the last line/statement executed in any method... all that is written after that is dead code and makes no sense since it can not be executed...

you should instead

```<code>MenuInflater mif = getMenuInflater();
mif.inflate(R.menu.mainmenu,menu);
return super.onCreateOptionsMenu(menu);
</code>```

Body:
Because return is the last line/statement executed in any method... all that is written after that is dead code and makes no sense since it can not be executed...

you should instead

MenuInflater mif = getMenuInflater();
mif.inflate(R.menu.mainmenu,menu);
return super.onCreateOptionsMenu(menu);


问:
how to display object details in alert in ionic 1
On clicking a button i am invoking this funtion

```<code>$scope.showAlert = function(item) {
   var alertPopup = $ionicPopup.alert({
     title: 'Data',
     template: JSON.stringify(item),
   });

   alertPopup.then(function(res) {
     console.log('Thank you for not eating my delicious ice cream cone');
   });
 };
</code>```

my object look like this

```<code>{id: 2, firstname: "abcd", lastname: "xyza", class: "1", attendance: "123"}
</code>```

i am able to get the alert in object formate but i want to dis play in this way .

```<code>var alertPopup = $ionicPopup.alert({
         title: 'Data',
         template: 'firstname: item.firstname,
                   lastname: item.lastname,
                   class: item.class,
                   attendance: item.attendance'
       });
</code>```

it will be print in one line after another line how can i achive this in ionic 1

答:
I hope this will help you</p>

```<code>var alertPopup = $ionicPopup.alert({
         title: 'Data',
         template: "firstname: "+item.firstname+' ,'+"<br>"+"lastname:                         "+item.lastname+' ,'+"<br>"+"class: "+item.class+' ,'+"<br>"+"attendance: "+item.attendance
       });
</code>```

Body:
On clicking a button i am invoking this funtion

$scope.showAlert = function(item) {
   var alertPopup = $ionicPopup.alert({
     title: 'Data',
     template: JSON.stringify(item),
   });

   alertPopup.then(function(res) {
     console.log('Thank you for not eating my delicious ice cream cone');
   });
 };

my object look like this

{id: 2, firstname: "abcd", lastname: "xyza", class: "1", attendance: "123"}

i am able to get the alert in object formate but i want to dis play in this way .

var alertPopup = $ionicPopup.alert({
         title: 'Data',
         template: 'firstname: item.firstname,
                   lastname: item.lastname,
                   class: item.class,
                   attendance: item.attendance'
       });

it will be print in one line after another line how can i achive this in ionic 1

Body:
I hope this will help you

var alertPopup = $ionicPopup.alert({
         title: 'Data',
         template: "firstname: "+item.firstname+' ,'+"<br>"+"lastname:                         "+item.lastname+' ,'+"<br>"+"class: "+item.class+' ,'+"<br>"+"attendance: "+item.attendance
       });


问:
sendmailR (Part2): Sending files as mail attachments
Following the directions provided in this related question, I was able to send html formated mail messages. Now the question is this: How should I modify the following code, in order to attach one or more files (of any type) to this message?</p>

```<code>library(sendmailR)

from <- "<sendmailR@myserver.mycompany.com>"
to <- c("<someone@mycompany.com>","<anotherone@mycompany.com>")
subject <- iconv("Message Title", to = "utf8")

msg <- "<hr size='2' width='33%' style='text-align: left;'><font size='2'>
  <i>This email was sent automatically using <a href='http://finzi.psych.upenn.edu/R/library/sendmailR/html/00Index.html' rel='nofollow' target='_blank'>sendmailR</a>.<br>
  Please do not reply directly to this e-mail.</i></font>"

msg <- iconv(msg, to = "utf8")

sapply(to,function(x) sendmail(from, x, subject, msg, control=list(smtpServer="###.###.###.###"), headers=list("Content-Type"="text/html; charset=UTF-8; format=flowed")))
</code>```

答:
Here's an example that is setup for a daily batch job like setting using sendmail() in R (available with the package sendmailR) with multiple attachments (one CSV, one PDF):

Setting up date information to reference in the file names:

```<code>> yesterday_date_stuff  <- new.env()
> yesterday_date_stuff[['month']] <- strftime(Sys.Date()-1, format="%m")
> yesterday_date_stuff[['day']] <- strftime(Sys.Date()-1, format="%d")
> yesterday_date_stuff[['year']] <- strftime(Sys.Date()-1, format="%y")
> yesterday_date_stuff$month
[1] "03"
> yesterday_date_stuff$day
[1] "29"
> yesterday_date_stuff$year
[1] "17"
</code>```

Now create some of the needed information for sendmail() function at the end of this post:

```<code>> from <- "youremail@whateveryourmailserveris.com"
> to <- c("person_A_to_send_email_to@whatever.com", "person_B_to_send_email_to@whatever.com", "person_C_to_send_email_to@whatever.com")
> subject <- paste("whatever you want subject line to read for batch job analyzing data for ", yesterday_date_stuff$month, "/", yesterday_date_stuff$day, "/", yesterday_date_stuff$year, sep="")
> body <- "Text to insert into the body of your email"
</code>```

Specify mail server here:

```<code>> mailControl=list(smtpServer="mail.whateveryourmailserveris.com")
</code>```

Define attachment 1 path and name:

```<code>> attachmentPath1 <- paste("file1name", "_", yesterday_date_stuff$month, yesterday_date_stuff$day, yesterday_date_stuff$year, ".csv", sep="")
> attachmentName1 <- paste("file1name", "_", yesterday_date_stuff$month, yesterday_date_stuff$day, yesterday_date_stuff$year, ".csv", sep="")
</code>```

Define attachment 1 object:

```<code>> attachmentObject1 <- mime_part(x=attachmentPath1,name=attachmentName1)
</code>```

Define attachment 2 path and name:

```<code>> attachmentPath2 <- paste("file2name", "_", yesterday_date_stuff$month, yesterday_date_stuff$day, yesterday_date_stuff$year, ".pdf", sep="")
> attachmentName2 <- paste("file2name", "_", yesterday_date_stuff$month, yesterday_date_stuff$day, yesterday_date_stuff$year, ".pdf", sep="")
</code>```

Define attachment 2 object:

```<code>> attachmentObject2 <- mime_part(x=attachmentPath2,name=attachmentName2)
</code>```

Now combine the body of the email with your attachments:

```<code>> bodyWithAttachment <- list(body,attachmentObject1, attachmentObject2)
> bodyWithAttachment
[[1]]
[1] "Text to insert into the body of your email"

[[2]]
<environment: 0x000000004efff188>
attr(,"class")
[1] "mime_part"

[[3]]
<environment: 0x00000000407a1b68>
attr(,"class")
[1] "mime_part"
</code>```

Send the email using sendmail() function:

```<code>> sendmail(from=from, to=to, subject=subject, msg=bodyWithAttachment, control=mailControl)
</code>```

Body:
Following the directions provided in this related question, I was able to send html formated mail messages. Now the question is this: How should I modify the following code, in order to attach one or more files (of any type) to this message?

library(sendmailR)

from <- "<sendmailR@myserver.mycompany.com>"
to <- c("<someone@mycompany.com>","<anotherone@mycompany.com>")
subject <- iconv("Message Title", to = "utf8")

msg <- "

  This email was sent automatically using sendmailR.

  Please do not reply directly to this e-mail."

msg <- iconv(msg, to = "utf8")

sapply(to,function(x) sendmail(from, x, subject, msg, control=list(smtpServer="###.###.###.###"), headers=list("Content-Type"="text/html; charset=UTF-8; format=flowed")))

Body:
Here's an example that is setup for a daily batch job like setting using sendmail() in R (available with the package sendmailR) with multiple attachments (one CSV, one PDF):

Setting up date information to reference in the file names:

> yesterday_date_stuff  <- new.env()
> yesterday_date_stuff[['month']] <- strftime(Sys.Date()-1, format="%m")
> yesterday_date_stuff[['day']] <- strftime(Sys.Date()-1, format="%d")
> yesterday_date_stuff[['year']] <- strftime(Sys.Date()-1, format="%y")
> yesterday_date_stuff$month
[1] "03"
> yesterday_date_stuff$day
[1] "29"
> yesterday_date_stuff$year
[1] "17"

Now create some of the needed information for sendmail() function at the end of this post:

> from <- "youremail@whateveryourmailserveris.com"
> to <- c("person_A_to_send_email_to@whatever.com", "person_B_to_send_email_to@whatever.com", "person_C_to_send_email_to@whatever.com")
> subject <- paste("whatever you want subject line to read for batch job analyzing data for ", yesterday_date_stuff$month, "/", yesterday_date_stuff$day, "/", yesterday_date_stuff$year, sep="")
> body <- "Text to insert into the body of your email"

Specify mail server here:

> mailControl=list(smtpServer="mail.whateveryourmailserveris.com")

Define attachment 1 path and name:

> attachmentPath1 <- paste("file1name", "_", yesterday_date_stuff$month, yesterday_date_stuff$day, yesterday_date_stuff$year, ".csv", sep="")
> attachmentName1 <- paste("file1name", "_", yesterday_date_stuff$month, yesterday_date_stuff$day, yesterday_date_stuff$year, ".csv", sep="")

Define attachment 1 object:

> attachmentObject1 <- mime_part(x=attachmentPath1,name=attachmentName1)

Define attachment 2 path and name:

> attachmentPath2 <- paste("file2name", "_", yesterday_date_stuff$month, yesterday_date_stuff$day, yesterday_date_stuff$year, ".pdf", sep="")
> attachmentName2 <- paste("file2name", "_", yesterday_date_stuff$month, yesterday_date_stuff$day, yesterday_date_stuff$year, ".pdf", sep="")

Define attachment 2 object:

> attachmentObject2 <- mime_part(x=attachmentPath2,name=attachmentName2)

Now combine the body of the email with your attachments:

> bodyWithAttachment <- list(body,attachmentObject1, attachmentObject2)
> bodyWithAttachment
[[1]]
[1] "Text to insert into the body of your email"

[[2]]
<environment: 0x000000004efff188>
attr(,"class")
[1] "mime_part"

[[3]]
<environment: 0x00000000407a1b68>
attr(,"class")
[1] "mime_part"

Send the email using sendmail() function:

> sendmail(from=from, to=to, subject=subject, msg=bodyWithAttachment, control=mailControl)