问:
Is it better practice to style an element based on its state with a data attribute or class?
I'm wondering what the best practice here is for styling an element based on its state.

I have some content that can take a while to load, whilst it's loading I want to show a loading spinner.

Is it better to apply a class of 'loading' to the element until it's loaded, then remove this class with JS. Using the 'loading' class to render the spinner.

Or is it better practice to disassociate the loading state from a class and use a data attribute, i.e. [data-status = "loading"]. Then applying my styles to the data attribute rather than the class.

Cheers.

答:
When a certain area (HTML element) can have different views, but all the different views use the same data, then I believe it is more semantically "correct" to use a data attribute.

I normally use data-view, but if it's a loading state, then I would use a class, and create some generalized solution for all things with that
loading class to look the same, if possible.

A simple example, if you have a div which shows some data which is visually represented by some graph/chart and the user can switch the view of that area to become a "table" view, than that div would look like this:

default state

```<code><div class='myComponent' data-view='chart'>...</div>
</code>```

loading state

```<code><div class='myComponent loading'>...</div>
</code>```

alternative-view state

```<code><div class='myComponent' data-view='table'>...</div>
</code>```

I use this style of coding extensively, and it can get nested. for example, I usually work on SPA pages, where the content of the page changes depending on the URL, so the main HTML element might look like:

```<code><main id="page" data-view="home">
</code>```

And the CSS:

```<code>#page[data-view="home"]{
...
}
</code>```

OwnerDisplayName: anon

Body:
When a certain area (HTML element) can have different views, but all the different views use the same data, then I believe it is more semantically "correct" to use a data attribute.

I normally use data-view, but if it's a loading state, then I would use a class, and create some generalized solution for all things with that
loading class to look the same, if possible.

A simple example, if you have a div which shows some data which is visually represented by some graph/chart and the user can switch the view of that area to become a "table" view, than that div would look like this:

default state

<div class='myComponent' data-view='chart'>...</div>

loading state

<div class='myComponent loading'>...</div>

alternative-view state

<div class='myComponent' data-view='table'>...</div>

I use this style of coding extensively, and it can get nested. for example, I usually work on SPA pages, where the content of the page changes depending on the URL, so the main HTML element might look like:

<main id="page" data-view="home">

And the CSS:

#page[data-view="home"]{
...
}


来源: stackexchange

问:
How to set selected or default value in select2 yii2?
How to set selected or default value in select2 yii2?
i've tried using 'value' => $myvalue and 'initValue' => $myValue

Is there any solution? Thank You.

I've just found solution.
here if you want to set default value or selected value for select :

```<code><?php $model->group = yourdefaultValue ?>
<?=$form->field($model, 'group')->label('Group Name')->widget(Select2::classname(),
[
     'data' => ArrayHelper::map(Group::find()->all(),'id','name', 'kategori'),
     'options' => ['placeholder' => 'Select Phone Number'],
     'pluginOptions' => [
           'allowClear' => true,
           'minimumInputLength' => 2,
     ],
]);
?>
</code>```

答:
```<code><?php $form = ActiveForm::begin() ?>
<?=$form->field($model, 'group')->label('Group Name')->widget(Select2::classname(),
    [
        'data' => ArrayHelper::map(Group::find()->all(),'id','name', 'kategori'),
        'options' => ['placeholder' => 'Select Phone Number', 'value' => 1],
        'pluginOptions' => [
            'allowClear' => true,
            'minimumInputLength' => 2,
        ],
    ]);
?>
<?php $form::end()?>
</code>```

You just need set default value in selection.

```<code>'options' => ['placeholder' => 'Select Phone Number',
</code>```

'value' => $model->id

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

ContentLicense: CC BY-SA 3.0

Body:
How to set selected or default value in select2 yii2?
i've tried using 'value' => $myvalue and 'initValue' => $myValue

Is there any solution? Thank You.

I've just found solution.
here if you want to set default value or selected value for select :

<?php $model->group = yourdefaultValue ?>
<?=$form->field($model, 'group')->label('Group Name')->widget(Select2::classname(),
[
     'data' => ArrayHelper::map(Group::find()->all(),'id','name', 'kategori'),
     'options' => ['placeholder' => 'Select Phone Number'],
     'pluginOptions' => [
           'allowClear' => true,
           'minimumInputLength' => 2,
     ],
]);
?>

Body:
<?php $form = ActiveForm::begin() ?>
<?=$form->field($model, 'group')->label('Group Name')->widget(Select2::classname(),
    [
        'data' => ArrayHelper::map(Group::find()->all(),'id','name', 'kategori'),
        'options' => ['placeholder' => 'Select Phone Number', 'value' => 1],
        'pluginOptions' => [
            'allowClear' => true,
            'minimumInputLength' => 2,
        ],
    ]);
?>
<?php $form::end()?>

You just need set default value in selection.

'options' => ['placeholder' => 'Select Phone Number',

'value' => $model->id

]


问:
Subtracting of a SUM?
I was wondering if I could perform this algebraic use, Here is the ones I am trying to perform with.

```<code>JCCM.BilledAmt + JCCM.udGEACrev As REVENUE_2,
(JCCM.udGEACrev + JCCM.BilledAmt) - JCCP.ActualCost As BilledCostDifference,
</code>```

I tried adding REVENUE_2 between the brackets but the Report Builder does not take it as a column

答:
Yes.

Add a calculated field to your dataset:

-Right click dataset -> Add Calculated Field

Enter the following values in the dialog that pops up:

-Field name: REVENUE_2

-Field source: Fields!JCCM.BilledAmt.Value + Fields!JCCM.udGEACrev.Value

Add another calculated field with the following values:

-Field name: BilledCostDifference

-Field source: Fields!REVENUE_2.Value - Fields!JCCP.ActualCost.Value

Drag the second calculated field to your report.

NOTE:

SSRS will not recognize the first calculated field you added unless you hit OK. So add the first calculated field, hit OK, add the second calculated field.

Title: Subtracting of a SUM?

Body:
I was wondering if I could perform this algebraic use, Here is the ones I am trying to perform with.

JCCM.BilledAmt + JCCM.udGEACrev As REVENUE_2,
(JCCM.udGEACrev + JCCM.BilledAmt) - JCCP.ActualCost As BilledCostDifference,

I tried adding REVENUE_2 between the brackets but the Report Builder does not take it as a column


问:
getting xml child in javascript
I'm trying to get to to the items child in XML using javascript.

The rss file is: Can i use dot syntax? item.title? I'mg etting undefined in the code below

<item>
<title><link>

$(document).ready(function(){     alert =
  console.log;

```<code>  var ns = {
</code>```

```<code>    init : function(){
        $.ajax({
            url: '/calendar/RSSSyndicator.aspx?type=N&number=15&category=8-0%2c4-0%2c6-0%2c10-0%2c7-0%2c17-0%2c16-0%2c9-0%2c5-0%2c3-0%2c2-0&department=3&numdays=31&ics=Y&rsstitle=Annandale+-+Event+Listing&rssid=11',
            success: this.loaded
        });
    },

    loaded: function(data){
        // Get access to the events id in the DOM
        var events = document.getElementById('events');

        // Get item from the RSS document
        var items = data.getElementsByTagName('item');
    alert('test');

    }

}

ns.init();
</code>```

});

答:
The easiest way to debug issues like this is to load up the page in firefox after installing the FireBug plugin. In this plugin, you can set a breakpoint, and then inspect the items variable and see what properties and structure the object has.

Alternatively, if you are open to it, you can load up the XML into a jQuery object and then use those facilities to navigate the DOM.

ContentLicense: CC BY-SA 2.5

Title: getting xml child in javascript

Body:
I'm trying to get to to the items child in XML using javascript.

The rss file is: Can i use dot syntax? item.title? I'mg etting undefined in the code below

<item>
<title><link>

$(document).ready(function(){     alert =
  console.log;

  var ns = {

    init : function(){
        $.ajax({
            url: '/calendar/RSSSyndicator.aspx?type=N&number=15&category=8-0%2c4-0%2c6-0%2c10-0%2c7-0%2c17-0%2c16-0%2c9-0%2c5-0%2c3-0%2c2-0&department=3&numdays=31&ics=Y&rsstitle=Annandale+-+Event+Listing&rssid=11',
            success: this.loaded
        });
    },

    loaded: function(data){
        // Get access to the events id in the DOM
        var events = document.getElementById('events');

        // Get item from the RSS document
        var items = data.getElementsByTagName('item');
    alert('test');

    }

}

ns.init();

});


问:
arduino write and reading
I am working with C# and arduino. I am still a newbie on this. I wish someone can help me. So my project is to send some code to Arduino. Then apply delay on Arduino and send back some string/char back to C#. I gave a textbox on C# to show the result of reading. This is my code:
C# code

```<code>Public form1()
{
    initializeComponent();
    Serialport1.Open();
}

public void Read()
{
    while (Serialport1.IsOpen)
    {
        try
        {
            string message = SerialPort1.ReadLine();
            textbox1.text = message;
        }
        catch (timeoutException)
        {
        }
    }
}
private void button1_click(object sender, eventargs e)
{
    SerialPort1.write("A");
    read();
}
</code>```

arduino code:

```<code>int data;
void setup()
{
    Serial.begin(9600);
    Serial.print("START\n");
}

void loop()
{
    if(Serial.available())
    {
        data = Serial.read();
        if(data=='A')
        {
            delay(3000);
            Serial.print("B");
        }
    }
}
</code>```

