问:
Dynamic style - Angular
Basivally i have a div ,which i'm putting a dynamic style

```<code><div style="position:relative; left: {{et.getNumPadStyle()}}px">
</code>```

My function getNumPadStyle will have

```<code>function getNumPadStyle {
    var num = "25";
    return num;
}
</code>```

This is giving me an error

```<code>Referencing DOM nodes in Angular expressions is disallowed! Expression: et.getNumPadStyle()
</code>```

And when i inspect the element, the exact number is not reflecting

```<code>element {
    position:relative;
    left:{{et.getNumPadStyle()}}px
}
</code>```

How to resolve this?

答:
Try with ng-style like this:

```<code><div ng-style="et.getNumPadStyle()">
</code>```

And in Angular code:

```<code>    $scope.et = {};
    $scope.et.getNumPadStyle = {
        "padding-left" : "25px"
    }
</code>```

Title: Dynamic style - Angular

Body:
Basivally i have a div ,which i'm putting a dynamic style

My function getNumPadStyle will have

function getNumPadStyle {
    var num = "25";
    return num;
}

This is giving me an error

Referencing DOM nodes in Angular expressions is disallowed! Expression: et.getNumPadStyle()

And when i inspect the element, the exact number is not reflecting

element {
    position:relative;
    left:{{et.getNumPadStyle()}}px
}

How to resolve this?

Body:
Try with ng-style like this:

<div ng-style="et.getNumPadStyle()">

And in Angular code:

    $scope.et = {};
    $scope.et.getNumPadStyle = {
        "padding-left" : "25px"
    }


来源: stackexchange

问:
How combine two query in mysql which have all different column name
this is the query for search product. The data have product listing from the different two table.</p>

```<code>$where = " Jewellery_Title like '%$id%' or Jewellery_SKU like '%$id%' and Jewellery_Status='Active'";
// $where_s = implode(' and ', $where);
$sql = "select * from jewellery where (".$where."".$jewellery_name." ) $metal_where  order by rank asc";
$res1 = query($con,$sql);
$total1 = row($res1);

$where = " Ring_Title like '%$id%' or Ring_SKU like '%$id%' $ring_name
and Ring_Status='Active'";
$sql = "select * from rings where (".$where.")  $metal_where order by rank asc";
$res2 = query($con,$sql);
$total2 = row($res2);
</code>```

答:
Use alias in mysql query as i mention above and run the array merge .

```<code>$sql=select jewelleryname as name from jewellery
$sql1=select ringname as name from rings
// more code
 $total = row($res1);
 $total1 = row($res2);
$C = array_merge($total , $total1);
</code>```

if you want join query use this

```<code>select jewelleryname as name from jewellery
UNION ALL
select ringname as name from rings
</code>```

ContentLicense: CC BY-SA 3.0

Body:
this is the query for search product. The data have product listing from the different two table.

$where = " Jewellery_Title like '%$id%' or Jewellery_SKU like '%$id%' and Jewellery_Status='Active'";
// $where_s = implode(' and ', $where);
$sql = "select * from jewellery where (".$where."".$jewellery_name." ) $metal_where  order by rank asc";
$res1 = query($con,$sql);
$total1 = row($res1);

$where = " Ring_Title like '%$id%' or Ring_SKU like '%$id%' $ring_name
and Ring_Status='Active'";
$sql = "select * from rings where (".$where.")  $metal_where order by rank asc";
$res2 = query($con,$sql);
$total2 = row($res2);

Body:
Use alias in mysql query as i mention above and run the array merge .

$sql=select jewelleryname as name from jewellery
$sql1=select ringname as name from rings
// more code
 $total = row($res1);
 $total1 = row($res2);
$C = array_merge($total , $total1);

if you want join query use this

select jewelleryname as name from jewellery
UNION ALL
select ringname as name from rings


问:
How do I add am image in a TableView from URL
I am confused about how I can take the DownloadURL which is a link and turn it into an image and add it in my tableview cell? I have an imageview in my storyboard and dont know how to connect it to the tableview cell either. Thanks!</p>

```<code>override func viewDidLoad() { super.viewDidLoad()

    let ref = FIRDatabase.database().reference().child("Posts")

    ref.observeSingleEvent(of: .value, with: { snapshot in

        print(snapshot.childrenCount)

        for rest in snapshot.children.allObjects as! [FIRDataSnapshot] {

            guard let value = rest.value as? Dictionary<String,Any> else { continue }

            guard let  downloadURL = value["DownloadURL"] as? String else { continue }

            let post = postStruct(title: title, date: date, author: author, article: article, downloadURL: downloadURL)

            self.posts.append(post)

        }

        self.posts = self.posts.reversed(); self.tableView.reloadData()

    })

}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return posts.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")

    let label1 = cell?.viewWithTag(1) as! UILabel
    label1.text = posts[indexPath.row].title
    return cell!
}
</code>```

答:
Google this cocoapod: SDWebImage

use this, it is incredible

Swift:

```<code>import SDWebImage

imageView.sd_setImage(with: URL(string: "url"), placeholderImage: UIImage(named: "placeholder.png"))
</code>```

In regards to your second question connection your image view, you will need to create a custom cell

Body:
I am confused about how I can take the DownloadURL which is a link and turn it into an image and add it in my tableview cell? I have an imageview in my storyboard and dont know how to connect it to the tableview cell either. Thanks!

override func viewDidLoad() { super.viewDidLoad()

    let ref = FIRDatabase.database().reference().child("Posts")

    ref.observeSingleEvent(of: .value, with: { snapshot in

        print(snapshot.childrenCount)

        for rest in snapshot.children.allObjects as! [FIRDataSnapshot] {

            guard let value = rest.value as? Dictionary<String,Any> else { continue }

            guard let  downloadURL = value["DownloadURL"] as? String else { continue }

            let post = postStruct(title: title, date: date, author: author, article: article, downloadURL: downloadURL)

            self.posts.append(post)

        }

        self.posts = self.posts.reversed(); self.tableView.reloadData()

    })

}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return posts.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")

    let label1 = cell?.viewWithTag(1) as! UILabel
    label1.text = posts[indexPath.row].title
    return cell!
}

Body:
Google this cocoapod: SDWebImage

use this, it is incredible

Swift:

import SDWebImage

imageView.sd_setImage(with: URL(string: "url"), placeholderImage: UIImage(named: "placeholder.png"))

In regards to your second question connection your image view, you will need to create a custom cell


问:
"expected'; ',' or 'or') 'before' * 'token" error when using structure
all

I have a few problems with using structures.

The source is shown below.

main.c

#include <stdio.h>
#include "info.h"

_Rbuffer Rb;

void write(_Rbuffer Rb *rb)
{
    printf("write function\n");
}

void main(void)
{

    printf("Hello World\n");

}
```

<h2>info.h</h2>

<pre class="lang-c prettyprint-override"><code>#include <stdint.h>

typedef struct
{
    uint8_t Button1;
} _Rbuffer;

extern _Rbuffer Rb;
</code>```

When compiling, the following error occurs.

```<code>root@test-VirtualBox:~/sample# gcc main.c
main.c:6:24: error: expected ‘;’, ‘,’ or ‘)’ before ‘*’ token
 void write(_Rbuffer Rb *rb)
                        ^
root@test-VirtualBox:~/sample#
</code>```

I am currently unable to change info.h.

I declare a structure and I do not know why an error occurs.

How do I fix this?

答:
```<code>void write(_Rbuffer Rb *rb)
{
printf("write function\n");
}
</code>```

you passed in Rb, but you also pointed at *rb

if you want to modify Rb, then

```<code>void write(_Rbuffer* Rb)
</code>```

if you just want to a copy of your Rb, then

```<code>void write (_Rbuffer Rb)
</code>```

Body:
all

I have a few problems with using structures.

The source is shown below.

main.c

#include <stdio.h>
#include "info.h"

_Rbuffer Rb;

void write(_Rbuffer Rb *rb)
{
    printf("write function\n");
}

void main(void)
{

    printf("Hello World\n");

}

info.h

#include <stdint.h>

typedef struct
{
    uint8_t Button1;
} _Rbuffer;

extern _Rbuffer Rb;

When compiling, the following error occurs.

root@test-VirtualBox:~/sample# gcc main.c
main.c:6:24: error: expected ‘;’, ‘,’ or ‘)’ before ‘*’ token
 void write(_Rbuffer Rb *rb)
                        ^
root@test-VirtualBox:~/sample#

I am currently unable to change info.h.

I declare a structure and I do not know why an error occurs.

How do I fix this?

Body:
void write(_Rbuffer Rb *rb)
{
printf("write function\n");
}

you passed in Rb, but you also pointed at *rb

if you want to modify Rb, then

void write(_Rbuffer* Rb)

if you just want to a copy of your Rb, then

void write (_Rbuffer Rb)


问:
Way to compare index of 2 lists?
Hi guys how do I compare index of 2 lists (by linking them together)

```<code>a = [1,2,3,4]
b = ["a","b","c","d"]
</code>```

For exammple, let's say I want to print a value from b after inputing a value from a into another variable, how do I go about doing that where output generated is for examples : a and 1
sorry for my bad english

答:
You could try</p>

```<code>for index in range(0,len(a)):
    print(a[index],b[index]);
</code>```

Title: Way to compare index of 2 lists?

Body:
Hi guys how do I compare index of 2 lists (by linking them together)

a = [1,2,3,4]
b = ["a","b","c","d"]

For exammple, let's say I want to print a value from b after inputing a value from a into another variable, how do I go about doing that where output generated is for examples : a and 1
sorry for my bad english

Body:
You could try

for index in range(0,len(a)):
    print(a[index],b[index]);


问:
Bind to AccessibilityService in Android?
I have created an android Service, which  extends an AccessibilityService. From my Activity, I would like to bind to that Service. Because I need to send information from Service to Activity. I need example code please. I have searched google and have not found anything similar, someone could put a link to an example please.

答:
Maybe there is another way to communicate whith each other:

At AccessibilityService Child Class:

Handle the target Activity's:

  PackageName AND

  ActivityName AND

  specific EventType(eg:AccessibilityEvent.TYPE_VIEW_CLICKED)

```<code>@Override
public void onAccessibilityEvent(final AccessibilityEvent event)
{
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_CLICKED)
            if (AccessibilityUtils.findNodeInfoByViewTypeAndText(event.getSource(), "android.widget.ToggleButton", TextUtils.getString(R.string.lable_disabled)) != null)
                getAccessibilityService().disableSelf();
}
</code>```

At target Activity:just invoke the specific EventType

invoke by user OR

  invoke by code

```<code>btnEnableService.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(final View v)
            {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && !btnEnableService.isChecked())
                {
                    btnEnableService.setChecked(false);
                    txvEnabledState.setText(btnEnableService.isChecked() ? R.string.lable_service_status_enabled : R.string.lable_service_status_closed);
                    AppState.instance().setIsEnable(btnEnableService.isChecked());
                }
                else
                {
                    openAccessibilitySettings();

                    btnEnableService.setChecked(!btnEnableService.isChecked());
                }
            }
        });
</code>```

Sample Code:

AppEventHandler_disableSelf.java — Bitbucket

SettingActivity.java — Bitbucket

Body:
Maybe there is another way to communicate whith each other:

At AccessibilityService Child Class:

Handle the target Activity's:

  PackageName AND

  ActivityName AND

  specific EventType(eg:AccessibilityEvent.TYPE_VIEW_CLICKED)

@Override
public void onAccessibilityEvent(final AccessibilityEvent event)
{
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_CLICKED)
            if (AccessibilityUtils.findNodeInfoByViewTypeAndText(event.getSource(), "android.widget.ToggleButton", TextUtils.getString(R.string.lable_disabled)) != null)
                getAccessibilityService().disableSelf();
}

At target Activity:just invoke the specific EventType

invoke by user OR

  invoke by code

btnEnableService.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(final View v)
            {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && !btnEnableService.isChecked())
                {
                    btnEnableService.setChecked(false);
                    txvEnabledState.setText(btnEnableService.isChecked() ? R.string.lable_service_status_enabled : R.string.lable_service_status_closed);
                    AppState.instance().setIsEnable(btnEnableService.isChecked());
                }
                else
                {
                    openAccessibilitySettings();

                    btnEnableService.setChecked(!btnEnableService.isChecked());
                }
            }
        });

Sample Code:

AppEventHandler_disableSelf.java — Bitbucket

SettingActivity.java — Bitbucket


问:
Executing JMETER Junit Sampler (Selenium Webdriver) using MAven
I have created a simple JMETER Load test which runs perfectly fine from JMETER. I have created the Load test case by:

Writing a simple JUNIT test in eclipse

Exporting the JUNIT test as Jar

Creating a load test using JUNIT test case.

The above works fine within JMETER. However, I am unable to run the same using MAVEN ( JMETER MAVEN Plugin) i.e. test does not run. I can see a message

```<code>[info] Executing test: JUnitRequest.jmx
[info] Completed Test: JUnitRequest.jmx
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 10.033s
[INFO] Finished at: Wed Jun 07 20:12:40 BST 2017
[INFO] Final Memory: 16M/309M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal com.lazerycode.jmeter:jmeter-maven-plugin:1.9.1:jmeter (jmeter-tests) on project restapitest: C:\2017\JMETER\RestApiTest\target\jmeter\results\20170607-JUnitRequest.jtl (The system cannot find the file specified) -> [Help 1]
[ERROR]
</code>```

and then a error message:

Please find below my POM.XML:

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

    <groupId>com.jmeter.restapi</groupId>
    <artifactId>restapitest</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>com.lazerycode.jmeter</groupId>
                <artifactId>jmeter-maven-plugin</artifactId>
                <version>1.9.1</version>
                <executions>
                    <execution>
                        <id>jmeter-tests</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>jmeter</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <jmeterExtensions>
                        <artifact>kg.apc:jmeter-plugins:pom:1.3.1</artifact>
                    </jmeterExtensions>
                    <junitLibraries>
                        <artifact>com.lazerycode.junit:junit-test:1.0.0</artifact>
                    </junitLibraries>
                </configuration>

                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.17</version>
                        <type>jar</type>
                        <scope>compile</scope>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

答:
Going forward could you please include the error as well as we are most interested in it rather than in your configuration.

With regards to your question itself, I fail to see any sign of plugging your jar or dependency libraries.

You need to include:

Your JUnit jar itself

Any dependencies

into the pom.xml file. The process is described in details at Adding additional libraries to the classpath page of the JMeter Maven Plugin wiki.

My expectation is that your pom.xml file should look somehow like:

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

    <groupId>jmeter-selenium-junit</groupId>
    <artifactId>jmeter-selenium-junit-test</artifactId>
    <version>1.0-SNAPSHOT</version>

    <repositories>
        <repository>
            <id>your-junit-jar</id>
            <name>your junit repo</name>
            <url>file:/path/to/your-junit-jar.jar</url>
        </repository>
    </repositories>

    <build>
        <plugins>
            <plugin>
                <groupId>com.lazerycode.jmeter</groupId>
                <artifactId>jmeter-maven-plugin</artifactId>
                <version>2.2.0</version>
                <executions>
                    <execution>
                        <id>jmeter-tests</id>
                        <goals>
                            <goal>jmeter</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <jmeterExtensions>
                        <artifact>org.seleniumhq.selenium:selenium-java:2.52.0</artifact>
                        <artifact>org.seleniumhq.selenium:selenium-firefox-driver:2.52.0</artifact>
                    </jmeterExtensions>
                    <junitLibraries>
                        <artifact>com.yourcompany.yourgroup:your-artifact:1.0-SNAPSHOT</artifact>
                    </junitLibraries>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

See Five Ways To Launch a JMeter Test without Using the JMeter GUI article for more information on different approaches to running a JMeter test including Maven plugin

Body:
I have created a simple JMETER Load test which runs perfectly fine from JMETER. I have created the Load test case by:

Writing a simple JUNIT test in eclipse

Exporting the JUNIT test as Jar

Creating a load test using JUNIT test case.

The above works fine within JMETER. However, I am unable to run the same using MAVEN ( JMETER MAVEN Plugin) i.e. test does not run. I can see a message

[info] Executing test: JUnitRequest.jmx
[info] Completed Test: JUnitRequest.jmx
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 10.033s
[INFO] Finished at: Wed Jun 07 20:12:40 BST 2017
[INFO] Final Memory: 16M/309M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal com.lazerycode.jmeter:jmeter-maven-plugin:1.9.1:jmeter (jmeter-tests) on project restapitest: C:\2017\JMETER\RestApiTest\target\jmeter\results\20170607-JUnitRequest.jtl (The system cannot find the file specified) -> [Help 1]
[ERROR]

and then a error message:

Please find below my POM.XML:

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

    <groupId>com.jmeter.restapi</groupId>
    <artifactId>restapitest</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>com.lazerycode.jmeter</groupId>
                <artifactId>jmeter-maven-plugin</artifactId>
                <version>1.9.1</version>
                <executions>
                    <execution>
                        <id>jmeter-tests</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>jmeter</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <jmeterExtensions>
                        <artifact>kg.apc:jmeter-plugins:pom:1.3.1</artifact>
                    </jmeterExtensions>
                    <junitLibraries>
                        <artifact>com.lazerycode.junit:junit-test:1.0.0</artifact>
                    </junitLibraries>
                </configuration>

                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.17</version>
                        <type>jar</type>
                        <scope>compile</scope>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

</project>

Body:
Going forward could you please include the error as well as we are most interested in it rather than in your configuration.

With regards to your question itself, I fail to see any sign of plugging your jar or dependency libraries.

You need to include:

Your JUnit jar itself

Any dependencies

into the pom.xml file. The process is described in details at Adding additional libraries to the classpath page of the JMeter Maven Plugin wiki.

My expectation is that your pom.xml file should look somehow like:

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

    <groupId>jmeter-selenium-junit</groupId>
    <artifactId>jmeter-selenium-junit-test</artifactId>
    <version>1.0-SNAPSHOT</version>

    <repositories>
        <repository>
            <id>your-junit-jar</id>
            <name>your junit repo</name>
            <url>file:/path/to/your-junit-jar.jar</url>
        </repository>
    </repositories>

    <build>
        <plugins>
            <plugin>
                <groupId>com.lazerycode.jmeter</groupId>
                <artifactId>jmeter-maven-plugin</artifactId>
                <version>2.2.0</version>
                <executions>
                    <execution>
                        <id>jmeter-tests</id>
                        <goals>
                            <goal>jmeter</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <jmeterExtensions>
                        <artifact>org.seleniumhq.selenium:selenium-java:2.52.0</artifact>
                        <artifact>org.seleniumhq.selenium:selenium-firefox-driver:2.52.0</artifact>
                    </jmeterExtensions>
                    <junitLibraries>
                        <artifact>com.yourcompany.yourgroup:your-artifact:1.0-SNAPSHOT</artifact>
                    </junitLibraries>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

See Five Ways To Launch a JMeter Test without Using the JMeter GUI article for more information on different approaches to running a JMeter test including Maven plugin


问:
Publising nuget package with Powershell scripts - scripts are not packaged
I am using Visual Studio Team Services to package a folder and pr documentation I have added a content folder, also tried with contentFiles folder, that contains another folder and then my powershell script. The package is created, but the content folder is not packaged.

Structure is like /content/ReleaseScripts/MyScript.ps1

答:
If you package project file directly, you need to change that file’s Build Action to Content. (Right click the file in VS > Properties >Change Build Action to Content)

If you just create .nuspec file in a folder (no project file, such as .csproj) and pack this .nuspec file, you can refer to these steps:

Add Nuget.exe tool to source control and map to build agent (same folder level (content folder) that you need to package) or add it to the environment variable (path) of build agent service account.

Add Command Line task (Tool: nugget.exe; Arguments: spec; Working folder:[same level path that you need to package, such as the folder path that contains content folder]

Add NuGet Packager task (Path to csproj or nuspec files to pack: **\*.nuspec)


问:
SSMS - stop execution with sql command
Is there a command in SSMS to pause execution at selected point, like putting break point?

Example:

```<code>declare @i int
declare @b int

debugger // stop execution here

select * from myTable
</code>```

Something like debugger command in javascript?

答:
If you want to execute a certain part only then you can select only that part and execute it. If you want to execute only this part then you select this and

```<code>declare @i int
declare @b int
</code>```

press F5 or the click on the execute button.

And later on you can execute this part.
select * from myTable

Title: SSMS - stop execution with sql command

Body:
Is there a command in SSMS to pause execution at selected point, like putting break point?

Example:

declare @i int
declare @b int

debugger // stop execution here

select * from myTable

Something like debugger command in javascript?

Body:
If you want to execute a certain part only then you can select only that part and execute it. If you want to execute only this part then you select this and

declare @i int
declare @b int

press F5 or the click on the execute button.

And later on you can execute this part.
select * from myTable


问:
How will I know when to create an interface?
I'm at a point in my development learning where I feel like I must learn more about interfaces.

I frequently read about them but it just seems like I cannot grasp them.

I've read examples like: Animal base class, with IAnimal interface for things like 'Walk', 'Run', 'GetLegs', etc - but I've never been working on something and felt like "Hey I should use an interface here!"

What am I missing? Why is it such a hard concept for me to grasp! I am just intimidated by the fact that I might not ever realize a concrete need for one - mostly due to some missing aspect of understanding them! It makes me feel like I'm missing something up top in terms of being a developer! If anyone has had an experience like this and had a breakthrough I would appreciate some tips on how to understand this concept. Thank you.

答:
Use interfaces when implementations of the same functionality will differ.

Use a abstract/base classes when you need to share a common concrete implementation.

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: ALassek


问:
Populate Pivot Table from a Comma Delimited Field in a Data Flow Task in SSIS
This is my 1st post, so be gentle :). I am building an SSIS package to collect information on jobs running throughout the enterprise at work. The goal is to have tables filled with info on Servers, Instance, DBs, Jobs, and their relations to each other. Ideally I will use merge commands to update or insert where necessary but for now it just inserts. Here is an overview of my package (keep your mind out of the gutter please :P):