What I wish is textbox result write B, but nothing is come and the textbox keep blank. What did I do wrong? I hope someone can explain to me. Thank you

答:
You Should attach a listener to the port like this:

SerialPort port = new SerialPort("COM4", 9600);
port.DataReceived += new SerialDataReceivedEventHandler(dataReceivedHandler);
port.open();

And then write your handler like:

```<code>private void dataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();

        Dispatcher.Invoke(
            delegate
        {
            textbox1.Text = indata;
        });
    }
</code>```

Also your button click could be like this:

```<code>private void button1_click(object sender, RoutedEventArgs e)
    {
        try {
            port.Write("A");
        }
        catch (Exception ex)
        {
            textbox.Text = " Send Failed !";
        }
    }
</code>```

Title: arduino write and reading

Body:
I am working with C# and arduino. I am still a newbie on this. I wish someone can help me. So my project is to send some code to Arduino. Then apply delay on Arduino and send back some string/char back to C#. I gave a textbox on C# to show the result of reading. This is my code:
C# code

Public form1()
{
    initializeComponent();
    Serialport1.Open();
}

public void Read()
{
    while (Serialport1.IsOpen)
    {
        try
        {
            string message = SerialPort1.ReadLine();
            textbox1.text = message;
        }
        catch (timeoutException)
        {
        }
    }
}
private void button1_click(object sender, eventargs e)
{
    SerialPort1.write("A");
    read();
}

arduino code:

int data;
void setup()
{
    Serial.begin(9600);
    Serial.print("START\n");
}

void loop()
{
    if(Serial.available())
    {
        data = Serial.read();
        if(data=='A')
        {
            delay(3000);
            Serial.print("B");
        }
    }
}

What I wish is textbox result write B, but nothing is come and the textbox keep blank. What did I do wrong? I hope someone can explain to me. Thank you

Body:
You Should attach a listener to the port like this:

SerialPort port = new SerialPort("COM4", 9600);
port.DataReceived += new SerialDataReceivedEventHandler(dataReceivedHandler);
port.open();

And then write your handler like:

private void dataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();

        Dispatcher.Invoke(
            delegate
        {
            textbox1.Text = indata;
        });
    }

Also your button click could be like this:

private void button1_click(object sender, RoutedEventArgs e)
    {
        try {
            port.Write("A");
        }
        catch (Exception ex)
        {
            textbox.Text = " Send Failed !";
        }
    }


问:
The import javax.servlet.ServletRegistration cannot be resolved
I use Spring Tool Suite 3.8.1.RELEASE to create a Spring project integrating Hibernate. I follow the tutorial in this site. When I tried to create the class mentioned at the first step 1. Bootstrapping Spring Dispatcher Servlet then I got an error saying The import javax.servlet.ServletRegistration cannot be resolved. Here is the pom.xml :

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.ambre</groupId>
    <artifactId>hib</artifactId>
    <name>SpringMvcHibernateJavaBased</name>
    <packaging>war</packaging>
    <version>1.0.0-BUILD-SNAPSHOT</version>
    <properties>
        <java-version>1.7</java-version>
        <org.springframework-version>4.0.3.RELEASE</org.springframework-version>
        <org.aspectj-version>1.6.10</org.aspectj-version>
        <org.slf4j-version>1.6.6</org.slf4j-version>
    </properties>
    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework-version}</version>
            <exclusions>
                <!-- Exclude Commons Logging in favor of SLF4j -->
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                 </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${org.springframework-version}</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.5.Final</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>2.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
        </dependency>

        <!-- AspectJ -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${org.aspectj-version}</version>
        </dependency>

        <!-- Logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${org.slf4j-version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.15</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.mail</groupId>
                    <artifactId>mail</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.jms</groupId>
                    <artifactId>jms</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jdmk</groupId>
                    <artifactId>jmxtools</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jmx</groupId>
                    <artifactId>jmxri</artifactId>
                </exclusion>
            </exclusions>
            <scope>runtime</scope>
        </dependency>

        <!-- @Inject -->
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>

        <!-- Servlet -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- Test -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.7</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

So why is the import impossible and how to fix it ?

答:
If this is only for the error reported - where it is unable to resolve and find class ServletRegistration or any other class from javax.serlvlet package the updated version of the dependency i.e. 3.x is all what is required</p>

```<code><dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
</dependency>
</code>```

Body:
I use Spring Tool Suite 3.8.1.RELEASE to create a Spring project integrating Hibernate. I follow the tutorial in this site. When I tried to create the class mentioned at the first step 1. Bootstrapping Spring Dispatcher Servlet then I got an error saying The import javax.servlet.ServletRegistration cannot be resolved. Here is the pom.xml :

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.ambre</groupId>
    <artifactId>hib</artifactId>
    <name>SpringMvcHibernateJavaBased</name>
    <packaging>war</packaging>
    <version>1.0.0-BUILD-SNAPSHOT</version>
    <properties>
        <java-version>1.7</java-version>
        <org.springframework-version>4.0.3.RELEASE</org.springframework-version>
        <org.aspectj-version>1.6.10</org.aspectj-version>
        <org.slf4j-version>1.6.6</org.slf4j-version>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework-version}</version>
            <exclusions>

                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                 </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${org.springframework-version}</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.5.Final</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>2.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${org.aspectj-version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${org.slf4j-version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.15</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.mail</groupId>
                    <artifactId>mail</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.jms</groupId>
                    <artifactId>jms</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jdmk</groupId>
                    <artifactId>jmxtools</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jmx</groupId>
                    <artifactId>jmxri</artifactId>
                </exclusion>
            </exclusions>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.7</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

So why is the import impossible and how to fix it ?

Body:
If this is only for the error reported - where it is unable to resolve and find class ServletRegistration or any other class from javax.serlvlet package the updated version of the dependency i.e. 3.x is all what is required

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
</dependency>


问:
Excel Help - creating tables from data sets
I'm trying to create a table from a list which has the following components, to show how many users within a company have completed a course within a date

Please see image for how the data set looks:

So for example, Dave A has completed 2 courses in Jan-17 for the same company, but I'm struggling to calculate this in one formula as the data set is very large. there's over 40 training courses and numerous users within each company.

Any help would be appreciated!

答:
Pivot table (as suggested by pnuts) would be best in my opinion; however, if you need a formula try COUNTIFS:

```<code>=COUNTIFS(A:A,A2,C:C,C2,D:D,D2)
</code>```

Per your data:

It checks all of the A column (name range) and compares it to cell A2

It checks all of the C column (company range) and compares it to cell C2

It checks all of the D column (complete date range) and compares it to cell D2

If all three criteria are equal it will add 1 to the count.

You can make a list of the names in the list and put this formula in for all of them using whatever cell their name first appears as the criteria (compare cell).

Body:
Pivot table (as suggested by pnuts) would be best in my opinion; however, if you need a formula try COUNTIFS:

=COUNTIFS(A:A,A2,C:C,C2,D:D,D2)

Per your data:

It checks all of the A column (name range) and compares it to cell A2

It checks all of the C column (company range) and compares it to cell C2

It checks all of the D column (complete date range) and compares it to cell D2

If all three criteria are equal it will add 1 to the count.

You can make a list of the names in the list and put this formula in for all of them using whatever cell their name first appears as the criteria (compare cell).


问:
SVG getBBox function returns zero in FireFox & Edge (but not in Chrome)
I have an svg element (created with D3).

while in chrome the "getBBox" function works fabulously, it fails in fireFox and Edge. Thought I saw this discussion in couple of places(e.g. here, here) none of them yielded a clear answer.

This doesn't work either - getBoundingClientRect()
And my element is not underneath  (i saw that it might cause issues).

Thanks alot!

答:
Ok, i found what was wrong.

Chrome can handle "g" elements with "display : none". but Firefox and edge treat it as "non-existing/zero dimensions".

sorry for the fuss.


问:
Regular expression - delimiter problem in PHP
I'm trying to extract src attributes from: [attname src="http://example.org"] somecontent [attname src="http://www.example.com"]

What I have now:

preg_match_all('#attname src=".*[^"]#', $buffer, $bufferarr);

However it doesn't work - there's no stop after second ", what results in: attname src="http://example.org"] somecontent [attname src="http://www.example.com

答:
By default, + and * are "greedy" - they gobble up as many characters as they can. That's why you get more than you want. If you add ? to them (+? and *?) they will be non-greedy and will stop as soon as they can.

You regexp also looks wrong. It should be something like #attname src="[^"]*?"#.


问:
How can i achieve img coming out from border. email templates?
http://imgur.com/a/fKv2H

I need banner with height 100px. and img inside it with height 120px. So  the picture comeee out my banner for 20px;
Its for emails.
Also i need text column right before picture, so that text in column with background f4f4f4

```<code><table>
   <tr>
      <td>
         <img src="" style="margin-top:-20px;" />
      </td>
      <td>
        banner text here
      </td>
   </tr>
</table>
</code>```

答:
I added colors so you could see that it was outside the table. I gave the image a height of 120px, width of auto. Made the td's have a max-height of 100px; And I left your -20px margin on the image.

        banner text here

```

Body:
http://imgur.com/a/fKv2H

I need banner with height 100px. and img inside it with height 120px. So  the picture comeee out my banner for 20px;
Its for emails.
Also i need text column right before picture, so that text in column with background f4f4f4

        banner text here

Body:
I added colors so you could see that it was outside the table. I gave the image a height of 120px, width of auto. Made the td's have a max-height of 100px; And I left your -20px margin on the image.

<body style="background-color:pink">
<table style="background-color:orange;">
   <tr>
      <td style="max-height:100px; overflow-y:initial;">
         <img src="https://i.imgur.com/ZESO4DT.png" style="margin-top:-20px; height:120px; width:auto;" />
      </td>
      <td style="max-height:100px;overflow-y:initial;">
        banner text here
      </td>
   </tr>
</table>
</body>


问:
How can I print to the clipboard in OS X?
OS X has useful PDF workflow functions such as "Mail PDF" and "Save as PDF...". I often need to attach a PDF export of a document to an existing draft mail message or other document. In these cases "Mail PDF" doesn't work as it creates a new blank mail message each time.

The way I do this currently is to save the document as a PDF and then attach the intermediate file. I would like to achieve the same without dealing with the intermediate file.

I would like a workflow that allows me to print the current document as PDF and copy it to the clipboard.

I tried to create a workflow using Automator and pbcopy, but pbcopy can't be told that the stream of bytes is of type PDF.

答:
Graphic Clipboard (from snip taken with shift-control-command-4 in macOs Sierra):

Open Preview and

Edit>New from Clipboard (or just command N).  Voilá - it appears in Preview

Save or Print from Preview

Text Clipboard (taken from highlighting and command-c)

Open Pages, the macOs word processor

Open a Blank Document

Paste in your clipboard (command-v)

Save or print


问:
Redirect inside a component in React with react-router 3
How to do a route redirect in React component with react router 3 ?

If I user a 'guard' component like this:

```<code>const GuardContainer = (props) => {

    const {ok} = isOk(props)

    if (!ok) {
        // Redirect here  to /not-ok
        return null
    }

    return <WrappedComponent {...props}/>
}
</code>```

then React complains about changing state with

Cannot update during an existing state transition (such as within
  render or another component's constructor).

答:
In React Router V4 there is a <Redirect /> component that allows you to render and it will navigate to the target. You can probably make your own in V3 using browserHistory:

```<code>import React from 'react';
import { browserHistory } from 'react-router';

class Redirect extends React.Component {

  componentDidMount() {
    browserHistory.push(this.props.to);
  }

  render() {
    return <div />
  }

}

export default Redirect;
</code>```

Then render it with to="/not-ok"

```<code>if (!ok) {
  return <Redirect to="/not-ok" />;
}
</code>```

Give this a try or something similar to it.

Body:
How to do a route redirect in React component with react router 3 ?

If I user a 'guard' component like this:

const GuardContainer = (props) => {

    const {ok} = isOk(props)

    if (!ok) {
        // Redirect here  to /not-ok
        return null
    }

    return <WrappedComponent {...props}/>
}

then React complains about changing state with

Cannot update during an existing state transition (such as within
  render or another component's constructor).

Body:
In React Router V4 there is a <Redirect /> component that allows you to render and it will navigate to the target. You can probably make your own in V3 using browserHistory:

import React from 'react';
import { browserHistory } from 'react-router';

class Redirect extends React.Component {

  componentDidMount() {
    browserHistory.push(this.props.to);
  }

  render() {
    return <div />
  }

}

export default Redirect;

Then render it with to="/not-ok"

if (!ok) {
  return <Redirect to="/not-ok" />;
}

Give this a try or something similar to it.


问:
Microsoft.WebApplication.targets was not found, on the build server. What's your solution?
Trying to build my project on the build server gives me the following error:

```<code>Microsoft (R) Build Engine Version 4.0.30319.1
error MSB4019: The imported project "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\TeamData\Microsoft.Data.Schema.SqlTasks.targets" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.
error MSB4019: The imported project "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.
error MSB4019: The imported project "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.
</code>```

I solved this problem a few months ago, with installing Visual Studio 2010 on the Build Server. But now I'm setup a new server from scratch, and I want to know if there any better solution to solve this issue.

答:
It seems the new version of msbuild does not ship with Microsoft.WebApplication.targets. To fix you need to update your csproj file as so:

1) Edit the web app csproj (right click). Find the section in the csproj towards the bottom concerning build tools. It should look like so.

```<code><PropertyGroup>
  <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
</PropertyGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" />
</code>```

2) You need to add one VSToolsPath line below the VisualStudioVersion tag so it looks like so

```<code><PropertyGroup>
  <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
  <!--Add the below line to fix the project loading in VS 2017 -->
  <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
  <!--End -->
</PropertyGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" />
</code>```

Reference link:
https://alastaircrabtree.com/cannot-open-vs-2015-web-project-in-vs-2017/

Body:
Trying to build my project on the build server gives me the following error:

Microsoft (R) Build Engine Version 4.0.30319.1
error MSB4019: The imported project "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\TeamData\Microsoft.Data.Schema.SqlTasks.targets" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.
error MSB4019: The imported project "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.
error MSB4019: The imported project "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.

I solved this problem a few months ago, with installing Visual Studio 2010 on the Build Server. But now I'm setup a new server from scratch, and I want to know if there any better solution to solve this issue.

Body:
It seems the new version of msbuild does not ship with Microsoft.WebApplication.targets. To fix you need to update your csproj file as so:

1) Edit the web app csproj (right click). Find the section in the csproj towards the bottom concerning build tools. It should look like so.

<PropertyGroup>
  <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
</PropertyGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" />

2) You need to add one VSToolsPath line below the VisualStudioVersion tag so it looks like so

<PropertyGroup>
  <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
  <!--Add the below line to fix the project loading in VS 2017 -->
  <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
  <!--End -->
</PropertyGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" />

Reference link:
https://alastaircrabtree.com/cannot-open-vs-2015-web-project-in-vs-2017/


问:
Java array initialization within argument list
How come the first call to someMethod doesn't compile without being explicit that it's String[]?

It's fine to use an array initializer to create a String[] array but you can't use it to pass an argument.  Are the curly braces used in some other fashion for passing arguments that derails how I'd expect this to behave?

```<code>public void someMethod(String[] arr){
    //do some magic
}

public void makeSomeMagic(){

    String[] arr = {"cat", "fish", "cow"};

    //Does not compile!
    someMethod({"cat", "fish", "cow"});

    //This compiles!
    someMethod(new String[]{"cat", "fish", "cow"});

    //This compiles!
    someMethod(arr);
}
</code>```

The compiler error is the following:

The method someMethod(String[]) in the type Moo is not applicable for the arguments (String, String, String)

答:
You can only use the { "hello", "world" } initialization notation when declaring an array variable or in an array creation expression such as new String[] { ... }.

See Section 10.6 Array Initializers in the Java Language Specification:

An array initializer may be specified in a declaration, or as part of an array creation expression (§15.10), creating an array and providing some initial values

Body:
How come the first call to someMethod doesn't compile without being explicit that it's String[]?

It's fine to use an array initializer to create a String[] array but you can't use it to pass an argument.  Are the curly braces used in some other fashion for passing arguments that derails how I'd expect this to behave?

public void someMethod(String[] arr){
    //do some magic
}

public void makeSomeMagic(){

    String[] arr = {"cat", "fish", "cow"};

    //Does not compile!
    someMethod({"cat", "fish", "cow"});

    //This compiles!
    someMethod(new String[]{"cat", "fish", "cow"});

    //This compiles!
    someMethod(arr);
}

The compiler error is the following:

The method someMethod(String[]) in the type Moo is not applicable for the arguments (String, String, String)


问:
Python - Set file EOF
Say, for some reason, I have a 1 TB file. In Python, if I wanted to add 10 bytes, I could just seek to the end, and write a 10 byte string. However, say I'd like to cut 10 bytes off the end of it. Obviously, it would take a ridiculous amount of time (and there may not even be HDD space) to copy this file without the excess 10 bytes, then delete the old one.

In c++ for Windows, there's a function, SetEndOfFile, that lets me change file size to something smaller without file rewriting.

Is there a similar function in python that will do this? I've researched and cannot find anything...

答:
Wow, I guess I hadn't looked hard enough: truncate

```
f = open(fname)
f.seek(-10,2) # jump 10 bytes before end
f.truncate() # truncate it!!
f.close()
```

Title: Python - Set file EOF

Body:
Wow, I guess I hadn't looked hard enough: truncate

f = open(fname)
f.seek(-10,2) # jump 10 bytes before end
f.truncate() # truncate it!!
f.close()


问:
Good OO practice + Should we implement complicated logic in subclasses for sake of OO?
I have an Employee classified into two ( domestic and international ).
I have another class Refund, which is used to refund employees.
I have a class called Bank account used by Refund class to Refund.

Now my immediate design looks like this:

Employee interface, with 2 sub-types domestic and international.

Refund class takes in Bank in constructor.

A rough pseudocode of Refund class

```<code>Class Refund

    Refund( bank account )

   Public class Refund( employee ) {

         If (employee is domestic) {
             Pay to bank
             Account for taxes
        } else {
           do currency conversion
           Pay to bank
           Call some 3rd party to do taxation
       }
    }
}
</code>```

Now here is my question:

How can I replace Refund class with object oriented design, which is extensible and I don’t need to use if-else ?

Immediate option is to shift refund functionality into Employee class and individual subtypes can then do their own logic for refund. BUT-  does it make sense to complicate employee class with Refund logic ( which deservers its own modular class given it’s complex functions ) ?

答:
After I briefly read your question, I think double dispatch is what you seek.
See e. g. https://sourcemaking.com/design_patterns/visitor/java/2</p>

Body:
I have an Employee classified into two ( domestic and international ).
I have another class Refund, which is used to refund employees.
I have a class called Bank account used by Refund class to Refund.

Now my immediate design looks like this:

Employee interface, with 2 sub-types domestic and international.

Refund class takes in Bank in constructor.

A rough pseudocode of Refund class

Class Refund

    Refund( bank account )

   Public class Refund( employee ) {

         If (employee is domestic) {
             Pay to bank
             Account for taxes
        } else {
           do currency conversion
           Pay to bank
           Call some 3rd party to do taxation
       }
    }
}

Now here is my question:

How can I replace Refund class with object oriented design, which is extensible and I don’t need to use if-else ?

Immediate option is to shift refund functionality into Employee class and individual subtypes can then do their own logic for refund. BUT-  does it make sense to complicate employee class with Refund logic ( which deservers its own modular class given it’s complex functions ) ?


问:
ASP.NET MVC background image
i'm a newbie in ASP.NET MVC. I'm trying to make a decent site, and i've encountered a stupid problem:
I can't set the background to be a local image.

-in Site.css, this works :

```<code>body {
padding-top: 50px;
padding-bottom: 20px;
background-image: url(http://wallpapercave.com/wp/zJj7EIt.jpg);
}
</code>```

,but i don't want the image be an URL.

I've tried the following things:

Number one :

```<code>body {
padding-top: 50px;
padding-bottom: 20px;
background-image:
url( C:\Users\alexh\Documents\GitHub\StupidASP.NET\StupidASP.NET\StupidASP.NET\Styles\Images\background.jpg)
}
</code>```

Number two :

```<code><body style="background-image:
url( C:\Users\alexh\Documents\GitHub\StupidASP.NET\StupidASP.NET\StupidASP.NET\Styles\Images\background.jpg)">
</code>```

Number three(wich is obsolete):

```<code><body background="C:\Users\alexh\Documents\GitHub\StupidASP.NET\StupidASP.NET\StupidASP.NET\Styles\Images\background.jpg">
</code>```

I must miss something related to resources, and not with properties. Do you have any solution or ideea ? Or an explication about what vs does.

答:
Here, the problem is it's not picking the exact file mentioned in the url(), so just try the below scenario.

Create a folder with name Images inside your project folder and then copy all the images into it.

then your css should be

```<code>background-image: url('Images/imageFile.png');
</code>```

this url location means from the root of your project there should be one folder with name Images and inside it there should be the mentioned image file.

Title: ASP.NET MVC background image

Body:
i'm a newbie in ASP.NET MVC. I'm trying to make a decent site, and i've encountered a stupid problem:
I can't set the background to be a local image.

-in Site.css, this works :

body {
padding-top: 50px;
padding-bottom: 20px;
background-image: url(http://wallpapercave.com/wp/zJj7EIt.jpg);
}

,but i don't want the image be an URL.

I've tried the following things:

Number one :

body {
padding-top: 50px;
padding-bottom: 20px;
background-image:
url( C:\Users\alexh\Documents\GitHub\StupidASP.NET\StupidASP.NET\StupidASP.NET\Styles\Images\background.jpg)
}

Number two :

Number three(wich is obsolete):

I must miss something related to resources, and not with properties. Do you have any solution or ideea ? Or an explication about what vs does.

Body:
Here, the problem is it's not picking the exact file mentioned in the url(), so just try the below scenario.

Create a folder with name Images inside your project folder and then copy all the images into it.

then your css should be

background-image: url('Images/imageFile.png');

this url location means from the root of your project there should be one folder with name Images and inside it there should be the mentioned image file.


问:
Connection refused thrown when instantiating a new chrome driver
I have a selenium project with cucumber on my local Jenkins server.

```<code>        DesiredCapabilities capability = DesiredCapabilities.chrome();
        try {
            baseUtil.driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
</code>```

This is how i instantiate my driver. I have the chrome plugin on jenkins as well.

When i try to build, i get this error:

org.openqa.selenium.remote.UnreachableBrowserException: Could not
  start a new session. Possible causes are invalid address of the remote
  server or browser start-up failure.

....

Caused by: org.apache.http.conn.HttpHostConnectException: Connect to
  localhost:4444 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1]
  failed: Connection refused

Any idea what am i doing wrong?

答:
If you are running locally try switching to chromedriver

```<code>DesiredCapabilities capability = DesiredCapabilities.chrome();
try {
baseUtil.driver = new ChromeDriver(capability));
} catch (MalformedURLException e) { e.printStackTrace(); }
</code>```

the URL in your previous call was set to point to the hub which you aren't using.
you might need to point it at the local driver location such as:

```<code>System.setProperty("webdriver.chrome.driver", "<pathtoyourchromedriver>/chromedriver.exe");
</code>```

Body:
I have a selenium project with cucumber on my local Jenkins server.

        DesiredCapabilities capability = DesiredCapabilities.chrome();
        try {
            baseUtil.driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

This is how i instantiate my driver. I have the chrome plugin on jenkins as well.

When i try to build, i get this error:

org.openqa.selenium.remote.UnreachableBrowserException: Could not
  start a new session. Possible causes are invalid address of the remote
  server or browser start-up failure.

....

Caused by: org.apache.http.conn.HttpHostConnectException: Connect to
  localhost:4444 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1]
  failed: Connection refused

Any idea what am i doing wrong?

Body:
If you are running locally try switching to chromedriver

DesiredCapabilities capability = DesiredCapabilities.chrome();
try {
baseUtil.driver = new ChromeDriver(capability));
} catch (MalformedURLException e) { e.printStackTrace(); }

the URL in your previous call was set to point to the hub which you aren't using.
you might need to point it at the local driver location such as:

System.setProperty("webdriver.chrome.driver", "<pathtoyourchromedriver>/chromedriver.exe");


问:
Reset button not updating value in AngularJS
I'm pulling blanks on this, it looks like it should work, but...

I have a button:

```<code> <button class="btn btn-warning" type="reset" ng-click="reset()">Clear </button>
</code>```

Condensed version of reset function:

```<code>  $scope.reset = function() {
        $scope.application = {};
        $scope.PostDataResponse = null;
        $scope.errors = null;
        $scope.selectedApplication = null;
        $scope.application.status = true;
        $scope.application.version = 1.0;
        $scope.gridOptions.data.length = 0;
        $scope.ApplicationSettingsForm.$setPristine();
        $scope.ApplicationSettingsForm.$setUntouched();
    };
</code>```

Input I'm trying to reset:

```<code><input type="number" style="font-family: sans-serif" class="form-control" ng-model="application.version" ng-disabled="true" id="Version" name="Version" placeholder="Version..." required>
</code>```

How it seeds when the page is first loaded:

```<code>    $scope.application = {};
    $scope.application.version = 1.0;
</code>```

When the page loads I get a 1 in there, but when I click reset, it reverts to Version... instead of the expected 1.  What am I doing wrong here?

答:
Some of the lines of code in your reset() function, might be throwing exceptions. Most probably it is likely to be $scope.gridOptions.data.length = 0; If this is not the case, please check the console to see if any other lines are throwing any exceptions.

If some lines in your reset() function throw exceptions, it is likely that the application object's version did not get set properly.

Can you try changing your code to this? I added some null checks, hoping to avoid any exceptions:

```<code>  $scope.reset = function() {
        $scope.application = {};
        $scope.application.status = true;
        $scope.application.version = 1.0;
        $scope.PostDataResponse = null;
        $scope.errors = null;
        $scope.selectedApplication = null;
        if($scope.gridOptions && $scope.gridOptions.data) {
             $scope.gridOptions.data.length = 0;
        }
        if($scope.ApplicationSettingsForm) {
          $scope.ApplicationSettingsForm.$setPristine();
          $scope.ApplicationSettingsForm.$setUntouched();
        }
    };
</code>```

Body:
I'm pulling blanks on this, it looks like it should work, but...

I have a button:

 <button class="btn btn-warning" type="reset" ng-click="reset()">Clear </button>

Condensed version of reset function:

  $scope.reset = function() {
        $scope.application = {};
        $scope.PostDataResponse = null;
        $scope.errors = null;
        $scope.selectedApplication = null;
        $scope.application.status = true;
        $scope.application.version = 1.0;
        $scope.gridOptions.data.length = 0;
        $scope.ApplicationSettingsForm.$setPristine();
        $scope.ApplicationSettingsForm.$setUntouched();
    };

Input I'm trying to reset:

<input type="number" style="font-family: sans-serif" class="form-control" ng-model="application.version" ng-disabled="true" id="Version" name="Version" placeholder="Version..." required>

How it seeds when the page is first loaded:

    $scope.application = {};
    $scope.application.version = 1.0;

When the page loads I get a 1 in there, but when I click reset, it reverts to Version... instead of the expected 1.  What am I doing wrong here?

Body:
Some of the lines of code in your reset() function, might be throwing exceptions. Most probably it is likely to be $scope.gridOptions.data.length = 0; If this is not the case, please check the console to see if any other lines are throwing any exceptions.

If some lines in your reset() function throw exceptions, it is likely that the application object's version did not get set properly.

Can you try changing your code to this? I added some null checks, hoping to avoid any exceptions:

  $scope.reset = function() {
        $scope.application = {};
        $scope.application.status = true;
        $scope.application.version = 1.0;
        $scope.PostDataResponse = null;
        $scope.errors = null;
        $scope.selectedApplication = null;
        if($scope.gridOptions && $scope.gridOptions.data) {
             $scope.gridOptions.data.length = 0;
        }
        if($scope.ApplicationSettingsForm) {
          $scope.ApplicationSettingsForm.$setPristine();
          $scope.ApplicationSettingsForm.$setUntouched();
        }
    };


问:
Error in Android Tab Tutorial
Ive been trying to fix this for ages, on the tab tutorial for android ive followed it exactly but keep getting this error messege on my TabWidget.java class.

R.drawable.ic_tab_albums cannot be resolved

  tabWidget.java/HelloTabWidget/src/com/example/tabwidget

and

R.drawable.ic_tab_songs cannot be resolved

  tabWidget.java/HelloTabWidget/src/com/example/tabwidget

Heres my code for my TabWidget.java class

`

     import com.example.androidtab.R;

```<code> import android.app.Activity;
 import android.content.Intent;
 import android.content.res.Resources;
 import android.os.Bundle;
 import android.widget.TabHost;

public class TabWidget extends Activity {
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Resources res = getResources(); // Resource object to get Drawables
    TabHost tabHost = getTabHost();  // The activity TabHost
    TabHost.TabSpec spec;  // Resusable TabSpec for each tab
    Intent intent;  // Reusable Intent for each tab

    // Create an Intent to launch an Activity for the tab (to be reused)
    intent = new Intent().setClass(this, ArtistsActivity.class);

    // Initialize a TabSpec for each tab and add it to the TabHost
    spec = tabHost.newTabSpec("artists").setIndicator("Artists",
                      res.getDrawable(R.drawable.ic_tab_artists))
                  .setContent(intent);
    tabHost.addTab(spec);

    // Do the same for the other tabs
    intent = new Intent().setClass(this, AlbumsActivity.class);
    spec = tabHost.newTabSpec("albums").setIndicator("Albums",
                      res.getDrawable(R.drawable.ic_tab_albums))
                  .setContent(intent);
    tabHost.addTab(spec);

    intent = new Intent().setClass(this, SongsActivity.class);
    spec = tabHost.newTabSpec("songs").setIndicator("Songs",
                      res.getDrawable(R.drawable.ic_tab_songs))
                  .setContent(intent);
    tabHost.addTab(spec);

    tabHost.setCurrentTab(2);
}

private TabHost getTabHost() {
    // TODO Auto-generated method stub
    return null;
}
</code>```

}`

答:
That is covered in step #3 of the tutorial.

"You need an icon for each of your tabs. For each icon, you should create two versions: one for when the tab is selected and one for when it is unselected."

You only created an icon for one, not for all three.

Admittedly, this step is pretty poorly written.

Title: Error in Android Tab Tutorial

Body:
Ive been trying to fix this for ages, on the tab tutorial for android ive followed it exactly but keep getting this error messege on my TabWidget.java class.

R.drawable.ic_tab_albums cannot be resolved

  tabWidget.java/HelloTabWidget/src/com/example/tabwidget

and

R.drawable.ic_tab_songs cannot be resolved

  tabWidget.java/HelloTabWidget/src/com/example/tabwidget

Heres my code for my TabWidget.java class

`

     import com.example.androidtab.R;

 import android.app.Activity;
 import android.content.Intent;
 import android.content.res.Resources;
 import android.os.Bundle;
 import android.widget.TabHost;

public class TabWidget extends Activity {
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Resources res = getResources(); // Resource object to get Drawables
    TabHost tabHost = getTabHost();  // The activity TabHost
    TabHost.TabSpec spec;  // Resusable TabSpec for each tab
    Intent intent;  // Reusable Intent for each tab

    // Create an Intent to launch an Activity for the tab (to be reused)
    intent = new Intent().setClass(this, ArtistsActivity.class);

    // Initialize a TabSpec for each tab and add it to the TabHost
    spec = tabHost.newTabSpec("artists").setIndicator("Artists",
                      res.getDrawable(R.drawable.ic_tab_artists))
                  .setContent(intent);
    tabHost.addTab(spec);

    // Do the same for the other tabs
    intent = new Intent().setClass(this, AlbumsActivity.class);
    spec = tabHost.newTabSpec("albums").setIndicator("Albums",
                      res.getDrawable(R.drawable.ic_tab_albums))
                  .setContent(intent);
    tabHost.addTab(spec);

    intent = new Intent().setClass(this, SongsActivity.class);
    spec = tabHost.newTabSpec("songs").setIndicator("Songs",
                      res.getDrawable(R.drawable.ic_tab_songs))
                  .setContent(intent);
    tabHost.addTab(spec);

    tabHost.setCurrentTab(2);
}

private TabHost getTabHost() {
    // TODO Auto-generated method stub
    return null;
}

}`


问:
Copying 15 million records to a new table/server
Good day. I need to move 15 Million Records from one MySQL table to a new table on other schemas. This is a live system and time is a problem. The table I need to move is a history table and isn't important for day to day business. I can't leave the table as it is part of a bigger upgrade I am doing.

I tried just moving the data with basic sql in a test environment but this doesn't work; the server kicks me out after 20min.

What would be the best way of moving the data?

I am a C# programmer  if someone has a coding solution

答:
There are few options with which you can achieve it.

Creating linked server to move using T-SQL scripts.

Create a service file that will do the task for you.

SSIS is an option that you can explore.

Export/Import.


问:
2 Business Rules calling at the same time when incident created
I am facing an issue in servicenow Business rules. I have 2 business rules which has to trigger when

When an incident created

When specific fields of an incident updated

While creating an incident I'm setting some default values say State - closed, Urgency - Low. I am expecting that it should only trigger create incident business rule but it's triggering update incident business rule as well to set Urgency and State values.

答:
Are you using current.update() in your Business Rule that runs on insert? If so, that is probably triggering the second Business Rule to run.

Also, make sure your Business Rule is set as a before Business Rule instead of an after to help the flow if at all possible.

It's generally not necessary to call current.update() for a before Business Rule since these run before the actual insert happens.

Take a look at the best practices for Business Rules when you have some time https://hi.service-now.com/kb_view.do?sysparm_article=KB0540192

In particular this one may describe the behavior your are seeing.

Best Practice #2: Avoid using current.update() in before or after
  business rules.  Avoid using current.update() to prevent recursions
  that impact system performance. The current.update() triggers business
  rules to run on the same table for insert and update operations. In a
  before or after business rule, this can lead to the rule calling
  itself over and over again.

It is unnecessary to use current.update() in a before business rule
  since these are saved automatically when the database is updated.
  After business rules are not intended to update current objects, so
  this is also not needed.

Unless there is a special case, avoid using current.update()since it
  not only stops business rules, but it also prevents the workflow
  engine from running on the record.


问:
Export queries from SSMS to files - not the results but the query
I want to export all my queries as individual files for purposes of putting them into mercurial source control, but I don't know how to export the individual queries as individual files without having to open each one, then save to the folder, then add into the project, or some equally convoluted process.

I wouldn't mind having to add each one individually, but how do I get them out of the database as individual files without opening them all and doing each one save as? Ostensibly I would like them named with the name they have in the database right now.

I could easily dump the whole lot into one long file using database tasks, but that's not really super helpful is it?

I have SSMS 2k5 and 2k8 (and VS 2k5, 2k8, 2010 to boot) to work with, any thoughts?

答:
When you script a database in SSMS you have the option of one file per objects.

SMO is useful with a small app to iterate through

Third party tools like Red Gate SQL Compare (there are other free tools) can script too


问:
Component function works only on the first component Vue.js
I'm learning Vue.js and as exercise i'm developing a SPA. I recursively add some icon as imgs via components. (a lot of code has been omitted to focus on the problem)

Vue.js

```<code>Vue.component('icon', {
  template:
    '<img id="logo-icon" v-on:mouseover="animation"
     class="platform_button" width="50" height="50"
     src="../assets/img/logos/Android_icon.png" alt="img" />',

  methods: {
    animation: function(){
      animate("#logo-icon","animated bounce")
    }
  }
})