(restrictions on hyperlinks for new users means you need to replace the + signs with "t"s in my links

http://img262.imageshack.us/i/package.jpg/

The 1st Data Flow task pulls in a list of instances to check from a flat text file and stores them in a record set. The foreach loop then goes through each one of them and changes my source Connection Manager's Connection string appropriately. Inside the loop we are going through 1 instance at a time. The "Process Server" Dataflow task is used to find the Server name and add it to the Destination DB if it doesn't exist, either way it also stores the Server ID and Name in package variables. The "Process Instance" does the same as the above but for the Instance instead. The "Collect DB Data" Task then uses those package variables to insert all the DBs in that instance as records with the Package variables mentioned above for Foreign keys. Once that is Finished we move on to the "Collect Job Data" task (hopefully the final task for this package). The following is the contents of the last task:

http://img809.imageshack.us/i/dataflow.png/

So inside of this task this is what I'm doing so far. I use a query to collect Job Info with Maintenance plan data 1st. Here is the Query for the OLE DB Source:

```<code>--WRITTEN BY MAXWELL WALLACE
--THE PURPOSE OF THIS QUERY IS TO COLLECT INFORMATION ABOUT JOBS AND MAINTENANCE PLANS
--RUNNING ON A PARTICULAR INSTANCE. IT COLLECTS NAMES, STATUSES, RUN TIMES AND DATES
--AS WELL AS DATABASES AFFECTED AND MAINTENANCE PLAN NAMES IF APPLICABLE.
SELECT B.NAME AS JOB_NAME, B.CATEGORY_ID,
--RUN_STATUS CODE GETS TRANSLATED INTO ENGLISH
CASE A.RUN_STATUS
WHEN 0 THEN 'Failed'
WHEN 1 THEN 'Succeeded'
WHEN 2 THEN 'Retry'
WHEN 3 THEN 'Canceled'
ELSE 'Unknown'
END AS RUN_STATUS,
--CONVERT INTEGER DATE INTO SOMETHING MORE LEGABLE
SUBSTRING(CAST(A.RUN_DATE AS CHAR(8)),5,2) + '/' +
RIGHT(CAST(A.RUN_DATE AS CHAR(8)),2) + '/' +
LEFT(CAST(A.RUN_DATE AS CHAR(8)),4) AS RUN_DATE,
--CONVERT RUN_TIME INTO SOMETHING MORE RECONGNIZABLE (HH:MM:SS)
LEFT(RIGHT('000000' + CAST(A.RUN_TIME AS VARCHAR(10)),6),2) + ':' +
SUBSTRING(RIGHT('000000' + CAST(A.RUN_TIME AS VARCHAR(10)),6),3,2) + ':' +
RIGHT(RIGHT('000000' + CAST(A.RUN_TIME AS VARCHAR(10)),6),2) AS RUN_TIME,
--CONVERT RUN_DURATION INTO SOMETHING MORE RECONGNIZABLE (HH:MM:SS)
LEFT(RIGHT('000000' + CAST(A.RUN_DURATION AS VARCHAR(10)),6),2) + ':' +
SUBSTRING(RIGHT('000000' + CAST(A.RUN_DURATION AS VARCHAR(10)),6),3,2) + ':' +
RIGHT(RIGHT('000000' + CAST(A.RUN_DURATION AS VARCHAR(10)),6),2) AS RUN_DURATION,
--THE FOLLOWING SUBQUERY IS USED TO EXTRAPOLATE DETAILS FOR THE JOB IN IT'S MAINTENANCE PLAN (IF IT HAS 1)
--THE TOP 1 MAKES SURE WE GET ONLY 1 RECORD SINCE THIS IS A 1 TO MANY RELATIONSHIP
--THE LINE3 COLUMN CONTAINS DETAILS ABOUT THE TASK THAT WAS RUN
(SELECT TOP 1 E.LINE3
    --WE START WITH THE SYSMAINTPLAN_LOG BECAUSE WE CAN (IN A WAY) JOIN IT TO OUR OUTER JOIN THROUGH THE PLAN_ID IN THE WHERE CLAUSE
    FROM MSDB.DBO.SYSMAINTPLAN_LOG AS D
    --NOW IT IS POSSIBLE TO, BY EXTENTION, JOIN SYSMAINTPLAN_LOGDETAIL TO THE OUTER JOIN AS WELL THROUGH ITS 1 TO 1 RELATIONSHIP WITH SYSMAINTPLAN_LOG
    INNER JOIN MSDB.DBO.SYSMAINTPLAN_LOGDETAIL AS E ON E.TASK_DETAIL_ID = D.TASK_DETAIL_ID
    --THE 1ST PART OF THE WHERE RETURNS ONLY RECORDS OF THE SAME PLAN_ID, ESSENTIALLY "JOINING" THIS RECORD TO THE OUTER JOIN THE IN MAIN QUERY
    --THE 2ND PART MAKES SURE THE FIELD WE ACTUALLY CARE ABOUT CONTAINS MEANINGFUL DATA
    WHERE D.PLAN_ID = C.PLAN_ID AND E.LINE3 != '') AS PLAN_DETAILS,
--THE FOLLOWING SUBQUERY RETURNS THE NAME OF THE MAINTENANCE PLAN (IF IT HAS 1)
(SELECT F.NAME
    FROM MSDB.DBO.SYSMAINTPLAN_PLANS AS F --THIS IS A SYSTEM GENERATED VIEW
    --LIKE THE ABOVE SUBQUERY, THIS WHERE ESSENTIALLY "JOINS" THIS RECORD TO THE OUTER JOIN IN THE MAIN QUERY
    WHERE F.ID = C.PLAN_ID) AS PLAN_NAME
FROM MSDB.DBO.SYSJOBHISTORY AS A
INNER JOIN MSDB.DBO.SYSJOBS AS B ON A.JOB_ID = B.JOB_ID
--THIS OUTTER JOIN ATTACHES PLAN_IDS OF MAINTENANCE PLANS TO JOBS THAT HAVE THEM
LEFT OUTER JOIN SYSMAINTPLAN_SUBPLANS AS C ON C.JOB_ID = B.JOB_ID
--ONLY RETURN ENABLED JOBS
WHERE B.[ENABLED] = 1
--AND ONLY JOB OUTCOMES, NOT EACH STEP
AND A.STEP_ID = 0
--AND ONLY COMPLETED JOBS
AND A.RUN_STATUS <> 4
--SORTED BY LATEST DATE 1ST
ORDER BY A.RUN_DATE DESC
</code>```

Sorry, but for some reason this forum doesn't preserve my formatting. Anyway, after that I add the package variable Instance ID as a column to assist in inserting these records with this Foreign Key. I convert some strings to unicode which is neither here nor there and then I do a conditional split on Records With a maintenance plan and records without. For records without I can Simply insert them into the destination and they are done! For records with a Maintenance plan however, the chance of them having a connection to one or more DB is very high. So, 1st I insert the job record into the Job table (exactly as I do with records not within a maintenance plan) and then I do a lookup to find the record I just inserted's ID. Next I take the field from my query that has a comma separated list of DBs affected by the Maintenance plan this job is part of and separate it into a VB.Net ArrayList. I then assign that ArrayList to a Package Variable.

This is the part I'm at. Obviously my next step is to create some sort of loop using the Job ID I just looked up and running through each variable in the ArrayList to insert them 1 at a time into the DB/Job Pivot table. Problem is I am not aware of how I can do a loop within a Data Flow Task and I can't think of a good way to move the pivot table insert out of this task. I might be able to do this with a script component but I am unsure how to preform inserts from within the script task (should I even consider that?). I am proficient with VB.Net and C# as well as TSQL so I can investigate any method of implementing this. Thanks in advance for your help. Cheers!

PS. Here is the table structure I am inserting the data into:

```<code>CREATE TABLE TBL_SERVERS(
ID INT UNIQUE IDENTITY(1,1),
TITLE NVARCHAR(50) PRIMARY KEY,
CLUSTER_NAME NVARCHAR(50) DEFAULT '',
RESOURCES_USED NVARCHAR(20) DEFAULT '',
RESOURCE_THRESHOLD NVARCHAR(20) DEFAULT '',
IS_CLUSTERED BIT NOT NULL DEFAULT 0)

CREATE TABLE TBL_INSTANCES(
ID INT UNIQUE IDENTITY(1,1),
SERVER_ID INT NOT NULL REFERENCES TBL_SERVERS(ID),
TITLE NVARCHAR(50) NOT NULL,
PRIMARY KEY (SERVER_ID,TITLE))

CREATE TABLE TBL_CATEGORY_TYPES(
ID INT UNIQUE IDENTITY(1,1),
TITLE NVARCHAR(50) PRIMARY KEY)

INSERT INTO TBL_CATEGORY_TYPES VALUES ('LOCAL')
INSERT INTO TBL_CATEGORY_TYPES VALUES ('MULTISERVER')
INSERT INTO TBL_CATEGORY_TYPES VALUES ('NONE')

CREATE TABLE TBL_CATEGORY_CLASSES(
ID INT UNIQUE IDENTITY(1,1),
TITLE NVARCHAR(50) PRIMARY KEY)

INSERT INTO TBL_CATEGORY_CLASSES VALUES ('JOB')
INSERT INTO TBL_CATEGORY_CLASSES VALUES ('ALERT')
INSERT INTO TBL_CATEGORY_CLASSES VALUES ('OPERATOR')

CREATE TABLE TBL_CATEGORIES(
ID INT UNIQUE IDENTITY(1,1),
TITLE NVARCHAR(50) NOT NULL,
CATEGORY_CLASS_ID INT NOT NULL REFERENCES TBL_CATEGORY_CLASSES(ID),
CATEGORY_TYPE_ID INT NOT NULL REFERENCES TBL_CATEGORY_TYPES(ID),
PRIMARY KEY (TITLE,CATEGORY_CLASS_ID))

CREATE TABLE TBL_SQL_JOBS(
ID INT PRIMARY KEY IDENTITY(1,1),
TITLE NVARCHAR(200) NOT NULL,
INSTANCE_ID INT NOT NULL REFERENCES TBL_INSTANCES(ID),
CATEGORY_ID INT NOT NULL REFERENCES TBL_CATEGORIES(ID),
RUN_STATUS NVARCHAR(10) NOT NULL,
RUN_DATE NVARCHAR(10) NOT NULL,
RUN_TIME NVARCHAR(8) NOT NULL,
RUN_DURATION NVARCHAR(8) NOT NULL,
MAINTENANCE_PLAN_NAME NVARCHAR(200),
RUN_INTERVAL NVARCHAR(20) DEFAULT '',
IS_ENABLED BIT NOT NULL DEFAULT 1)

SET IDENTITY_INSERT TBL_CATEGORIES ON
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (0,'[Uncategorized (Local)]',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (2,'[Uncategorized (Multi-Server)]',1,2,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (98,'[Uncategorized]',2,3,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (99,'[Uncategorized]',3,3,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (8,'Data Collector',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (7,'Database Engine Tuning Advisor',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (3,'Database Maintenance',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (5,'Full-Text',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (1,'Jobs from MSX',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (6,'Log Shipping',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (18,'REPL-Alert Response',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (16,'REPL-Checkup',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (10,'REPL-Distribution',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (11,'REPL-Distribution Cleanup',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (12,'REPL-History Cleanup',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (20,'Replication',2,3,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (13,'REPL-LogReader',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (14,'REPL-Merge',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (19,'REPL-QueueReader',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (15,'REPL-Snapshot',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (17,'REPL-Subscription Cleanup',1,1,1)
SET IDENTITY_INSERT TBL_CATEGORIES OFF

CREATE TABLE TBL_APPLICATIONS(
ID INT UNIQUE IDENTITY(1,1),
TITLE NVARCHAR(200) NOT NULL,
HUB_SITE NVARCHAR(50) DEFAULT '',
PRIMARY KEY (TITLE,HUB_SITE))

CREATE TABLE TBL_DATABASES(
ID INT UNIQUE IDENTITY(1,1),
INSTANCE_ID INT NOT NULL REFERENCES TBL_INSTANCES(ID),
TITLE NVARCHAR(200) NOT NULL,
APPLICATION_ID INT REFERENCES TBL_APPLICATIONS(ID),
MANAGED BIT NOT NULL DEFAULT 0,
CONNECTIONSTRING NVARCHAR(MAX) NOT NULL DEFAULT '',
RESOURCES_USED NVARCHAR(MAX) NOT NULL DEFAULT '',
RESOURCE_THRESHOLD NVARCHAR(MAX) NOT NULL DEFAULT '',
LAST_SEEN DATETIME NOT NULL DEFAULT GETDATE(),
PRIMARY KEY (INSTANCE_ID,TITLE))

CREATE TABLE TBL_DATABASE_JOBS(
ID INT UNIQUE IDENTITY(1,1),
DATABASE_ID INT NOT NULL REFERENCES TBL_DATABASES(ID),
JOB_ID INT NOT NULL REFERENCES TBL_SQL_JOBS(ID),
PRIMARY KEY (DATABASE_ID,JOB_ID))
</code>```

And here is some sample results from the query I posted earlier. Keep in mind the script can be run against any instance as long as you used MSDB because it uses all system generated tables and views:

http://img253.imageshack.us/i/resultsn.jpg/

Just do be clear about my objectives for this package. JOB_NAME, CATEGORY_ID, RUN_DATE, RUN_TIME, RUN_DURATION and PLAN_NAME all go into the TBL_SQL_JOBS table. The PLAN_DETAILS column will do nothing for nulls (as will PLAN_NAME) but for populated records it will remove the "Databases: " string and split the comma delimited database names. Then it needs to check the DB names from the split against the TBL_Databases table (previously populated) and grab the corresponding ID. Then, combined with the ID of the current job record we are processing (think the "lookup job ID" part of the last task of the package) we add those records to the TBL_DATABASE_JOBS table separately. The end result being a table with a list of unique DBs and a table with a list of Historical Job info and a table between that provides a 1 job: to many DB relationship. Thanks again.

答:
It sounds like your script solution is the way to go.  And, you don't need to worry about inserting from the script.

You can limit the role of the script to only handle the splitting of the comma-separated list.  The output of the script would be one row for each item in the list.

The important step is to set the script component to be asynchronous.  Asynchronous mode with enable the component to output a different number of rows than the input number of rows.  After creating a new script component as a Transformation, edit the component.  Select the Input and Output Properties, select Output 0.  Change the value for the SynchronousInputID property to None.  Expand The Output 0 branch and Add Columns to the Output Columns branch.  The columns will comprise the rows that exit the component.  Finally, add your script code that will create a row for each item in your comma-separated list.

Once you can export one row for each item in the list, add a destination just like any other destination.

Body:
This is my 1st post, so be gentle :). I am building an SSIS package to collect information on jobs running throughout the enterprise at work. The goal is to have tables filled with info on Servers, Instance, DBs, Jobs, and their relations to each other. Ideally I will use merge commands to update or insert where necessary but for now it just inserts. Here is an overview of my package (keep your mind out of the gutter please :P):