new Vue({
  el: '#apps'
})

...
</code>```

.html

```<code><div id="apps">
  ...
  <div v-for="(el, in) in x" style="width:50%">
    <icon></icon>
  </div>
  ...
</div>
</code>```

All images are shown properly. I want to start an animation on mouse hover the image. The function to animate works fine, problem is that regardless of which image I hover with the mouse, only the first one will bounce. E.g. if I'm on img1 with the mouse, img1 will bounce. If I'm on img5 with the mouse, img1 will bounce instead of img5.
How can I make animate only the image covered by mouse?

答:
As the commenters pointed out, since you are applying the animation to #logo-icon, and you have multiple copies of your component on the page, there are multiple img tags that match #logo-icon. As such the behavior of animate may affect just a single element (the first) or more than one, depending on implementation.

Instead, with Vue, you can just refer to the root element via this.$el. This is a reference to the single specific img element you want to animate.

```<code>Vue.component('icon', {
  template:
    '<img id="logo-icon" v-on:mouseover="animation"
     class="platform_button" width="50" height="50"
     src="../assets/img/logos/Android_icon.png" alt="img" />',

  methods: {
    animation: function(){
      animate(this.$el,"animated bounce")
    }
  }
})
</code>```

What this does is apply the animation to the root element of your component. In this case, the root element is your img. If you had more than one element in your component you would likely need to use a ref.

Body:
I'm learning Vue.js and as exercise i'm developing a SPA. I recursively add some icon as imgs via components. (a lot of code has been omitted to focus on the problem)

Vue.js

Vue.component('icon', {
  template:
    '',

  methods: {
    animation: function(){
      animate("#logo-icon","animated bounce")
    }
  }
})

new Vue({
  el: '#apps'
})

...

.html

  ...

    <icon></icon>

  ...

All images are shown properly. I want to start an animation on mouse hover the image. The function to animate works fine, problem is that regardless of which image I hover with the mouse, only the first one will bounce. E.g. if I'm on img1 with the mouse, img1 will bounce. If I'm on img5 with the mouse, img1 will bounce instead of img5.
How can I make animate only the image covered by mouse?

Body:
As the commenters pointed out, since you are applying the animation to #logo-icon, and you have multiple copies of your component on the page, there are multiple img tags that match #logo-icon. As such the behavior of animate may affect just a single element (the first) or more than one, depending on implementation.

Instead, with Vue, you can just refer to the root element via this.$el. This is a reference to the single specific img element you want to animate.

Vue.component('icon', {
  template:
    '<img id="logo-icon" v-on:mouseover="animation"
     class="platform_button" width="50" height="50"
     src="../assets/img/logos/Android_icon.png" alt="img" />',

  methods: {
    animation: function(){
      animate(this.$el,"animated bounce")
    }
  }
})

What this does is apply the animation to the root element of your component. In this case, the root element is your img. If you had more than one element in your component you would likely need to use a ref.


问:
How to run a macro in sheet1 from sheet2
I can't figure out what to change to be able to run this macro from another sheet. Any idea ?

This macro is stored in sheet "Mail"

I want to run the macro from Sheet2 via a button

Is it possible or do I have to change the macro fundamentally?

```<code>    Sub DynamicRange()
    'Find the last row in the range then make the slection
    '-----------------------------------------------------------------------
    Dim sht As Worksheet
    Dim LastRow As Long
    Dim LastColumn As Long
    Dim StartCell As Range
    Dim Sendrng As Range
    Dim strbody As String

    '----------------------------------------------------------------
    If IsEmpty(Range("B26").Value) = True Then
    ThisWorkbook.Sheets("Mail").Range("B2:K26").Select
    Else
    '----------------------------------------------------------------

    Set sht = Worksheets("Mail")
    Set StartCell = Range("B2")

    'Refresh UsedRange
    Worksheets("Mail").UsedRange

    'Find Last Row
    LastRow = sht.Cells.Find("*", SearchOrder:=xlByRows,
    SearchDirection:=xlPrevious).Row

    'Select Range
    sht.Range("B2:K" & LastRow).Select

    End If

    '-----------------------------------------------------
    'Mail codes starts here
    On Error GoTo StopMacro

    With Application
    .ScreenUpdating = False
    .EnableEvents = False
    End With

    'Note: if the selection is one cell it will send the whole worksheet
     Set Sendrng = Selection

    'Create the mail and send it
    With Sendrng

    ActiveWorkbook.EnvelopeVisible = True
    With .Parent.MailEnvelope

        With .Item
            .To = "here@myour.mail"
            .CC = ""
            .BCC = ""
            .Subject = ThisWorkbook.Sheets("Mail").Range("O4").Value
            .Importance = 2
            .ReadReceiptRequested = True
            .Send
        End With

    End With
    End With

    StopMacro:
    With Application
    .ScreenUpdating = True
    .EnableEvents = True
    End With
    ActiveWorkbook.EnvelopeVisible = False

    End Sub
</code>```

答:
Explanation

Always specify a Range() or Cells() with a worksheet like sht.Range().

Of course sht has to be set to your desired worksheet first:

```<code>Set sht = ThisWorkbook.Worksheets("Mail")
</code>```

Also try to avoid .Select instead set the desired range to a variable Set SendRng = sht.Range("B2:K26") and use this later.

Apparently MailEnvelope really sends the selected range from the active sheet :( so this time we have a real use case for .Select and .Activate where we cannot avoid it (at least I didn't find one).

This way your code gets independent from the active worksheet and any selection, so you can run it whatever sheet or cell is selected.

I tidied up your code a bit. Save this into a module and it should run from any worksheet.

Note: I removed unused variables.

```<code>Option Explicit

Sub DynamicRange()
    Dim sht As Worksheet, actSht As Worksheet
    Dim LastRow As Long
    Dim SendRng As Range

    Set sht = ThisWorkbook.Worksheets("Mail")

    'Find the last row in the range then make the slection
    '-----------------------------------------------------------------------
    If IsEmpty(sht.Range("B26").Value) = True Then
        Set SendRng = sht.Range("B2:K26")
    Else
        'Find Last Row
        LastRow = sht.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

        'Select Range
        Set SendRng = sht.Range("B2:K" & LastRow)
    End If

    '-----------------------------------------------------
    'Mail codes starts here
    On Error GoTo StopMacro

    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With
    Set actSht = ActiveSheet 'remember active sheet

    'Create the mail and send it
    With SendRng
        .Parent.Activate 'we need to activate the mail sheet
        .Select 'we need to select the range which should be in the email

        ActiveWorkbook.EnvelopeVisible = True
        With .Parent.MailEnvelope.Item
            .To = "here@myour.mail"
            .CC = ""
            .BCC = ""
            .Subject = sht.Range("O4").Value
            .Importance = 2
            .ReadReceiptRequested = True
            .Send
        End With
    End With