(restrictions on hyperlinks for new users means you need to replace the + signs with "t"s in my links

http://img262.imageshack.us/i/package.jpg/

The 1st Data Flow task pulls in a list of instances to check from a flat text file and stores them in a record set. The foreach loop then goes through each one of them and changes my source Connection Manager's Connection string appropriately. Inside the loop we are going through 1 instance at a time. The "Process Server" Dataflow task is used to find the Server name and add it to the Destination DB if it doesn't exist, either way it also stores the Server ID and Name in package variables. The "Process Instance" does the same as the above but for the Instance instead. The "Collect DB Data" Task then uses those package variables to insert all the DBs in that instance as records with the Package variables mentioned above for Foreign keys. Once that is Finished we move on to the "Collect Job Data" task (hopefully the final task for this package). The following is the contents of the last task:

http://img809.imageshack.us/i/dataflow.png/

So inside of this task this is what I'm doing so far. I use a query to collect Job Info with Maintenance plan data 1st. Here is the Query for the OLE DB Source:

--WRITTEN BY MAXWELL WALLACE
--THE PURPOSE OF THIS QUERY IS TO COLLECT INFORMATION ABOUT JOBS AND MAINTENANCE PLANS
--RUNNING ON A PARTICULAR INSTANCE. IT COLLECTS NAMES, STATUSES, RUN TIMES AND DATES
--AS WELL AS DATABASES AFFECTED AND MAINTENANCE PLAN NAMES IF APPLICABLE.
SELECT B.NAME AS JOB_NAME, B.CATEGORY_ID,
--RUN_STATUS CODE GETS TRANSLATED INTO ENGLISH
CASE A.RUN_STATUS
WHEN 0 THEN 'Failed'
WHEN 1 THEN 'Succeeded'
WHEN 2 THEN 'Retry'
WHEN 3 THEN 'Canceled'
ELSE 'Unknown'
END AS RUN_STATUS,
--CONVERT INTEGER DATE INTO SOMETHING MORE LEGABLE
SUBSTRING(CAST(A.RUN_DATE AS CHAR(8)),5,2) + '/' +
RIGHT(CAST(A.RUN_DATE AS CHAR(8)),2) + '/' +
LEFT(CAST(A.RUN_DATE AS CHAR(8)),4) AS RUN_DATE,
--CONVERT RUN_TIME INTO SOMETHING MORE RECONGNIZABLE (HH:MM:SS)
LEFT(RIGHT('000000' + CAST(A.RUN_TIME AS VARCHAR(10)),6),2) + ':' +
SUBSTRING(RIGHT('000000' + CAST(A.RUN_TIME AS VARCHAR(10)),6),3,2) + ':' +
RIGHT(RIGHT('000000' + CAST(A.RUN_TIME AS VARCHAR(10)),6),2) AS RUN_TIME,
--CONVERT RUN_DURATION INTO SOMETHING MORE RECONGNIZABLE (HH:MM:SS)
LEFT(RIGHT('000000' + CAST(A.RUN_DURATION AS VARCHAR(10)),6),2) + ':' +
SUBSTRING(RIGHT('000000' + CAST(A.RUN_DURATION AS VARCHAR(10)),6),3,2) + ':' +
RIGHT(RIGHT('000000' + CAST(A.RUN_DURATION AS VARCHAR(10)),6),2) AS RUN_DURATION,
--THE FOLLOWING SUBQUERY IS USED TO EXTRAPOLATE DETAILS FOR THE JOB IN IT'S MAINTENANCE PLAN (IF IT HAS 1)
--THE TOP 1 MAKES SURE WE GET ONLY 1 RECORD SINCE THIS IS A 1 TO MANY RELATIONSHIP
--THE LINE3 COLUMN CONTAINS DETAILS ABOUT THE TASK THAT WAS RUN
(SELECT TOP 1 E.LINE3
    --WE START WITH THE SYSMAINTPLAN_LOG BECAUSE WE CAN (IN A WAY) JOIN IT TO OUR OUTER JOIN THROUGH THE PLAN_ID IN THE WHERE CLAUSE
    FROM MSDB.DBO.SYSMAINTPLAN_LOG AS D
    --NOW IT IS POSSIBLE TO, BY EXTENTION, JOIN SYSMAINTPLAN_LOGDETAIL TO THE OUTER JOIN AS WELL THROUGH ITS 1 TO 1 RELATIONSHIP WITH SYSMAINTPLAN_LOG
    INNER JOIN MSDB.DBO.SYSMAINTPLAN_LOGDETAIL AS E ON E.TASK_DETAIL_ID = D.TASK_DETAIL_ID
    --THE 1ST PART OF THE WHERE RETURNS ONLY RECORDS OF THE SAME PLAN_ID, ESSENTIALLY "JOINING" THIS RECORD TO THE OUTER JOIN THE IN MAIN QUERY
    --THE 2ND PART MAKES SURE THE FIELD WE ACTUALLY CARE ABOUT CONTAINS MEANINGFUL DATA
    WHERE D.PLAN_ID = C.PLAN_ID AND E.LINE3 != '') AS PLAN_DETAILS,
--THE FOLLOWING SUBQUERY RETURNS THE NAME OF THE MAINTENANCE PLAN (IF IT HAS 1)
(SELECT F.NAME
    FROM MSDB.DBO.SYSMAINTPLAN_PLANS AS F --THIS IS A SYSTEM GENERATED VIEW
    --LIKE THE ABOVE SUBQUERY, THIS WHERE ESSENTIALLY "JOINS" THIS RECORD TO THE OUTER JOIN IN THE MAIN QUERY
    WHERE F.ID = C.PLAN_ID) AS PLAN_NAME
FROM MSDB.DBO.SYSJOBHISTORY AS A
INNER JOIN MSDB.DBO.SYSJOBS AS B ON A.JOB_ID = B.JOB_ID
--THIS OUTTER JOIN ATTACHES PLAN_IDS OF MAINTENANCE PLANS TO JOBS THAT HAVE THEM
LEFT OUTER JOIN SYSMAINTPLAN_SUBPLANS AS C ON C.JOB_ID = B.JOB_ID
--ONLY RETURN ENABLED JOBS
WHERE B.[ENABLED] = 1
--AND ONLY JOB OUTCOMES, NOT EACH STEP
AND A.STEP_ID = 0
--AND ONLY COMPLETED JOBS
AND A.RUN_STATUS <> 4
--SORTED BY LATEST DATE 1ST
ORDER BY A.RUN_DATE DESC

Sorry, but for some reason this forum doesn't preserve my formatting. Anyway, after that I add the package variable Instance ID as a column to assist in inserting these records with this Foreign Key. I convert some strings to unicode which is neither here nor there and then I do a conditional split on Records With a maintenance plan and records without. For records without I can Simply insert them into the destination and they are done! For records with a Maintenance plan however, the chance of them having a connection to one or more DB is very high. So, 1st I insert the job record into the Job table (exactly as I do with records not within a maintenance plan) and then I do a lookup to find the record I just inserted's ID. Next I take the field from my query that has a comma separated list of DBs affected by the Maintenance plan this job is part of and separate it into a VB.Net ArrayList. I then assign that ArrayList to a Package Variable.

This is the part I'm at. Obviously my next step is to create some sort of loop using the Job ID I just looked up and running through each variable in the ArrayList to insert them 1 at a time into the DB/Job Pivot table. Problem is I am not aware of how I can do a loop within a Data Flow Task and I can't think of a good way to move the pivot table insert out of this task. I might be able to do this with a script component but I am unsure how to preform inserts from within the script task (should I even consider that?). I am proficient with VB.Net and C# as well as TSQL so I can investigate any method of implementing this. Thanks in advance for your help. Cheers!

PS. Here is the table structure I am inserting the data into:

CREATE TABLE TBL_SERVERS(
ID INT UNIQUE IDENTITY(1,1),
TITLE NVARCHAR(50) PRIMARY KEY,
CLUSTER_NAME NVARCHAR(50) DEFAULT '',
RESOURCES_USED NVARCHAR(20) DEFAULT '',
RESOURCE_THRESHOLD NVARCHAR(20) DEFAULT '',
IS_CLUSTERED BIT NOT NULL DEFAULT 0)

CREATE TABLE TBL_INSTANCES(
ID INT UNIQUE IDENTITY(1,1),
SERVER_ID INT NOT NULL REFERENCES TBL_SERVERS(ID),
TITLE NVARCHAR(50) NOT NULL,
PRIMARY KEY (SERVER_ID,TITLE))

CREATE TABLE TBL_CATEGORY_TYPES(
ID INT UNIQUE IDENTITY(1,1),
TITLE NVARCHAR(50) PRIMARY KEY)

INSERT INTO TBL_CATEGORY_TYPES VALUES ('LOCAL')
INSERT INTO TBL_CATEGORY_TYPES VALUES ('MULTISERVER')
INSERT INTO TBL_CATEGORY_TYPES VALUES ('NONE')

CREATE TABLE TBL_CATEGORY_CLASSES(
ID INT UNIQUE IDENTITY(1,1),
TITLE NVARCHAR(50) PRIMARY KEY)

INSERT INTO TBL_CATEGORY_CLASSES VALUES ('JOB')
INSERT INTO TBL_CATEGORY_CLASSES VALUES ('ALERT')
INSERT INTO TBL_CATEGORY_CLASSES VALUES ('OPERATOR')

CREATE TABLE TBL_CATEGORIES(
ID INT UNIQUE IDENTITY(1,1),
TITLE NVARCHAR(50) NOT NULL,
CATEGORY_CLASS_ID INT NOT NULL REFERENCES TBL_CATEGORY_CLASSES(ID),
CATEGORY_TYPE_ID INT NOT NULL REFERENCES TBL_CATEGORY_TYPES(ID),
PRIMARY KEY (TITLE,CATEGORY_CLASS_ID))

CREATE TABLE TBL_SQL_JOBS(
ID INT PRIMARY KEY IDENTITY(1,1),
TITLE NVARCHAR(200) NOT NULL,
INSTANCE_ID INT NOT NULL REFERENCES TBL_INSTANCES(ID),
CATEGORY_ID INT NOT NULL REFERENCES TBL_CATEGORIES(ID),
RUN_STATUS NVARCHAR(10) NOT NULL,
RUN_DATE NVARCHAR(10) NOT NULL,
RUN_TIME NVARCHAR(8) NOT NULL,
RUN_DURATION NVARCHAR(8) NOT NULL,
MAINTENANCE_PLAN_NAME NVARCHAR(200),
RUN_INTERVAL NVARCHAR(20) DEFAULT '',
IS_ENABLED BIT NOT NULL DEFAULT 1)

SET IDENTITY_INSERT TBL_CATEGORIES ON
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (0,'[Uncategorized (Local)]',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (2,'[Uncategorized (Multi-Server)]',1,2,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (98,'[Uncategorized]',2,3,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (99,'[Uncategorized]',3,3,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (8,'Data Collector',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (7,'Database Engine Tuning Advisor',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (3,'Database Maintenance',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (5,'Full-Text',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (1,'Jobs from MSX',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (6,'Log Shipping',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (18,'REPL-Alert Response',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (16,'REPL-Checkup',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (10,'REPL-Distribution',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (11,'REPL-Distribution Cleanup',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (12,'REPL-History Cleanup',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (20,'Replication',2,3,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (13,'REPL-LogReader',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (14,'REPL-Merge',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (19,'REPL-QueueReader',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (15,'REPL-Snapshot',1,1,1)
INSERT INTO TBL_CATEGORIES (ID,TITLE,CATEGORY_CLASS_ID,CATEGORY_TYPE_ID,CATEGORY_GROUP_ID) VALUES (17,'REPL-Subscription Cleanup',1,1,1)
SET IDENTITY_INSERT TBL_CATEGORIES OFF

CREATE TABLE TBL_APPLICATIONS(
ID INT UNIQUE IDENTITY(1,1),
TITLE NVARCHAR(200) NOT NULL,
HUB_SITE NVARCHAR(50) DEFAULT '',
PRIMARY KEY (TITLE,HUB_SITE))

CREATE TABLE TBL_DATABASES(
ID INT UNIQUE IDENTITY(1,1),
INSTANCE_ID INT NOT NULL REFERENCES TBL_INSTANCES(ID),
TITLE NVARCHAR(200) NOT NULL,
APPLICATION_ID INT REFERENCES TBL_APPLICATIONS(ID),
MANAGED BIT NOT NULL DEFAULT 0,
CONNECTIONSTRING NVARCHAR(MAX) NOT NULL DEFAULT '',
RESOURCES_USED NVARCHAR(MAX) NOT NULL DEFAULT '',
RESOURCE_THRESHOLD NVARCHAR(MAX) NOT NULL DEFAULT '',
LAST_SEEN DATETIME NOT NULL DEFAULT GETDATE(),
PRIMARY KEY (INSTANCE_ID,TITLE))

CREATE TABLE TBL_DATABASE_JOBS(
ID INT UNIQUE IDENTITY(1,1),
DATABASE_ID INT NOT NULL REFERENCES TBL_DATABASES(ID),
JOB_ID INT NOT NULL REFERENCES TBL_SQL_JOBS(ID),
PRIMARY KEY (DATABASE_ID,JOB_ID))

And here is some sample results from the query I posted earlier. Keep in mind the script can be run against any instance as long as you used MSDB because it uses all system generated tables and views:

http://img253.imageshack.us/i/resultsn.jpg/

Just do be clear about my objectives for this package. JOB_NAME, CATEGORY_ID, RUN_DATE, RUN_TIME, RUN_DURATION and PLAN_NAME all go into the TBL_SQL_JOBS table. The PLAN_DETAILS column will do nothing for nulls (as will PLAN_NAME) but for populated records it will remove the "Databases: " string and split the comma delimited database names. Then it needs to check the DB names from the split against the TBL_Databases table (previously populated) and grab the corresponding ID. Then, combined with the ID of the current job record we are processing (think the "lookup job ID" part of the last task of the package) we add those records to the TBL_DATABASE_JOBS table separately. The end result being a table with a list of unique DBs and a table with a list of Historical Job info and a table between that provides a 1 job: to many DB relationship. Thanks again.


问:
How to check if UNIXTimeStamp is mid day time or evening in php
I have the JSON Response which contains DateTime in UNIXTIMESTAMP. I would like find that the time in JSON Response is of Mid Day time or evening.

Lets say below is the response and I want to check CloseTime weather it is mid day time or evening time.

```<code>{
    "gameName": "NUMBERS",
    "id": "16440",
    "status": "RESULTS_AVAILABLE",
    "closeTime": "1491927615000"
}
</code>```

答:
This might work for you..decode your json and  assign closeTime to $timestamp

```<code> <?php
    $timestamp = 1491927615000;
    $date = date('H', $timestamp);

    if($date < 12){

         echo "good morning";

       }elseif($date > 11 && $date < 18){

         echo "good afternoon";

       }elseif($date > 17){

         echo "good evening";

       }

    ?>
</code>```

http://codepad.org/SCJw32FL

Body:
I have the JSON Response which contains DateTime in UNIXTIMESTAMP. I would like find that the time in JSON Response is of Mid Day time or evening.

Lets say below is the response and I want to check CloseTime weather it is mid day time or evening time.

{
    "gameName": "NUMBERS",
    "id": "16440",
    "status": "RESULTS_AVAILABLE",
    "closeTime": "1491927615000"
}

Body:
This might work for you..decode your json and  assign closeTime to $timestamp

 <?php
    $timestamp = 1491927615000;
    $date = date('H', $timestamp);

    if($date < 12){

         echo "good morning";

       }elseif($date > 11 && $date < 18){

         echo "good afternoon";

       }elseif($date > 17){

         echo "good evening";

       }

    ?>

http://codepad.org/SCJw32FL


问:
multiple alarm clock in javascript using dynamic generated input elements in javascript
I am trying to make a web page which will allow to set multiple alarms using dynamic element creation property of javascript but I'm not able to get the values of these multiple elements and create a alert on that time.
This is my code so far</p>

```<code><div id="TextBoxContainer">
     <!--Textboxes will be added here -->
</div>
<br />
<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />

<script type="text/javascript">
        var room = 0;
        var i = 0;
        function GetDynamicTextBox(){
            return '<div>Alarm ' + room +':</div><input type="number"style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" placeholder="hour" id="a'+room+'" /><input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" /><input type="date" style="margin:auto;text-align:center; width:200px; padding:10px"><input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
        }
        function AddTextBox() {
            var div = document.createElement('DIV');
            div.innerHTML = GetDynamicTextBox("");
            document.getElementById("TextBoxContainer").appendChild(div);
        }

        function RemoveTextBox(div) {
            document.getElementById("TextBoxContainer").removeChild(div.parentNode);
        }

        function RecreateDynamicTextboxes() {
                var html = "";
                html += "<div>" + GetDynamicTextBox() + "</div>";
                document.getElementById("TextBoxContainer").innerHTML = html;
                room++;
        }
        window.onload = RecreateDynamicTextboxes;

        function AddAlarm(values){
            var hour = document.getElementById('');
            var minute = document.getElementById('');
            var date = document.getElementById('');
        }
</script>
</code>```

答:
So far I'm able to generate a alert when the values match the system time but I don't know how to delete the array value when an element is deleted. I am not able to do it. This is my code so far:</p>

```<code><script type="text/javascript">

        var snd = new Audio("clock.mp3"); // buffers automatically when created
        // Get
        if (localStorage.getItem("test")) {
            data = JSON.parse(localStorage.getItem("test"));
        } else {
            // No data, start with an empty array
            data = [];
        }

        var today = new Date();
        var d = today.getDay();
        var h = today.getHours();
        var m = today.getMinutes();
        //since page reloads then we will just check it first for the data
        function check() {
        //current system values
        console.log("inside check");
        //if time found in the array the create a alert and delete that array object
        for(var i = 0; i < data.length; i++) {
            var today = new Date();
            var d = today.getDay();
            var h = today.getHours();
            var m = today.getMinutes();

            if (data[i].hours == h && data[i].minutes == m && data[i].dates == d ) {
                data.splice(i,1);
                localStorage["test"] = JSON.stringify(data);
                snd.play();
                alert("Wake Up Man ! Alarm is over ");
                }
            }
            if((data.length)>0)
            {
                setTimeout(check, 1000);
            }

        }
        //we do not want to run the loop everytime so we will use day to check
        for(var i =0 ; i< data.length; i++)
        {
            if((data[i].dates == d) && (data[i].hours >= h) && (data[i].minutes >= m) )
            {
                check();
            }
        }

        console.log(data);

        var room = 1;
        //var data = [];
        var i = 0;
        function GetDynamicTextBox(){

            var date = new Date();
            var h = date.getHours();
            var m = date.getMinutes();
            var d = date.getDay();

            return '<div>Alarm ' + room +':</div><input type="number" style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" value ='+h+' placeholder="hour" id="a'+room+'" /> <input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" value ='+m+' /> <select id="c'+room+'" style="margin:auto; width:150px; padding:10px; color: black" required> <option value="1">Monday</option> <option value="2">Tuesday</option> <option value="3">Wednesday</option> <option value="4">Thursday</option> <option value="5">Friday</option> <option value="6">Saturday</option> <option value="0">Sunday</option> </select> <input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
        }
        function AddTextBox() {
            room++;
            var div = document.createElement('DIV');
            div.innerHTML = GetDynamicTextBox("");
            document.getElementById("TextBoxContainer").appendChild(div);
        }

        function RemoveTextBox(div) {
            document.getElementById("TextBoxContainer").removeChild(div.parentNode);
        }

        function RecreateDynamicTextboxes() {
                var html = "";
                html += "<div>" + GetDynamicTextBox() + "</div>";
                document.getElementById("TextBoxContainer").innerHTML = html;
        }
        window.onload = RecreateDynamicTextboxes;

        function AddAlarm(values){
            var hour = $('#a'+values).val();
            var minute = $('#b'+values).val();
            var date = $('#c'+values).val();

            //get the current time and date
            var today = new Date();

            //current system values
            var d = today.getDay();
            var h = today.getHours();
            var m = today.getMinutes();

            //first check that whether a same date present in the array or not then push it
            var found = -1;
            for(var i = 0; i < data.length; i++) {
                if (data[i].hours == hour && data[i].minutes == minute && data[i].dates == date ) {
                    found = 0;
                    break;
                }
            }

            //if value does not present then push it into the array
            if(found == -1)
            {
                data.push({hours: hour, minutes: minute, dates: date});
                //storing it into localstorage
                localStorage.setItem("test", JSON.stringify(data));
            }
            else
            {
                alert("Same value Exists");
            }

            //console.log(data);

            function check() {
                //current system values
                //console.log("inside check");
                //if time found in the array the create a alert and delete that array object
                for(var i = 0; i < data.length; i++) {
                    var today = new Date();
                    var d = today.getDay();
                    var h = today.getHours();
                    var m = today.getMinutes();

                    if (data[i].hours == h && data[i].minutes == m && data[i].dates == d ) {
                        data.splice(i,1);
                        snd.play();
                        alert("Wake Up Man ! Alarm is over ");
                    }
                }
                if((data.length)>0)
                {
                    setTimeout(check, 1000);
                }

            }
            //we do not want to run the loop everytime so we will use day to check
            for(var i =0 ; i< data.length; i++)
            {
                if((data[i].dates == d) && (data[i].hours >= h) && (data[i].minutes >= m))
                {
                    check();
                }
            }
        }

        </script>
</code>```

Body:
I am trying to make a web page which will allow to set multiple alarms using dynamic element creation property of javascript but I'm not able to get the values of these multiple elements and create a alert on that time.
This is my code so far

<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />

Body:
So far I'm able to generate a alert when the values match the system time but I don't know how to delete the array value when an element is deleted. I am not able to do it. This is my code so far:

<script type="text/javascript">

        var snd = new Audio("clock.mp3"); // buffers automatically when created
        // Get
        if (localStorage.getItem("test")) {
            data = JSON.parse(localStorage.getItem("test"));
        } else {
            // No data, start with an empty array
            data = [];
        }

        var today = new Date();
        var d = today.getDay();
        var h = today.getHours();
        var m = today.getMinutes();
        //since page reloads then we will just check it first for the data
        function check() {
        //current system values
        console.log("inside check");
        //if time found in the array the create a alert and delete that array object
        for(var i = 0; i < data.length; i++) {
            var today = new Date();
            var d = today.getDay();
            var h = today.getHours();
            var m = today.getMinutes();

            if (data[i].hours == h && data[i].minutes == m && data[i].dates == d ) {
                data.splice(i,1);
                localStorage["test"] = JSON.stringify(data);
                snd.play();
                alert("Wake Up Man ! Alarm is over ");
                }
            }
            if((data.length)>0)
            {
                setTimeout(check, 1000);
            }

        }
        //we do not want to run the loop everytime so we will use day to check
        for(var i =0 ; i< data.length; i++)
        {
            if((data[i].dates == d) && (data[i].hours >= h) && (data[i].minutes >= m) )
            {
                check();
            }
        }

        console.log(data);

        var room = 1;
        //var data = [];
        var i = 0;
        function GetDynamicTextBox(){

            var date = new Date();
            var h = date.getHours();
            var m = date.getMinutes();
            var d = date.getDay();

            return '<div>Alarm ' + room +':</div><input type="number" style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" value ='+h+' placeholder="hour" id="a'+room+'" /> <input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" value ='+m+' /> <select id="c'+room+'" style="margin:auto; width:150px; padding:10px; color: black" required> <option value="1">Monday</option> <option value="2">Tuesday</option> <option value="3">Wednesday</option> <option value="4">Thursday</option> <option value="5">Friday</option> <option value="6">Saturday</option> <option value="0">Sunday</option> </select> <input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
        }
        function AddTextBox() {
            room++;
            var div = document.createElement('DIV');
            div.innerHTML = GetDynamicTextBox("");
            document.getElementById("TextBoxContainer").appendChild(div);
        }

        function RemoveTextBox(div) {
            document.getElementById("TextBoxContainer").removeChild(div.parentNode);
        }

        function RecreateDynamicTextboxes() {
                var html = "";
                html += "<div>" + GetDynamicTextBox() + "</div>";
                document.getElementById("TextBoxContainer").innerHTML = html;
        }
        window.onload = RecreateDynamicTextboxes;

        function AddAlarm(values){
            var hour = $('#a'+values).val();
            var minute = $('#b'+values).val();
            var date = $('#c'+values).val();

            //get the current time and date
            var today = new Date();

            //current system values
            var d = today.getDay();
            var h = today.getHours();
            var m = today.getMinutes();

            //first check that whether a same date present in the array or not then push it
            var found = -1;
            for(var i = 0; i < data.length; i++) {
                if (data[i].hours == hour && data[i].minutes == minute && data[i].dates == date ) {
                    found = 0;
                    break;
                }
            }

            //if value does not present then push it into the array
            if(found == -1)
            {
                data.push({hours: hour, minutes: minute, dates: date});
                //storing it into localstorage
                localStorage.setItem("test", JSON.stringify(data));
            }
            else
            {
                alert("Same value Exists");
            }

            //console.log(data);

            function check() {
                //current system values
                //console.log("inside check");
                //if time found in the array the create a alert and delete that array object
                for(var i = 0; i < data.length; i++) {
                    var today = new Date();
                    var d = today.getDay();
                    var h = today.getHours();
                    var m = today.getMinutes();

                    if (data[i].hours == h && data[i].minutes == m && data[i].dates == d ) {
                        data.splice(i,1);
                        snd.play();
                        alert("Wake Up Man ! Alarm is over ");
                    }
                }
                if((data.length)>0)
                {
                    setTimeout(check, 1000);
                }

            }
            //we do not want to run the loop everytime so we will use day to check
            for(var i =0 ; i< data.length; i++)
            {
                if((data[i].dates == d) && (data[i].hours >= h) && (data[i].minutes >= m))
                {
                    check();
                }
            }
        }

        </script>


问:
odoo 10 action menu button
Am working with Odoo 10 and I want two things:

Insert a button in the menu specified in the picture.

Then the button,

Will execute some code that operates with the selected objects.

I would like to know how to insert the button and the best approach for point number 2.

答:
Following is the way to create a new menu in More menu.

1. Need to create new action for that menu.

```<code><record model="ir.actions.act_window" id="action_id_1">
    <field name="name">action.name</field>
    <field name="view_id" ref="view_id_1"/>
    <field name="domain">[]</field>
    <field name="context">{}</field>
    <field name="res_model">Current Model</field>
    <field name="view_type">form</field>
    <field name="view_mode">form</field>
    <field name="target">new</field>
</record>
</code>```

2. Binding events to action

The available type of events are following

client_print_multi (print from a list or form)

client_action_multi (action from a list or form)

client_action_relate (action from a list or form)

tree_but_open (action on the items of a tree)

You have to use the client_action_multi and define the action_id in value. See below example.

```<code><record model="ir.values" id="ir_value_id">
    <field name="model_id" ref="module_name.model_<model_name>" />
    <field name="name">Create Delivery</field>
    <field name="key2">client_action_multi</field>
    <field name="value" eval="'ir.actions.act_window,' + str(ref('action_id_1'))" />
    <field name="key">action</field>
    <field name="model">model.name</field>
</record>
</code>```

So, At the end you have new option under the more menu.

Title: odoo 10 action menu button

Body:
Following is the way to create a new menu in More menu.

1. Need to create new action for that menu.

<record model="ir.actions.act_window" id="action_id_1">
    <field name="name">action.name</field>
    <field name="view_id" ref="view_id_1"/>
    <field name="domain">[]</field>
    <field name="context">{}</field>
    <field name="res_model">Current Model</field>
    <field name="view_type">form</field>
    <field name="view_mode">form</field>
    <field name="target">new</field>
</record>

2. Binding events to action

The available type of events are following

client_print_multi (print from a list or form)

client_action_multi (action from a list or form)

client_action_relate (action from a list or form)

tree_but_open (action on the items of a tree)

You have to use the client_action_multi and define the action_id in value. See below example.

<record model="ir.values" id="ir_value_id">
    <field name="model_id" ref="module_name.model_<model_name>" />
    <field name="name">Create Delivery</field>
    <field name="key2">client_action_multi</field>
    <field name="value" eval="'ir.actions.act_window,' + str(ref('action_id_1'))" />
    <field name="key">action</field>
    <field name="model">model.name</field>
</record>

So, At the end you have new option under the more menu.


问:
Erro on Ninject: Sequence contains no elements
This error appear just when I publish on Azure server:

Sequence contains no elements

I'm not sure this error is because of Ninject. I've tried all the tips with similar errors, but it seems that is a generic error.

I tried to run the same code on several machines and this error does not happen only when the public Azure.

If you have gone through something and can help, thank you very much.

Stack Trace:

```<code>[InvalidOperationException: Sequence contains no elements]
   System.Linq.Enumerable.Single(IEnumerable`1 source) +311
   Ninject.Web.Mvc.NinjectMvcHttpApplicationPlugin.Start() +44
   Ninject.Web.Common.Bootstrapper.<Initialize>b__0(INinjectHttpApplicationPlugin c) +8
   Ninject.Infrastructure.Language.ExtensionsForIEnumerableOfT.Map(IEnumerable`1 series, Action`1 action) +130
   Ninject.Web.Common.Bootstrapper.Initialize(Func`1 createKernelCallback) +140
   Splora.SploraV1.UI.Web.NinjectWebCommon.Start() +102

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
   System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +192
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +136
   WebActivatorEx.BaseActivationMethodAttribute.InvokeMethod() +73
   WebActivatorEx.ActivationManager.RunActivationMethods(Boolean designerMode) +350
   WebActivatorEx.ActivationManager.Run() +78

[InvalidOperationException: The pre-application start initialization method Run on type WebActivatorEx.ActivationManager threw an exception with the following error message: Exception has been thrown by the target of an invocation..]
   System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection`1 methods, Func`1 setHostingEnvironmentCultures) +613
   System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) +141
   System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +159
   System.Web.Compilation.BuildManager.ExecutePreAppStart() +157
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +656

[HttpException (0x80004005): The pre-application start initialization method Run on type WebActivatorEx.ActivationManager threw an exception with the following error message: Exception has been thrown by the target of an invocation..]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +4531288
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +94
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +191
</code>```

NinjectWebCommon.cs:

```<code>private static readonly Bootstrapper bootstrapper = new Bootstrapper();

    /// <summary>
    /// Starts the application
    /// </summary>
    public static void Start()
    {
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
        DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
       bootstrapper.Initialize(CreateKernel);
    }

    /// <summary>
    /// Stops the application.
    /// </summary>
    public static void Stop()
    {
        bootstrapper.ShutDown();
    }

    /// <summary>
    /// Creates the kernel that will manage your application.
    /// </summary>
    /// <returns>The created kernel.</returns>
    private static IKernel CreateKernel()
    {
        var kernel = RegisterServices();
        try
        {
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

            return kernel;
        }
        catch
        {
            kernel.Dispose();
            throw;
        }
    }

    private static StandardKernel RegisterServices()
    {
        return new Container().GetModules();
    }
</code>```

答:
In my case this issue was happening in UAT but not on my machine.

The reason for that is I changed namespace and as result in release folder there were two libraries with the same class.

I had to clean up release folder and publish it again.
All good now

Body:
This error appear just when I publish on Azure server:

Sequence contains no elements

I'm not sure this error is because of Ninject. I've tried all the tips with similar errors, but it seems that is a generic error.

I tried to run the same code on several machines and this error does not happen only when the public Azure.

If you have gone through something and can help, thank you very much.

Stack Trace:

[InvalidOperationException: Sequence contains no elements]
   System.Linq.Enumerable.Single(IEnumerable`1 source) +311
   Ninject.Web.Mvc.NinjectMvcHttpApplicationPlugin.Start() +44
   Ninject.Web.Common.Bootstrapper.<Initialize>b__0(INinjectHttpApplicationPlugin c) +8
   Ninject.Infrastructure.Language.ExtensionsForIEnumerableOfT.Map(IEnumerable`1 series, Action`1 action) +130
   Ninject.Web.Common.Bootstrapper.Initialize(Func`1 createKernelCallback) +140
   Splora.SploraV1.UI.Web.NinjectWebCommon.Start() +102

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
   System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +192
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +136
   WebActivatorEx.BaseActivationMethodAttribute.InvokeMethod() +73
   WebActivatorEx.ActivationManager.RunActivationMethods(Boolean designerMode) +350
   WebActivatorEx.ActivationManager.Run() +78

[InvalidOperationException: The pre-application start initialization method Run on type WebActivatorEx.ActivationManager threw an exception with the following error message: Exception has been thrown by the target of an invocation..]
   System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection`1 methods, Func`1 setHostingEnvironmentCultures) +613
   System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) +141
   System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +159
   System.Web.Compilation.BuildManager.ExecutePreAppStart() +157
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +656

[HttpException (0x80004005): The pre-application start initialization method Run on type WebActivatorEx.ActivationManager threw an exception with the following error message: Exception has been thrown by the target of an invocation..]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +4531288
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +94
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +191

NinjectWebCommon.cs:

private static readonly Bootstrapper bootstrapper = new Bootstrapper();

    ///
    /// Starts the application
    ///
    public static void Start()
    {
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
        DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
       bootstrapper.Initialize(CreateKernel);
    }

    ///
    /// Stops the application.
    ///
    public static void Stop()
    {
        bootstrapper.ShutDown();
    }

    ///
    /// Creates the kernel that will manage your application.
    ///
    /// <returns>The created kernel.</returns>
    private static IKernel CreateKernel()
    {
        var kernel = RegisterServices();
        try
        {
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

            return kernel;
        }
        catch
        {
            kernel.Dispose();
            throw;
        }
    }

    private static StandardKernel RegisterServices()
    {
        return new Container().GetModules();
    }


答:
1) You need to create custom cell class with image, like this:

```<code>class MyCustomCell: UITableViewCell {
    //...some vars?
    @IBOutlet myImageView: UIImageView!
    //...some vars?
}
</code>```

2) Set it for you table view. You can find a lot of tutorials for points 1 and 2 in google, SO etc. Example: Add custom cells for tableView

3) Install KingFisher for caching images. Kingfisher. It will let your tableview to have smooth scrolling. (note: you can use any analog like SDWebImage)

To install:

1) pod 'Kingfisher', '~> 3.0' in your pod file

2) pod install in terminal

3) import Kingfisher in your swift-code file

4) Use it in your table view:

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "myCustomCell", for: indexPath) as! MyCustomCell
    let row = indexPath.row

    // ...other vars?

    let imageURL = URL(string: self.posts[row].downloadURL)
    cell.myImageView.kf.setImage(with: imageURL) // Using kingfisher for caching and viewing.
     // next time, when you will use image with this URL, it will be taken from cache.

    // ...other vars?

    return cell
}
</code>```

Hope it helps

Title: How do I add am image in a TableView from URL

Body:
I am confused about how I can take the DownloadURL which is a link and turn it into an image and add it in my tableview cell? I have an imageview in my storyboard and dont know how to connect it to the tableview cell either. Thanks!

override func viewDidLoad() { super.viewDidLoad()

    let ref = FIRDatabase.database().reference().child("Posts")

    ref.observeSingleEvent(of: .value, with: { snapshot in

        print(snapshot.childrenCount)

        for rest in snapshot.children.allObjects as! [FIRDataSnapshot] {

            guard let value = rest.value as? Dictionary<String,Any> else { continue }

            guard let  downloadURL = value["DownloadURL"] as? String else { continue }

            let post = postStruct(title: title, date: date, author: author, article: article, downloadURL: downloadURL)

            self.posts.append(post)

        }

        self.posts = self.posts.reversed(); self.tableView.reloadData()

    })

}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return posts.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")

    let label1 = cell?.viewWithTag(1) as! UILabel
    label1.text = posts[indexPath.row].title
    return cell!
}

Body:
1) You need to create custom cell class with image, like this:

class MyCustomCell: UITableViewCell {
    //...some vars?
    @IBOutlet myImageView: UIImageView!
    //...some vars?
}

2) Set it for you table view. You can find a lot of tutorials for points 1 and 2 in google, SO etc. Example: Add custom cells for tableView

3) Install KingFisher for caching images. Kingfisher. It will let your tableview to have smooth scrolling. (note: you can use any analog like SDWebImage)

To install:

1) pod 'Kingfisher', '~> 3.0' in your pod file

2) pod install in terminal

3) import Kingfisher in your swift-code file

4) Use it in your table view:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "myCustomCell", for: indexPath) as! MyCustomCell
    let row = indexPath.row

    // ...other vars?

    let imageURL = URL(string: self.posts[row].downloadURL)
    cell.myImageView.kf.setImage(with: imageURL) // Using kingfisher for caching and viewing.
     // next time, when you will use image with this URL, it will be taken from cache.

    // ...other vars?

    return cell
}

Hope it helps


问:
Include zero frequencies in frequency table for Likert data
I have a dataset with responses to a Likert item on a 9pt scale. I would like to create a frequency table (and barplot) of the data but some values on the scale never occur in my dataset, so table() removes that value from the frequency table. I would like it instead to present the value with a frequency of 0. That is, given the following dataset

```<code># Assume a 5pt Likert scale for ease of example
data <- c(1, 1, 2, 1, 4, 4, 5)
</code>```

I would like to get the following frequency table without having to manually insert a column named 3 with the value 0.

```<code>1 2 3 4 5
3 1 0 2 1
</code>```

I'm new to R, so maybe I've overlooked something basic, but I haven't come across a function or option that gives the desired result.

答:
If you want to quickly calculate the counts or proportions for multiple likert items and get your output in a data.frame, you may like the function psych::response.frequencies in the psych package.

Lets create some data (note that there are no 9s):

```<code>df <- data.frame(item1 = sample(1:7, 2000, replace = TRUE),
                 item2 = sample(1:7, 2000, replace = TRUE),
                 item3 = sample(1:7, 2000, replace = TRUE))
</code>```

If you want to calculate the proportion in each category

```<code>psych::response.frequencies(df, max = 1000, uniqueitems = 1:9)
</code>```

you get the following:

```<code>           1      2     3      4      5      6      7 8 9 miss
item1 0.1450 0.1435 0.139 0.1325 0.1380 0.1605 0.1415 0 0    0
item2 0.1535 0.1315 0.126 0.1505 0.1535 0.1400 0.1450 0 0    0
item3 0.1320 0.1505 0.132 0.1465 0.1425 0.1535 0.1430 0 0    0
</code>```

If you want counts, you can multiply by the sample size:

```<code>psych::response.frequencies(df, max = 1000, uniqueitems = 1:9) * nrow(df)
</code>```

You get the following:

```<code>        1   2   3   4   5   6   7 8 9 miss
item1 290 287 278 265 276 321 283 0 0    0
item2 307 263 252 301 307 280 290 0 0    0
item3 264 301 264 293 285 307 286 0 0    0
</code>```

A few notes:

the default max is 10. Thus, if you have more than 10 response options, you'll have issues. Otherwise, in your case, and many Likert item cases, you could omit the max argument.

uniqueitems specifies the possible values. If all your values were present in at least one item, then this would be inferred from the data.

I think the function only works with numeric data. So if you have your likert categories coded "Strongly disagree", etc. it wont work.

Body:
I have a dataset with responses to a Likert item on a 9pt scale. I would like to create a frequency table (and barplot) of the data but some values on the scale never occur in my dataset, so table() removes that value from the frequency table. I would like it instead to present the value with a frequency of 0. That is, given the following dataset

# Assume a 5pt Likert scale for ease of example
data <- c(1, 1, 2, 1, 4, 4, 5)

I would like to get the following frequency table without having to manually insert a column named 3 with the value 0.

1 2 3 4 5
3 1 0 2 1

I'm new to R, so maybe I've overlooked something basic, but I haven't come across a function or option that gives the desired result.

Body:
If you want to quickly calculate the counts or proportions for multiple likert items and get your output in a data.frame, you may like the function psych::response.frequencies in the psych package.

Lets create some data (note that there are no 9s):

df <- data.frame(item1 = sample(1:7, 2000, replace = TRUE),
                 item2 = sample(1:7, 2000, replace = TRUE),
                 item3 = sample(1:7, 2000, replace = TRUE))

If you want to calculate the proportion in each category

psych::response.frequencies(df, max = 1000, uniqueitems = 1:9)

you get the following:

           1      2     3      4      5      6      7 8 9 miss
item1 0.1450 0.1435 0.139 0.1325 0.1380 0.1605 0.1415 0 0    0
item2 0.1535 0.1315 0.126 0.1505 0.1535 0.1400 0.1450 0 0    0
item3 0.1320 0.1505 0.132 0.1465 0.1425 0.1535 0.1430 0 0    0

If you want counts, you can multiply by the sample size:

psych::response.frequencies(df, max = 1000, uniqueitems = 1:9) * nrow(df)

You get the following:

        1   2   3   4   5   6   7 8 9 miss
item1 290 287 278 265 276 321 283 0 0    0
item2 307 263 252 301 307 280 290 0 0    0
item3 264 301 264 293 285 307 286 0 0    0

A few notes:

the default max is 10. Thus, if you have more than 10 response options, you'll have issues. Otherwise, in your case, and many Likert item cases, you could omit the max argument.

uniqueitems specifies the possible values. If all your values were present in at least one item, then this would be inferred from the data.

I think the function only works with numeric data. So if you have your likert categories coded "Strongly disagree", etc. it wont work.


问:
How can I separate templates by data in jbuilder
I want to make following data with jbuilder.

How can I make jbuilder separated?

```<code>data: [{
  type: "top"
  logo: "logo.png"
  title: "title"
  },{
  type: "nav"
  background: "bg.png"
  content: "<div> Welcome </div>"
  },{
  type: "footer"
  content: "Copyright: xx"
  }
]
</code>```

I did it like that, but couldn't running

data.jbuilder

```<code>json.set! :result do
  json.array! data do |item|
     case item.type
     when 'top'
       json.partial! '_top', item: item
     when 'nav'
       json.partial! '_nav', item: item
     when 'footer'
       json.partial! '_footer', item: item
     else
       return nil
  end
end
</code>```

_top.jbuilder

```<code>json.logo   item.logo
json.title  item.title
</code>```

_nav.jbuilder

```<code>json.background item.background
json.content    item.content
</code>```

_footer.jbuilder

```<code>json.content item.content
</code>```

How can I solve the problem?

答:
when you call partials, _ is not needed you just give the path if it is in different folder or name if in same folder.

try

```<code>json.partial! 'top', item: item
json.partial! 'nav', item: item
json.partial! 'footer', item: item
</code>```

Body:
I want to make following data with jbuilder.

How can I make jbuilder separated?

data: [{
  type: "top"
  logo: "logo.png"
  title: "title"
  },{
  type: "nav"
  background: "bg.png"
  content: "
 Welcome
"
  },{
  type: "footer"
  content: "Copyright: xx"
  }
]

I did it like that, but couldn't running

data.jbuilder

json.set! :result do
  json.array! data do |item|
     case item.type
     when 'top'
       json.partial! '_top', item: item
     when 'nav'
       json.partial! '_nav', item: item
     when 'footer'
       json.partial! '_footer', item: item
     else
       return nil
  end
end

_top.jbuilder

json.logo   item.logo
json.title  item.title

_nav.jbuilder

json.background item.background
json.content    item.content

_footer.jbuilder

json.content item.content

How can I solve the problem?

Body:
when you call partials, _ is not needed you just give the path if it is in different folder or name if in same folder.

try

json.partial! 'top', item: item
json.partial! 'nav', item: item
json.partial! 'footer', item: item


问:
Rare occurrence of null injected field
Rarely, when I try accessing an injected field, the application would crash because that accessed field is null. I have no way to reproduce it, and it's not supposed to happen to begin with.
Any idea why this might happen and how to avoid it?

The field is being injected inside a fragment:

```<code>public class MyFragment extends Fragment {
    @Inject StubManager mStubManager;
    ....
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Application.getAppComponent().inject(this);
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        ....
        menu.findItem(R.id.item_id)
            .setEnabled(!mStubManager.isRunning());
    }
}
</code>```

The app component looks like the below, and is initialized in the Application class:

```<code>@Singleton
@Component(modules = {
        MyModule.class
})
public interface AppComponent {
    StubManager stubManager();

    void inject(MyFragment target);
}
</code>```

答:
Move your inject call to onAttach before calling super.

As David mentioned in the comments, if you have a non-@Nullable field that Dagger successfully injects most of the time, then it is likely not a Dagger bug, but rather one of Android lifecycle or Java multithreading. I'm guessing the former is happening here.

Though I don't have a doubtless reason offhand in code or docs, anecdotally there seem to be cases where the options menu is prepared before onCreate, and a cursory glance at the Android open source code for FragmentManager and Activity (as well as the menu docs) suggest that the Fragment isn't guaranteed to be created and that the options menu is considered open as long as the action bar is visible. If so, this would be a case where you would read a null value from your injected field. You might be able to test this by opening your options menu (if you aren't using ActionBar), using the home button or clicking a notification to navigate away from your Activity, and then returning to your Activity such that it has to reattach the Fragment and recreate its options menu. This might be more reproducible if you enable the development option "Don't keep activities" to simulate memory pressure that would cause your Activity to be destroyed, which would otherwise be relatively random and infrequent on users' devices.

I suspect your injection may simply be happening too late: Note that onAttach is called before onCreate is called, such that the docs for dagger.android suggest injecting in onAttach before the call to super.onAttach. This is the earliest, most consistent, and recommended place to perform injection in Fragments, particularly if your Fragment inherits from a base Fragment class: if the superclass has any @Inject fields that it uses in onCreate or onAttach, those will also be null with your inject call where it is.

Title: Rare occurrence of null injected field

Body:
Rarely, when I try accessing an injected field, the application would crash because that accessed field is null. I have no way to reproduce it, and it's not supposed to happen to begin with.
Any idea why this might happen and how to avoid it?

The field is being injected inside a fragment:

public class MyFragment extends Fragment {
    @Inject StubManager mStubManager;
    ....
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Application.getAppComponent().inject(this);
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        ....
        menu.findItem(R.id.item_id)
            .setEnabled(!mStubManager.isRunning());
    }
}

The app component looks like the below, and is initialized in the Application class:

@Singleton
@Component(modules = {
        MyModule.class
})
public interface AppComponent {
    StubManager stubManager();

    void inject(MyFragment target);
}