StopMacro:
    actSht.Select 'jump back to the sheet we came from
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With
    ActiveWorkbook.EnvelopeVisible = False
End Sub
</code>```

Body:
I can't figure out what to change to be able to run this macro from another sheet. Any idea ?

This macro is stored in sheet "Mail"

I want to run the macro from Sheet2 via a button

Is it possible or do I have to change the macro fundamentally?

    Sub DynamicRange()
    'Find the last row in the range then make the slection
    '-----------------------------------------------------------------------
    Dim sht As Worksheet
    Dim LastRow As Long
    Dim LastColumn As Long
    Dim StartCell As Range
    Dim Sendrng As Range
    Dim strbody As String

    '----------------------------------------------------------------
    If IsEmpty(Range("B26").Value) = True Then
    ThisWorkbook.Sheets("Mail").Range("B2:K26").Select
    Else
    '----------------------------------------------------------------

    Set sht = Worksheets("Mail")
    Set StartCell = Range("B2")

    'Refresh UsedRange
    Worksheets("Mail").UsedRange

    'Find Last Row
    LastRow = sht.Cells.Find("*", SearchOrder:=xlByRows,
    SearchDirection:=xlPrevious).Row

    'Select Range
    sht.Range("B2:K" & LastRow).Select

    End If

    '-----------------------------------------------------
    'Mail codes starts here
    On Error GoTo StopMacro

    With Application
    .ScreenUpdating = False
    .EnableEvents = False
    End With

    'Note: if the selection is one cell it will send the whole worksheet
     Set Sendrng = Selection

    'Create the mail and send it
    With Sendrng

    ActiveWorkbook.EnvelopeVisible = True
    With .Parent.MailEnvelope

        With .Item
            .To = "here@myour.mail"
            .CC = ""
            .BCC = ""
            .Subject = ThisWorkbook.Sheets("Mail").Range("O4").Value
            .Importance = 2
            .ReadReceiptRequested = True
            .Send
        End With

    End With
    End With

    StopMacro:
    With Application
    .ScreenUpdating = True
    .EnableEvents = True
    End With
    ActiveWorkbook.EnvelopeVisible = False

    End Sub

Body:
Explanation

Always specify a Range() or Cells() with a worksheet like sht.Range().

Of course sht has to be set to your desired worksheet first:

Set sht = ThisWorkbook.Worksheets("Mail")

Also try to avoid .Select instead set the desired range to a variable Set SendRng = sht.Range("B2:K26") and use this later.

Apparently MailEnvelope really sends the selected range from the active sheet :( so this time we have a real use case for .Select and .Activate where we cannot avoid it (at least I didn't find one).

This way your code gets independent from the active worksheet and any selection, so you can run it whatever sheet or cell is selected.

I tidied up your code a bit. Save this into a module and it should run from any worksheet.

Note: I removed unused variables.

Option Explicit

Sub DynamicRange()
    Dim sht As Worksheet, actSht As Worksheet
    Dim LastRow As Long
    Dim SendRng As Range

    Set sht = ThisWorkbook.Worksheets("Mail")

    'Find the last row in the range then make the slection
    '-----------------------------------------------------------------------
    If IsEmpty(sht.Range("B26").Value) = True Then
        Set SendRng = sht.Range("B2:K26")
    Else
        'Find Last Row
        LastRow = sht.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

        'Select Range
        Set SendRng = sht.Range("B2:K" & LastRow)
    End If

    '-----------------------------------------------------
    'Mail codes starts here
    On Error GoTo StopMacro

    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With
    Set actSht = ActiveSheet 'remember active sheet

    'Create the mail and send it
    With SendRng
        .Parent.Activate 'we need to activate the mail sheet
        .Select 'we need to select the range which should be in the email

        ActiveWorkbook.EnvelopeVisible = True
        With .Parent.MailEnvelope.Item
            .To = "here@myour.mail"
            .CC = ""
            .BCC = ""
            .Subject = sht.Range("O4").Value
            .Importance = 2
            .ReadReceiptRequested = True
            .Send
        End With
    End With

StopMacro:
    actSht.Select 'jump back to the sheet we came from
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With
    ActiveWorkbook.EnvelopeVisible = False
End Sub


问:
Match number in python using re
I got many data wrote in this form(read from file):

```<code>(31265+0j)
(-5613.54281374+404.957401125j)
(1371.65134844+2671.06617046j)
...
</code>```

And yet I want to extract the numerical part, like [31265, 0] or [-5613.54281374 , 404.957401125] , I coded in python in the way I thought it would work:

```<code>re.findall(r'.*([\+|\-]?\d+.?\d+)([\+|\-]?\d+.?\d+).*', tempStr)
</code>```

But it does not work, it gave me this:

```<code>[]
[('26', '5+0')]
[('11', '25')]
...
</code>```

What's wrong with it? Is it something about lazy mode? And how should I fix it?

========================Update========================
For me, this question is solved, but I still wonder what's wrong with the regular expression part, is there someone willing to help me point out what's wrong with the regex pattern?

答:
These are numbers. You should not use regex here. The first part is the real and the second part is the imaginary you can access them like this

```<code> n = (-5613.54281374+404.957401125j)
 n.real
 n.imag
</code>```

This maybe hard to spot at first because in maths we often use i = sqrt(-1) but in python it's j = sqrt(-1) But quit interestingly, if you do

```<code>import math
math.sqrt(-1)
</code>```

you will get a ValueError

Update:

If the data is in a file

```<code>with open('complex.txt') as f:
    for line in f:
        number = complex(line.strip())
</code>```

Update 2:
if you really, really, really want to use regex:

```<code> map(float, line[1:-2].split('+'))
</code>```

Use re.split() instead if you have numbers where the complex part can be negative.

Title: Match number in python using re

Body:
I got many data wrote in this form(read from file):

(31265+0j)
(-5613.54281374+404.957401125j)
(1371.65134844+2671.06617046j)
...

And yet I want to extract the numerical part, like [31265, 0] or [-5613.54281374 , 404.957401125] , I coded in python in the way I thought it would work:

re.findall(r'.*([\+|\-]?\d+.?\d+)([\+|\-]?\d+.?\d+).*', tempStr)

But it does not work, it gave me this:

[]
[('26', '5+0')]
[('11', '25')]
...

What's wrong with it? Is it something about lazy mode? And how should I fix it?

========================Update========================
For me, this question is solved, but I still wonder what's wrong with the regular expression part, is there someone willing to help me point out what's wrong with the regex pattern?

Body:
These are numbers. You should not use regex here. The first part is the real and the second part is the imaginary you can access them like this

 n = (-5613.54281374+404.957401125j)
 n.real
 n.imag

This maybe hard to spot at first because in maths we often use i = sqrt(-1) but in python it's j = sqrt(-1) But quit interestingly, if you do

import math
math.sqrt(-1)

you will get a ValueError

Update:

If the data is in a file

with open('complex.txt') as f:
    for line in f:
        number = complex(line.strip())

Update 2:
if you really, really, really want to use regex:

 map(float, line[1:-2].split('+'))

Use re.split() instead if you have numbers where the complex part can be negative.


问:
Saving an interactive plot with information about the data series using python
I have a question related to plots created by matplotlib. I have a GUI (in python) which creates plots from *.mat files, it saves the plots as a *.JPG file. A sample plot Looks as follows:

Now as you can see there are two data series present in the plot, and now i want to save the plot like an Excel plot where i can interact with the plot and also obtain the Location of the *.mat file from which it was created.

Can this be done using Python? I need ideas from you guys

Thanks

答:
There are of course a lot of different options to save a file containing additional information. To list a few:

Using the EXIF tags of a jpg image to store the filenames. This might require a library like piexif.

Saving a dictionary like {"files" : ["filename1", "filename2"], "image" : <imagedata>} to a file, where <imagedata> could be the raw image or a numpy array of the image data.

Pickling a dictionary like {"files" : ["filename1", "filename2"], "image" :
}, where figure is the matplotlib figure object.

At the end it might be much easier to just create a lookup table with image filenames and raw data filenames to see which image belongs to which data.

Body:
There are of course a lot of different options to save a file containing additional information. To list a few:

Using the EXIF tags of a jpg image to store the filenames. This might require a library like piexif.

Saving a dictionary like {"files" : ["filename1", "filename2"], "image" : <imagedata>} to a file, where <imagedata> could be the raw image or a numpy array of the image data.

Pickling a dictionary like {"files" : ["filename1", "filename2"], "image" : <figure>}, where figure is the matplotlib figure object.

At the end it might be much easier to just create a lookup table with image filenames and raw data filenames to see which image belongs to which data.


问:
What does #(nop) mean in docker history?
What does the #(nop) prefix mean when listing docker history?

```<code>$ docker history swarm
IMAGE               CREATED             CREATED BY
c54bba046158        9 days ago          /bin/sh -c #(nop) CMD ["--help"]
</code>```

答:
NOP stands for "no operation".

Docker "runs a shell" for every layer. All the docker commands (or layers) in the Dockerfile except the RUN command show up in the history as empty or commented out shell commands. The # sign marks the start of the comment and anything after that will be skipped by the /bin/sh. Similarly if you typing in the terminal:

```<code>user@machine $ echo hello world
hello world
user@machine $ #But none of these lines starting with # do anything
user@machine $ #echo hello world
</code>```

The non-RUN commands will not need to be interpreted by the shell, but instead are processed by docker internally.

The history (including the non-RUN commands) can be used by the layer cache to skip processing in case the same command has been run previously.

Body:
What does the #(nop) prefix mean when listing docker history?

$ docker history swarm
IMAGE               CREATED             CREATED BY
c54bba046158        9 days ago          /bin/sh -c #(nop) CMD ["--help"]

Body:
NOP stands for "no operation".

Docker "runs a shell" for every layer. All the docker commands (or layers) in the Dockerfile except the RUN command show up in the history as empty or commented out shell commands. The # sign marks the start of the comment and anything after that will be skipped by the /bin/sh. Similarly if you typing in the terminal:

user@machine $ echo hello world
hello world
user@machine $ #But none of these lines starting with # do anything
user@machine $ #echo hello world

The non-RUN commands will not need to be interpreted by the shell, but instead are processed by docker internally.

The history (including the non-RUN commands) can be used by the layer cache to skip processing in case the same command has been run previously.

ContentLicense: CC BY-SA 4.0


问:
"Number Expected" Error in IE 11 with .toLocalString()/.toISOString()
I'm getting the error "Number expected" at the line:

```<code>new Date($('#itemOpenDate').val()).toISOString();
</code>```

where $('#itemOpenDate').val() is a string representing a date, e.g. "8/11/2016", in IE 11 only (tests fine in Chrome, Firefox, and Safari).

I've narrowed it down to how #itemOpenDate is populated. See the below code. I get the error with:

```<code>('#itemOpenDate').val(new Date("8/2/2016").toLocaleString());
</code>```

but the following works fine (even in IE 11):

```<code>$('#itemOpenDate').val(new Date("8/2/2016").toDateString());
</code>```

Of course, I want the format .toLocaleString provides. Any ideas?

Code to reproduce:

```<code><!doctype html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" >
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container" role="main">
    <form class="center-block form-horizontal">
        <div class="form-group">
            <label for="itemOpenDate" class="control-label">Open Date:</label>
            <input type="text" class="form-control input-lg" id="itemOpenDate">
        </div>

        <div class="form-group">
            <button id="updateItemButton"  title="Update Item" type="button" class="btn btn-primary btn-lg btn-block">Update</button>
        </div>
    </form>
</div>

<script type="text/javascript">

$(document).ready(function () {

$("#itemOpenDate").datepicker();

getPunchlistItem();

$("#updateItemButton").click(function () {
    updatePunchlistItem();
});
});

function getPunchlistItem(myPLItemID) {
$('#itemOpenDate').val(new Date("8/2/2016").toLocaleString());  //  error
$('#itemOpenDate').val(new Date("8/2/2016").toDateString());  //  no error
}

function updatePunchlistItem() {
var myOpenDate = new Date($('#itemOpenDate').val()).toISOString();
console.log(myOpenDate);
}
</script>
</body>
</html>
</code>```

答:
I have also seen this issue but in a different way.

var date = new Date('2017-07-02 00:00:00Z').toISOString();

this works in chrome but not IE11. Adding a T between the date and the time resolves the issue in IE11 and it still works in Chrome.

var date = new Date('2017-07-02T00:00:00Z').toISOString();

http://plnkr.co/edit/8WAhslAphwR3BHxnq3bE?p=preview

Body:
I'm getting the error "Number expected" at the line:

new Date($('#itemOpenDate').val()).toISOString();

where $('#itemOpenDate').val() is a string representing a date, e.g. "8/11/2016", in IE 11 only (tests fine in Chrome, Firefox, and Safari).

I've narrowed it down to how #itemOpenDate is populated. See the below code. I get the error with:

('#itemOpenDate').val(new Date("8/2/2016").toLocaleString());

but the following works fine (even in IE 11):

$('#itemOpenDate').val(new Date("8/2/2016").toDateString());

Of course, I want the format .toLocaleString provides. Any ideas?

Code to reproduce:

<!doctype html>

<title></title>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" >

    <form class="center-block form-horizontal">

            Open Date:
            <input type="text" class="form-control input-lg" id="itemOpenDate">

            <button id="updateItemButton"  title="Update Item" type="button" class="btn btn-primary btn-lg btn-block">Update</button>

    </form>


问:
Regex to find last token on a string
I was wondering if there is a way having this

```<code>var string = "foo::bar"
</code>```

To get the last part of the string: "bar" using just regex.

I was trying to do look-aheads but couldn't master them enough to do this.

--

UPDATE

Perhaps some examples will make the question clearer.

```<code>var st1 = "foo::bar::0"
match should be 0

var st2 = "foo::bar::0-3aab"
match should be 0-3aab

var st3 = "foo"
no match should be found
</code>```

答:
You can use a negative lookahead:

```<code>/::(?!.*::)(.*)$/
</code>```

The result will then be in the capture.

Another approach:

```<code>/^.*::(.*)$/
</code>```

This should work because the .* matches greedily, so the :: will match the last occurence of that string.

Title: Regex to find last token on a string

Body:
I was wondering if there is a way having this

var string = "foo::bar"

To get the last part of the string: "bar" using just regex.

I was trying to do look-aheads but couldn't master them enough to do this.

--

UPDATE

Perhaps some examples will make the question clearer.

var st1 = "foo::bar::0"
match should be 0

var st2 = "foo::bar::0-3aab"
match should be 0-3aab

var st3 = "foo"
no match should be found

Body:
You can use a negative lookahead:

/::(?!.*::)(.*)$/

The result will then be in the capture.

Another approach:

/^.*::(.*)$/

This should work because the .* matches greedily, so the :: will match the last occurence of that string.


问:
GroupbyKey on spark dataset
Does groupByKey causes a shuffle of all values across the network, even if they are already co-located within a partition, When we do group by operation in sparkSQL , does it uses groupbykey or it uses aggregateByKey for performance ? </p>

答:
groupByKey will not shuffle on data if the keys are all co-located within each partition. But that would be a rare case.

groupBy operation in sparkSQL is an aggregateByKey which makes it an aggregation operation. We can define aggregation functions after groupBy in sparkSQL. groupBy simply create one instance of the Aggregation Expressions for each group and each aggregation and go through the data and keep updating those Expressions

Title: GroupbyKey on spark dataset


问:
Efficiently restoring one database to another using AWS RDS
I have a MySQL database called latest, and another database called previous, both running on the same server. Both databases have identical content. Once per day, an application runs that updates latest. Later on, towards the end of the applications execution, a comparison is made between latest and previous for certain data. Differences that are found, if any, will trigger certain actions e.g. notification emails to sent. After that, a copy of latest is dumped to a file using mysqldump and restored to previous. Both databases are now in sync again and the process repeats the following day.

I would like to migrate the database(s) to AWS RDS. I'm open to using Aurora, but the MySQL engine is fine too. Is there a simpler or more efficient way of performing the restore process so that both databases are in sync using RDS? A way that avoids having to use mysqldump and feeding the result into previous?

I understand that I could create a read replica of an instance running latest to act as previous, but I think that updates the read replica as the source DB is updated (well, asynchronously anyway) which would ruin the possibility of performing a comparison between the two later on.

I don't have any particular problem with using mysqldump for the restore process, but I'm just not sure If I'm missing a trick.

答:
If you don't want a read replica, your option using mysqldump is good but probably you could use it with mysqlimport as suggested in the MySQL Docs:

Copying MySQL Databases to Another Machine

You can also use mysqldump and mysqlimport to transfer the database. For large tables, this is much faster than simply using mysqldump.


问:
CSS background image make darker
I have the following: www.thewhozoo.com

As you can see, it has a background image.

```<code>.top-container {
    float: left;
    width: 100%;
    background: url('../images/background1.jpg') no-repeat center center fixed;
       -webkit-background-size: cover;
       -moz-background-size: cover;
       -o-background-size: cover;
       background-size: cover;
  }
</code>```

The background image has white text on top of it, which may be a little difficult to read.

I have added a text-shadow to the text, which has helped make the text stand out more.

```<code>.text-description-header {
    font-size: 250%;
    color: white;
    text-shadow: 0px 1px 14px rgba(0,0,0,1.0);
}
</code>```

However, I would like the text to stand out even more.

Question

Are there suggestions how I can make the text-shadow even darker?

Or, make the background image a little darker?

Thanks

答:
I would go for photoshop to blur the background or give it an overlay. However you can try giving it a linear gradient on your top-container class before the url call on the background-image as so:

```<code>background: linear-gradient( rgba(0,0,0,0.5), rgba(0, 0, 0, 0.5) ),url(../images/background1.jpg) no-repeat center center fixed;
</code>```

just change the rgba value to what you need. Hope this helps.

Title: CSS background image make darker

Body:
I have the following: www.thewhozoo.com

As you can see, it has a background image.

.top-container {
    float: left;
    width: 100%;
    background: url('../images/background1.jpg') no-repeat center center fixed;
       -webkit-background-size: cover;
       -moz-background-size: cover;
       -o-background-size: cover;
       background-size: cover;
  }

The background image has white text on top of it, which may be a little difficult to read.

I have added a text-shadow to the text, which has helped make the text stand out more.

.text-description-header {
    font-size: 250%;
    color: white;
    text-shadow: 0px 1px 14px rgba(0,0,0,1.0);
}

However, I would like the text to stand out even more.

Question

Are there suggestions how I can make the text-shadow even darker?

Or, make the background image a little darker?

Thanks

Body:
I would go for photoshop to blur the background or give it an overlay. However you can try giving it a linear gradient on your top-container class before the url call on the background-image as so:

background: linear-gradient( rgba(0,0,0,0.5), rgba(0, 0, 0, 0.5) ),url(../images/background1.jpg) no-repeat center center fixed;

just change the rgba value to what you need. Hope this helps.


问:
Gradle task dependency only for rootProject in allprojects section
I got a gradle task to build docker images for all my projects. These run fine except for the rootProject which has a dependent task to be executed before the DockerimageBuild itself. This dependency should only apply for therootProject` and not the subprojects.
I googled extensively and read the docs but didn't find the perfect solution to add a dependency, probably i am missing a obvious point.

This is my task (stripped out some of the gradle file).

```<code>allprojects {
apply plugin: com.bmuschko.gradle.docker.DockerRemoteApiPlugin
    repositories { jcenter() }

docker {
    registryCredentials {
            username = dockerRegistryUsername
            password = dockerRegistryPassword
    }
}

// task build_DockerImage(type: DockerBuildImage, dependsOn: [copy_ImageSource, prepare_ImageConfig]) {
task build_DockerImage(type: DockerBuildImage) {
    group 'Docker'
    description "Builds the docker image: ${dockerTag} locally"
    println "Project: ${rootProject.projectDir}/ci/images/${project.name}"
    inputDir = file("${rootProject.projectDir}/ci/images/${project.name}")
    tag = "azeti/${project.name}:${dockerTag}"
}
</code>```

It should have dependsOn: copy_ImageSource but i can't figure out the right notation for it.

Thanks for your help.
Regards,
Sebastian

答:
The solution is as simple as comparing the current project's name with the ones of the root project and only applying dependsOnfor a match.

I have stripped out rest of the code for the sake of simplicity, check the if condition.

```<code>task build_DockerImage(type: DockerBuildImage) {
    group 'Docker'
    description "Builds the docker image: ${dockerTag} locally"
    if(project.name.equals(rootProject.name) ) {
        dependsOn copy_ImageSource
    }
    inputDir = file("${rootProject.projectDir}/ci/images/${project.name}")
    tag = "azeti/${project.name}:${dockerTag}"
}
</code>```

Body:
I got a gradle task to build docker images for all my projects. These run fine except for the rootProject which has a dependent task to be executed before the DockerimageBuild itself. This dependency should only apply for therootProject` and not the subprojects.
I googled extensively and read the docs but didn't find the perfect solution to add a dependency, probably i am missing a obvious point.

This is my task (stripped out some of the gradle file).

allprojects {
apply plugin: com.bmuschko.gradle.docker.DockerRemoteApiPlugin
    repositories { jcenter() }

docker {
    registryCredentials {
            username = dockerRegistryUsername
            password = dockerRegistryPassword
    }
}

// task build_DockerImage(type: DockerBuildImage, dependsOn: [copy_ImageSource, prepare_ImageConfig]) {
task build_DockerImage(type: DockerBuildImage) {
    group 'Docker'
    description "Builds the docker image: ${dockerTag} locally"
    println "Project: ${rootProject.projectDir}/ci/images/${project.name}"
    inputDir = file("${rootProject.projectDir}/ci/images/${project.name}")
    tag = "azeti/${project.name}:${dockerTag}"
}

It should have dependsOn: copy_ImageSource but i can't figure out the right notation for it.

Thanks for your help.
Regards,
Sebastian

Body:
The solution is as simple as comparing the current project's name with the ones of the root project and only applying dependsOnfor a match.

I have stripped out rest of the code for the sake of simplicity, check the if condition.

task build_DockerImage(type: DockerBuildImage) {
    group 'Docker'
    description "Builds the docker image: ${dockerTag} locally"
    if(project.name.equals(rootProject.name) ) {
        dependsOn copy_ImageSource
    }
    inputDir = file("${rootProject.projectDir}/ci/images/${project.name}")
    tag = "azeti/${project.name}:${dockerTag}"
}