问:
CSS style priority
Before this question, I already search 'CSS priority' and I found following

The priority of inline style like
 is higher than class blue which define color:blue; And this rule is still work between tag and inline, i.e., inline has higher priority than tag.

Now I encounter a obstacle that I don't know. Here, simple example of my case.

First there are
s

```<code><div></div>
<div></div>
<div></div>
</code>```

and they have CSS

```<code>div { backgorund:url('path') no-repeat; }
div:nth-child(2n+1) { background-position: 'position A'; }
</code>```

Now first and third
 has same background image at position A.
Then I tried change third
's background like

```<code><div></div>
<div></div>
<div style="background-position: 'position B';"></div>
</code>```

But the inline style of third
 is not applied, still the :nth-child's style occupy it. (third
 still has background-position with 'position A')

I want to change third
's background image that only has different
background position. How can I do this?

(I know the priority of inline style is always higher than any others. But
 in this case, it does not work)

for specification here my code

```<code>#courseList li { background:url('path') no-repeat; }
#courseList > li:nth-child(2n+1) {
    background-position:-5px -438px;
}
#courseList > li:nth-child(2n+2) {
    background-position:-187px -438px;
}

<ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li>
        <div style='background-position:-551px -438px;'></div>
    </li>
</ul>
</code>```

答:
```<code>#courseList li { background:url('path') no-repeat; }
#courseList > li:nth-child(2n+1) {
    background-position:-5px -438px;
}
#courseList > li:nth-child(2n+2) {
    background-position:-187px -438px;
}

<ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li>
        <div style='background-position:-551px -438px;'></div>
    </li>
</ul>
</code>```

Here is my case. The inline style of div do not work since
 is not target I think.

And, next code follow the rule

```<code>#courseList li { background:url('path') no-repeat; }
#courseList > li:nth-child(2n+1) {
    background-position:-5px -438px;
}
#courseList > li:nth-child(2n+2) {
    background-position:-187px -438px;
}

<ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li style='background-position:-551px -438px;'>
        <div></div>
    </li>
</ul>
</code>```

Title: CSS style priority

Body:
Before this question, I already search 'CSS priority' and I found following

The priority of inline style like
 is higher than class blue which define color:blue; And this rule is still work between tag and inline, i.e., inline has higher priority than tag.

Now I encounter a obstacle that I don't know. Here, simple example of my case.

First there are
s

and they have CSS

div { backgorund:url('path') no-repeat; }
div:nth-child(2n+1) { background-position: 'position A'; }

Now first and third
 has same background image at position A.
Then I tried change third
's background like

But the inline style of third
 is not applied, still the :nth-child's style occupy it. (third
 still has background-position with 'position A')

I want to change third
's background image that only has different
background position. How can I do this?

(I know the priority of inline style is always higher than any others. But
 in this case, it does not work)

for specification here my code

#courseList li { background:url('path') no-repeat; }
#courseList > li:nth-child(2n+1) {
    background-position:-5px -438px;
}
#courseList > li:nth-child(2n+2) {
    background-position:-187px -438px;
}

Body:
#courseList li { background:url('path') no-repeat; }
#courseList > li:nth-child(2n+1) {
    background-position:-5px -438px;
}
#courseList > li:nth-child(2n+2) {
    background-position:-187px -438px;
}

<ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li>
        <div style='background-position:-551px -438px;'></div>
    </li>
</ul>

Here is my case. The inline style of div do not work since <div> is not target I think.

And, next code follow the rule

#courseList li { background:url('path') no-repeat; }
#courseList > li:nth-child(2n+1) {
    background-position:-5px -438px;
}
#courseList > li:nth-child(2n+2) {
    background-position:-187px -438px;
}

<ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li style='background-position:-551px -438px;'>
        <div></div>
    </li>
</ul>


来源: stackexchange

问:
Trace where print is occurring?
Given the novice that I am, I have an extremely naive question, apologies for that

I modified certain core .py files by adding print. Now it's printing a bunch of lines and I'm unable to trace what file I added the print statement. How can I find out what line / file the print is occurring, so that i can go back and remove it? It happens when code executes import sklearn.

I tried debugging and going back to certain files I had modified and searching for print statement, but not able to trace back.

答:
OPTIONS:

Remember what you were trying to do when you went in and edited the .py files in the first place,  and that might give you a recollection of which files you changed.

Search the python folder and sort by date stamp.   The py files that have been recently changed are LIKELY to be the ones you edited.  Then go in and revert the edit you made

Flush your Python install and reinstall from scratch. (The 'Nuke the planet from orbit, it's the only way to be sure' option)

In general its a BAD idea to go in and edit the core Python files unless you REALLY know what you are doing.

ContentLicense: CC BY-SA 3.0

Title: Trace where print is occurring?


问:
Can Spring MVC or Spring Boot work with Amazon Alexa?
I am trying to develop a small Alexa skill with Spring Boot and Spring MVC framework via https (I tried both of them).
However when I tried to add alexa-skill-kit maven dependency in pom.xml. I got so many different kinds of errors.
like 'servlet.init() error','can't create a child container' etc.
It seems like the newest version of Alexa Java SDK has some conflicts with my spring set up...
Is there anyone who has set up amazon alexa with spring successfully?
Or a 'Hello world' sample project shared in github?
Thank you.</p>

答:
I've developed a alexa skill using spring boot successfully. Here's the dependency definition from my pom.xml.

```<code><dependency>
    <groupId>com.amazon.alexa</groupId>
    <artifactId>alexa-skills-kit</artifactId>
    <version>1.3.1</version>
    <exclusions>
        <exclusion>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
        </exclusion>
        <exclusion>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
        </exclusion>
    </exclusions>
</dependency>
</code>```

Hopefully that clears up your issues.

Also to use the sdks message objects you can add the bean

```<code>@Bean
Module speechletRequestModule() {
    return new SpeechletRequestModule();
}
</code>```

and then a request mapping in your rest controller is simply

```<code>@RequestMapping(value = "skills/myskill", method = RequestMethod.POST)
public SpeechletResponseEnvelope handle(@RequestBody final SpeechletRequestEnvelope speechletRequestEnvelope) {}
</code>```

Body:
I've developed a alexa skill using spring boot successfully. Here's the dependency definition from my pom.xml.

<dependency>
    <groupId>com.amazon.alexa</groupId>
    <artifactId>alexa-skills-kit</artifactId>
    <version>1.3.1</version>
    <exclusions>
        <exclusion>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
        </exclusion>
        <exclusion>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Hopefully that clears up your issues.

Also to use the sdks message objects you can add the bean

@Bean
Module speechletRequestModule() {
    return new SpeechletRequestModule();
}

and then a request mapping in your rest controller is simply

@RequestMapping(value = "skills/myskill", method = RequestMethod.POST)
public SpeechletResponseEnvelope handle(@RequestBody final SpeechletRequestEnvelope speechletRequestEnvelope) {}


问:
WPF ListView selected item problem
I have a ListView control with TextBox and Button inside the ListViewItem, my problem is that when you enter into a textbox the row doesn't select. If you want to select a row you have to click somewhere in the row where there is no control.

How can I make the row automaticly select when I click or enter into a child control of a row ?

I tried this on the button click event, but without any luck :

```<code>        DependencyObject dep = (DependencyObject)sender;
        while ((dep != null) && !(dep is ListViewItem))
        {
            dep = VisualTreeHelper.GetParent(dep);
        }

        if (dep != null)
        {
            lvRoutes.SelectedItem = (ListViewItem)dep;
        }
</code>```

It always keep the first row selected.

Thank in advance.

答:
try using attached properties

```<code>public static class ItemSelector
{
    public static DependencyProperty MakeSelectionProperty =
        DependencyProperty.RegisterAttached("MakeSelection",
        typeof(bool?),
        typeof(ItemSelector),
        new PropertyMetadata(null, OnMakeSelectionPropertyChanged));

    public static DependencyProperty ItemsControlProperty =
        DependencyProperty.RegisterAttached("ItemsControl",
        typeof(ItemsControl),
        typeof(ItemSelector));

    public static void SetMakeSelection(
        DependencyObject d, bool value)
    {
        d.SetValue(MakeSelectionProperty, value);
    }

    public static void SetItemsControl(
        DependencyObject d, ItemsControl value)
    {
        d.SetValue(ItemsControlProperty, value);
    }

    private static void OnMakeSelectionPropertyChanged(
        DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var itemsControl = d.GetValue(ItemsControlProperty)
            as ItemsControl;
        if (itemsControl == null)
            return;
        ((ListBoxItem) itemsControl.ContainerFromElement(d))
            .IsSelected = true;
    }
</code>```

and heres its use

```<code><ListView ItemsSource="{Binding}" SelectionMode="Single">
<ListView.ItemTemplate>
  <DataTemplate>
    <TextBox Text="{Binding SomeText}"
             w:ItemSelector.MakeSelection="{Binding RelativeSource=
                {RelativeSource Self}, Path=IsFocused}"
             w:ItemSelector.ItemsControl="{Binding RelativeSource=
                {RelativeSource FindAncestor, AncestorType=
                    {x:Type ListView}}}" Margin="10" />
  </DataTemplate>
</ListView.ItemTemplate>
</code>```

ContentLicense: CC BY-SA 2.5

Title: WPF ListView selected item problem

Body:
I have a ListView control with TextBox and Button inside the ListViewItem, my problem is that when you enter into a textbox the row doesn't select. If you want to select a row you have to click somewhere in the row where there is no control.

How can I make the row automaticly select when I click or enter into a child control of a row ?

I tried this on the button click event, but without any luck :

        DependencyObject dep = (DependencyObject)sender;
        while ((dep != null) && !(dep is ListViewItem))
        {
            dep = VisualTreeHelper.GetParent(dep);
        }

        if (dep != null)
        {
            lvRoutes.SelectedItem = (ListViewItem)dep;
        }

It always keep the first row selected.

Thank in advance.

Body:
try using attached properties

public static class ItemSelector
{
    public static DependencyProperty MakeSelectionProperty =
        DependencyProperty.RegisterAttached("MakeSelection",
        typeof(bool?),
        typeof(ItemSelector),
        new PropertyMetadata(null, OnMakeSelectionPropertyChanged));

    public static DependencyProperty ItemsControlProperty =
        DependencyProperty.RegisterAttached("ItemsControl",
        typeof(ItemsControl),
        typeof(ItemSelector));

    public static void SetMakeSelection(
        DependencyObject d, bool value)
    {
        d.SetValue(MakeSelectionProperty, value);
    }

    public static void SetItemsControl(
        DependencyObject d, ItemsControl value)
    {
        d.SetValue(ItemsControlProperty, value);
    }

    private static void OnMakeSelectionPropertyChanged(
        DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var itemsControl = d.GetValue(ItemsControlProperty)
            as ItemsControl;
        if (itemsControl == null)
            return;
        ((ListBoxItem) itemsControl.ContainerFromElement(d))
            .IsSelected = true;
    }

and heres its use

<ListView ItemsSource="{Binding}" SelectionMode="Single">
<ListView.ItemTemplate>
  <DataTemplate>
    <TextBox Text="{Binding SomeText}"
             w:ItemSelector.MakeSelection="{Binding RelativeSource=
                {RelativeSource Self}, Path=IsFocused}"
             w:ItemSelector.ItemsControl="{Binding RelativeSource=
                {RelativeSource FindAncestor, AncestorType=
                    {x:Type ListView}}}" Margin="10" />
  </DataTemplate>
</ListView.ItemTemplate>


问:
Why isn't my error being returned in my express response?
I have a default error handler setup in my express application as so.

```<code> app.use(function unhandledErrorHandler(err, req, res, next) {
   res.status(err.status || 500).json({
     error: err
   });
 });
</code>```

However whenever I call a route and an error is thrown I am getting a response that looks like this.

```<code>{
  "error": {}
}
</code>```

Can someone help my understand why express is returning my error as an empty Object?

答:
The reason Error instances are being shown as empty objects is because the normal properties (e.g. .message, .stack, etc.) on an Error object are not set as enumerable and JSON.stringify() (used by res.json()) ignores non-enumerable properties.

If you just want to send the message portion (not including the stack trace), you could do this instead:

```<code>res.json({ error: err.message });
</code>```

or

```<code>res.json({ error: { message: err.message } });
</code>```

Otherwise if you want to include other custom, enumerable properties that may have been tacked onto the Error instance, you could make .message enumerable and then use the same code you're using now:

```<code>Object.defineProperty(err, 'message', { enumerable: true });
res.json({ error: err });
</code>```

Body:
I have a default error handler setup in my express application as so.

 app.use(function unhandledErrorHandler(err, req, res, next) {
   res.status(err.status || 500).json({
     error: err
   });
 });

However whenever I call a route and an error is thrown I am getting a response that looks like this.

{
  "error": {}
}

Can someone help my understand why express is returning my error as an empty Object?

Body:
The reason Error instances are being shown as empty objects is because the normal properties (e.g. .message, .stack, etc.) on an Error object are not set as enumerable and JSON.stringify() (used by res.json()) ignores non-enumerable properties.

If you just want to send the message portion (not including the stack trace), you could do this instead:

res.json({ error: err.message });

or

res.json({ error: { message: err.message } });

Otherwise if you want to include other custom, enumerable properties that may have been tacked onto the Error instance, you could make .message enumerable and then use the same code you're using now:

Object.defineProperty(err, 'message', { enumerable: true });
res.json({ error: err });


问:
No Oracle DataSource in Entity Data Model Wizard
I am using ODP.NET and I need generate ORM from my database.

I have installed:

Visual Studio 2010 Ultimate

ODAC1120250Beta_EntityFramework_x64.zip

In Server Expolorer I can see Data Source for Oracle Database and I am able connect to remote oracle server and run queries.

When I add ADO.NET Entity Data Model and wanna generate code from database I cannot see Data source for oracle like in Server Explorer.

Do you need download some extra stuff to run entity framework with ODP.NET?

EDIT:

Use latest version of ODP.NET

Uncheck Oracle services for Microsoft Transaction Server .... During the installation

答:
I was able to solve this by unintall the ODP.NET and reinstall back. During the installing process, the ODP.NET will detect visual studio and be sure the CHECK the option. After that, the oracle managed driver appear in Data Provider.

Hope this help.


问:
How to call stored procedure and display what it returns in mvc 4 without using EF
I'm new to mvc and I'm trying to figure out how to connect to a database, call a stored procedure and display what it returns without using entity framework. I created a textbox and it suppose to filter the display based on user input (i.e. id number). There are a lot of columns in the db that needed to be displayed so if possible I prefer not creating a variable for each column in my Model. I've seen an example where they used model as strongly typed System.Data.DataTable, which works, but I ran into an issue since view doesn't allow two models and there for I couldn't use my textbox.

Does anyone know how can this be done, and would be able to shed some light into this?

Thank you!

答:
Here is an example how you can call a stored procedure directly without first importing the stored procedure in Entity Framework.  Put a break point after the call to see what is being returned.  Of course change the stored procedure name in commandText. You may open DB connection other ways too. You may already be using DB in your project so you would know this.

```<code> using (YourDBContext db = new YourDBContext()) {

    Common.DbConnection conn = db.Database.Connection;
    ConnectionState initialState = conn.State;

    if (initialState != ConnectionState.Open) {
        conn.Open();
    }

    using (Common.DbCommand cmd = conn.CreateCommand()) {
        cmd.CommandText = "show master status";
        dynamic dr = cmd.ExecuteReader();
        int index = 0;
        List<string> columns = new List<string>();
        for (index = 0; index <= dr.FieldCount - 1; index++) {
            string columnName = dr.GetName(index);
        }
        if (dr.HasRows) {
            while (dr.Read()) {
                //'
                //'
            }
        }
        dr.Close();
      }
    }
</code>```

Body:
Here is an example how you can call a stored procedure directly without first importing the stored procedure in Entity Framework.  Put a break point after the call to see what is being returned.  Of course change the stored procedure name in commandText. You may open DB connection other ways too. You may already be using DB in your project so you would know this.

 using (YourDBContext db = new YourDBContext()) {

    Common.DbConnection conn = db.Database.Connection;
    ConnectionState initialState = conn.State;

    if (initialState != ConnectionState.Open) {
        conn.Open();
    }

    using (Common.DbCommand cmd = conn.CreateCommand()) {
        cmd.CommandText = "show master status";
        dynamic dr = cmd.ExecuteReader();
        int index = 0;
        List<string> columns = new List<string>();
        for (index = 0; index <= dr.FieldCount - 1; index++) {
            string columnName = dr.GetName(index);
        }
        if (dr.HasRows) {
            while (dr.Read()) {
                //'
                //'
            }
        }
        dr.Close();
      }
    }


问:
Different coloured fly out menu
I'm creating a custom master page for a MOSS publishing site. The designers have come up with this idea for the fly out menu...

alt text http://www.abbeylegal.com/Downloads/2009-01-06/gradient%20menu.jpg

which uses graduated/different backgrond and text colours for each menu option.

Does anyone know how to accomplish this?

答: If you want to be able to calculate a gradient of arbitrary colors, this page has some useful functions for handling hex color triplet calculations.</p>

OwnerDisplayName: Rob

Title: Different coloured fly out menu

OwnerDisplayName: Diodeus


问:
ASP.NET Session identifier
I'm trying to make a session code for each client on my site. In the Session_Start of the global asax I have this code:

```<code>private static long codSesion = 0;
private static object codSesionLocker = new object();
protected void Session_Start(object sender, EventArgs e)
{
    if (Session["CodSesion"] == null)
    {
        lock (codSesionLocker)
        {
            if (Session["CodSesion"] == null)
            {
                if (codSesion == 9999)
                    codSesion = 0;
                codSesion++;
                Session["CodSesion"] = codSesion;
            }
        }

    }
}
</code>```

When I monitor this it seems to be perfect. After some time of inactivity starts the problems. One of the thing that happens is that too many times starts over from 1 (without reaching 9999 and without IIS rebouting). And recently, even worst than taht: I'd used the codes 1 and 2. I stop using the server (leting the IIS without activity). After almost 1 hour (50 minutes) I tried again. The code the IIS gave me was 2 (in a different PC than the last code 2).

Please I'd realy apreciate any help with this.

答:
IIS recycles the worker process and there you'll lose the static value of codSession.

Save the information in a file or database to overcome this issue.

Title: ASP.NET Session identifier

Body:
I'm trying to make a session code for each client on my site. In the Session_Start of the global asax I have this code:

private static long codSesion = 0;
private static object codSesionLocker = new object();
protected void Session_Start(object sender, EventArgs e)
{
    if (Session["CodSesion"] == null)
    {
        lock (codSesionLocker)
        {
            if (Session["CodSesion"] == null)
            {
                if (codSesion == 9999)
                    codSesion = 0;
                codSesion++;
                Session["CodSesion"] = codSesion;
            }
        }

    }
}

When I monitor this it seems to be perfect. After some time of inactivity starts the problems. One of the thing that happens is that too many times starts over from 1 (without reaching 9999 and without IIS rebouting). And recently, even worst than taht: I'd used the codes 1 and 2. I stop using the server (leting the IIS without activity). After almost 1 hour (50 minutes) I tried again. The code the IIS gave me was 2 (in a different PC than the last code 2).

Please I'd realy apreciate any help with this.


问:
Unix Shell Script - AWK delimiter issue
I have following lines in a file. Please note I have intentionally kept the extra hash between 2 and 0 in the 2nd line.
File name : test.txt

```<code>Name#|#Age#|#Dept
AC#|#2#0#|#Science
BC#|#22#|#Commerce
</code>```

I am using awk to get the data in Dept column

```<code>awk -F "#|#" -v c="Dept" 'NR==1{for (i=1; i<=NF; i++) if ($i==c){p=i; break}; next} {print $p}' "test.txt" >> result.txt
</code>```

The result.txt shows me the following

```<code>|
Commerce
</code>```

The first line is coming as pipe because if the extra # in the first line.
Can anyone help on this

答:
If you desire to extract Dept in your content, here's a good choice you can choose from,

```<code> awk -F'#' 'NR>1{print $NF}' test.txt
</code>```

output:

```<code>Science
Commerce
</code>```

Title: Unix Shell Script - AWK delimiter issue

Body:
I have following lines in a file. Please note I have intentionally kept the extra hash between 2 and 0 in the 2nd line.
File name : test.txt

Name#|#Age#|#Dept
AC#|#2#0#|#Science
BC#|#22#|#Commerce

I am using awk to get the data in Dept column

awk -F "#|#" -v c="Dept" 'NR==1{for (i=1; i<=NF; i++) if ($i==c){p=i; break}; next} {print $p}' "test.txt" >> result.txt

The result.txt shows me the following

|
Commerce

The first line is coming as pipe because if the extra # in the first line.
Can anyone help on this

Body:
If you desire to extract Dept in your content, here's a good choice you can choose from,

 awk -F'#' 'NR>1{print $NF}' test.txt

output:

Science
Commerce


问:
How to Drill Down to a JList within a JScrollPane from another function
I am creating a JList like so:

```<code>JScrollPane scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
gbc_scrollPane.insets = new Insets(0, 0, 5, 5);
gbc_scrollPane.fill = GridBagConstraints.BOTH;
gbc_scrollPane.gridx = 0;
gbc_scrollPane.gridy = 1;
contentPanel.add(scrollPane, gbc_scrollPane);
{
    JList listAvail = new JList();
    listAvail.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    scrollPane.setViewportView(listAvail);
}
</code>```

and I'm trying to access it when a button is clicked:

```<code>JButton btnAdd = new JButton("Add ->");
btnAdd.addMouseListener(new MouseAdapter()
{
    @Override
    public void mouseClicked(MouseEvent arg0)
    {
        if (!listAvail.isSelectionEmpty())
        {
            int[] selects = listAvail.getSelectedIndices();
            for (int i = selects.length - 1; i >= 0; i--)
            {
                appliedM.add(0, availM.getElementAt(selects[i]));
                appliedFeatures.add(0, availFeatures.get(selects[i]));
                availFeatures.remove(availFeatures.get(selects[i]));
                availM.remove(selects[i]);
            }
        }
    }
});
</code>```

Of course, I'm getting an error saying "listAvail cannot be resolved" since it's out of the button's scope. Is there a getter method or a way to drill down to a specific component? I'm thinking something along the lines of:

```<code>contentPanel.scrollPane.listAvail
</code>```

There must be something I'm missing but I haven't seen anything like this in the docs.

Edit: I am asking specifically about drilling down to a swing component. This is not a generic variable scoping question and not an exact duplicate of the referenced question. This question has yet to be answered at the time of this edit.

答:
Your question boils down to -- how do I access an object reference when it is assigned to a very locally scoped variable, here the object being the JList, and the variable it's being assigned to is listAvail, a variable buried within its own set of curly braces (why?) within a method or constructor.

The solution -- get the variable declaration out of the local scope and make it instead an instance field of the class. e.g.,

```<code>public class MyClass {
    private JList listAvail = new JList(); // should be generic btw
</code>```

Another issue is here:

```<code>btnAdd.addMouseListener(new MouseAdapter() {....
</code>```

Don't use a MouseListener with a JButton where an ActionListener is much more appropriate. This has ramifications if you want the button's actions to be disabled when the button itself is disabled.

Body:
I am creating a JList like so:

JScrollPane scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
gbc_scrollPane.insets = new Insets(0, 0, 5, 5);
gbc_scrollPane.fill = GridBagConstraints.BOTH;
gbc_scrollPane.gridx = 0;
gbc_scrollPane.gridy = 1;
contentPanel.add(scrollPane, gbc_scrollPane);
{
    JList listAvail = new JList();
    listAvail.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    scrollPane.setViewportView(listAvail);
}

and I'm trying to access it when a button is clicked:

JButton btnAdd = new JButton("Add ->");
btnAdd.addMouseListener(new MouseAdapter()
{
    @Override
    public void mouseClicked(MouseEvent arg0)
    {
        if (!listAvail.isSelectionEmpty())
        {
            int[] selects = listAvail.getSelectedIndices();
            for (int i = selects.length - 1; i >= 0; i--)
            {
                appliedM.add(0, availM.getElementAt(selects[i]));
                appliedFeatures.add(0, availFeatures.get(selects[i]));
                availFeatures.remove(availFeatures.get(selects[i]));
                availM.remove(selects[i]);
            }
        }
    }
});

Of course, I'm getting an error saying "listAvail cannot be resolved" since it's out of the button's scope. Is there a getter method or a way to drill down to a specific component? I'm thinking something along the lines of:

contentPanel.scrollPane.listAvail

There must be something I'm missing but I haven't seen anything like this in the docs.

Edit: I am asking specifically about drilling down to a swing component. This is not a generic variable scoping question and not an exact duplicate of the referenced question. This question has yet to be answered at the time of this edit.

Body:
Your question boils down to -- how do I access an object reference when it is assigned to a very locally scoped variable, here the object being the JList, and the variable it's being assigned to is listAvail, a variable buried within its own set of curly braces (why?) within a method or constructor.

The solution -- get the variable declaration out of the local scope and make it instead an instance field of the class. e.g.,

public class MyClass {
    private JList listAvail = new JList(); // should be generic btw

Another issue is here:

btnAdd.addMouseListener(new MouseAdapter() {....

Don't use a MouseListener with a JButton where an ActionListener is much more appropriate. This has ramifications if you want the button's actions to be disabled when the button itself is disabled.


问:
Store metadata in CSV file
I understand that this would be a misuse of the CSV format. I do understand that more appropriate solution would be to export xls/xlsx file, or give user an OData end point and let them use power pivot to retrieve data. At this time I want to stick with CSV, because it is easier to implement.

I need to export a flat list of rows (a report) as a CSV file. At the same time I would like to include some metadata about the data. E.g. report title, generation date, and user.

Is there a neat way to accomplish both goals using CSV file format?

The intent usage for this file is to allow the user to open file in Excel and do data crunching.

One solution would be to break CSV into two sections: meta and data. E.g.

```<code>Title,Report Generation Date,Generated by User,,
Outstanding Jobs,5/5/2015,bkent@compusa.com,,
,,,,
Job Started, Estimated Completion, Description, Foo, Bar
9/3/2003,1/1/2006,"do something important""""",5,7
5/4/2007,2/2/2010,"do something else""""",3,12
</code>```

Or perhaps there is a "standard" extension to CSV format for this purpose?

Are there any practical issues with this approach?

答:
I recently ran into this problem, and found a "solution" that worked for me.

The idea is to encode the metadata in a singular cell in the first and/or the last row of the csv, encoded as json.

In your program, you can support this with a stack of decorator layers:

A standard component that reads the CSV file as a stream of raw data, that is, a stream where each row is an array of strings (the "cells"). For this layer, the first row, even if it contains the labels, is no different conceptually than all the other rows. Ideally each row would have the same number of cells, but this is not absolutely required.

An optional component that can look at the raw file and extract the contents of the last row, without reading the rest of the file.

An optional decorator/adapter that consumes the first row, parses the first cell of this row as json, and uses it as metadata.

An optional decorator/adapter that discards the last row, knowing that it contains metadata.

An optional decorator/adapter layer that consumes the first row as column labels, and then returns each row as an associative array/structure with the column labels as keys. The result of this is a stream of associative arrays, where the values are still strings.

An optional decorator/adapter layer that processes the cell contents. E.g. if one column contains json, it would parse those cells and turn them into objects. This layer behaves as a stream of objects, where the property values can be of various types.

I personally did this with PHP, but it should be possible in other languages / environments as well.

Notes

Why would you store some metadata at the end of the file, instead of the beginning?

A typical example would be the total row count, which might only be known after the rest of the file is completely written.

In fact this is the only use case so far where I used this solution. I named these files *.ncsv, indicating that the last row contains the row count. But still this is technically valid csv, if we accept rows with different cell count.

Of course whatever you do here, every piece of code that deals with this file will need to know about the special format you came up with.

Title: Store metadata in CSV file

Body:
I understand that this would be a misuse of the CSV format. I do understand that more appropriate solution would be to export xls/xlsx file, or give user an OData end point and let them use power pivot to retrieve data. At this time I want to stick with CSV, because it is easier to implement.

I need to export a flat list of rows (a report) as a CSV file. At the same time I would like to include some metadata about the data. E.g. report title, generation date, and user.

Is there a neat way to accomplish both goals using CSV file format?

The intent usage for this file is to allow the user to open file in Excel and do data crunching.

One solution would be to break CSV into two sections: meta and data. E.g.

Title,Report Generation Date,Generated by User,,
Outstanding Jobs,5/5/2015,bkent@compusa.com,,
,,,,
Job Started, Estimated Completion, Description, Foo, Bar
9/3/2003,1/1/2006,"do something important""""",5,7
5/4/2007,2/2/2010,"do something else""""",3,12

Or perhaps there is a "standard" extension to CSV format for this purpose?

Are there any practical issues with this approach?


问:
Using firebase to get multiple individual values given an array of keys
I'm trying to access multiple individual keys in Firebase. I'm using a promise-based function and a for loop to iterate over the given keys.

Here's the code:

```<code>function getFirebaseData(key_arr)
{
   var ref_obj,
       data_obj = {};
   return new Promise(function(resolve)
   {
       for(var i = 0; i < key_arr.length; i++)
       {
           key_str = key_arr[i];
           ref_obj = firebase.database().ref('path/'+key_str);
           ref_obj.on('value', function(snapshot)
           {
               data_obj[key_str] = snapshot.val();
           });
        }
        resolve(data_obj);
   });
}
</code>```

And then I run this as follows:

```<code>var key_arr = ['first_key', 'second_key', 'third_key'];
getFirebaseData(key_arr).then(function(result){console.log(result);});
</code>```

The problem is that the result I get isn't all three keys; I only get one. I guess this is because the code inside the for loop is asynchronous, so resolve only gives me the first key.

How can I rewrite this in such a way that I can wait for the for loop to complete and return the full result.

答:
```<code>function getFirebaseData(key_arr)
{
   var ref_obj,
       data_obj = {},
       promises = [];

   for(var i = 0; i < key_arr.length; i++)
   {
       key_str = key_arr[i];
       promises.push(
           new Promise(function(resolve)
           {
               ref_obj = firebase.database().ref('path/'+key_str);
               ref_obj.on('value', function(snapshot)
               {
                   data_obj[key_str] = snapshot.val();
               });
               resolve(data_obj);
           })
       )
   }

   return Promise.all(promises);
}
</code>```

Minimal code change can be this. Basically, instead for return promise right away. create promises array and resolve it by Promise.all.

Body:
I'm trying to access multiple individual keys in Firebase. I'm using a promise-based function and a for loop to iterate over the given keys.

Here's the code:

function getFirebaseData(key_arr)
{
   var ref_obj,
       data_obj = {};
   return new Promise(function(resolve)
   {
       for(var i = 0; i < key_arr.length; i++)
       {
           key_str = key_arr[i];
           ref_obj = firebase.database().ref('path/'+key_str);
           ref_obj.on('value', function(snapshot)
           {
               data_obj[key_str] = snapshot.val();
           });
        }
        resolve(data_obj);
   });
}

And then I run this as follows:

var key_arr = ['first_key', 'second_key', 'third_key'];
getFirebaseData(key_arr).then(function(result){console.log(result);});

The problem is that the result I get isn't all three keys; I only get one. I guess this is because the code inside the for loop is asynchronous, so resolve only gives me the first key.

How can I rewrite this in such a way that I can wait for the for loop to complete and return the full result.

Body:
function getFirebaseData(key_arr)
{
   var ref_obj,
       data_obj = {},
       promises = [];

   for(var i = 0; i < key_arr.length; i++)
   {
       key_str = key_arr[i];
       promises.push(
           new Promise(function(resolve)
           {
               ref_obj = firebase.database().ref('path/'+key_str);
               ref_obj.on('value', function(snapshot)
               {
                   data_obj[key_str] = snapshot.val();
               });
               resolve(data_obj);
           })
       )
   }

   return Promise.all(promises);
}

Minimal code change can be this. Basically, instead for return promise right away. create promises array and resolve it by Promise.all.


问:
command line: how to copy files with the same name into one directory without overwriting
I have the next folder structure:

```<code>C:\My Test\
C:\My Test\Folder_1\activity[1].json
C:\My Test\Folder_N\...\activity[1].json
</code>```

My goal is to:

copy all activity*json files to D:\Output\ directory to have something like this:

```<code>D:\Output\activity[%unique_variable%].json
D:\Output\activity[%unique_variable%].json
</code>```

My code:

```<code>for /R "C:\My Test\" %%f in (activity*.json) do ( copy %%f D:\Output\activity%random%.json )
</code>```

答:
```<code>setlocal enabledelayedexpansion
for /R "C:\My Test\" %%f in (activity*.json) do (
 call :select
 copy %%f D:\Output\activity!unique!.json
)

...
goto :eof

:select
set /a unique=%random%
if exist "D:\Output\activity!unique!.json" goto Select
goto :eof
</code>```

Your error is the way in which the batch parser works with code blocks (parenthesised lines of code) - by replacing any %var% with the value of that variable at the time. Hence %random% is replaced by a random value, but it's not re-chosen each iteration, only once at parse-time.

The crude way is to invoke delayedexpansion (ther are many articles on SO about this - use search) and replace %random% with !random! - but there is a small possibility that a particular random value may be chosen more than once in any particular run, or that the proposed new filename already exists.

Therefore, use a subroutine to choose the destination filename and check that the proposed name is unique within the subroutine (which allows gotos)

The downside is that you should skip over the subroutine when terminating your batch, so the rest of your batch is represented by ... and the goto :eof skips over the remaining code (see call /? from the prompt for documentation)

Another approach would be to assign the filename to be moved to a variable and move it within the subroutine. This has the advantage of not requiring delayedexpansion

```<code>for /R "C:\My Test\" %%f in (activity*.json) do (
 set "moveme=%%f"
 call :select
)

...
goto :eof

:select
set /a unique=%random%
if exist "D:\Output\activity%unique%.json" goto Select
copy "%moveme%" D:\Output\activity%unique%.json
goto :eof
</code>```

Body:
I have the next folder structure:

C:\My Test\
C:\My Test\Folder_1\activity[1].json
C:\My Test\Folder_N\...\activity[1].json

My goal is to:

copy all activity*json files to D:\Output\ directory to have something like this:

D:\Output\activity[%unique_variable%].json
D:\Output\activity[%unique_variable%].json

My code:

for /R "C:\My Test\" %%f in (activity*.json) do ( copy %%f D:\Output\activity%random%.json )

Body:
setlocal enabledelayedexpansion
for /R "C:\My Test\" %%f in (activity*.json) do (
 call :select
 copy %%f D:\Output\activity!unique!.json
)

...
goto :eof

:select
set /a unique=%random%
if exist "D:\Output\activity!unique!.json" goto Select
goto :eof

Your error is the way in which the batch parser works with code blocks (parenthesised lines of code) - by replacing any %var% with the value of that variable at the time. Hence %random% is replaced by a random value, but it's not re-chosen each iteration, only once at parse-time.

The crude way is to invoke delayedexpansion (ther are many articles on SO about this - use search) and replace %random% with !random! - but there is a small possibility that a particular random value may be chosen more than once in any particular run, or that the proposed new filename already exists.

Therefore, use a subroutine to choose the destination filename and check that the proposed name is unique within the subroutine (which allows gotos)

The downside is that you should skip over the subroutine when terminating your batch, so the rest of your batch is represented by ... and the goto :eof skips over the remaining code (see call /? from the prompt for documentation)

Another approach would be to assign the filename to be moved to a variable and move it within the subroutine. This has the advantage of not requiring delayedexpansion

for /R "C:\My Test\" %%f in (activity*.json) do (
 set "moveme=%%f"
 call :select
)

...
goto :eof

:select
set /a unique=%random%
if exist "D:\Output\activity%unique%.json" goto Select
copy "%moveme%" D:\Output\activity%unique%.json
goto :eof


问:
Convert mpf of mpmath to python float to support cvxopt
I am working on CVXOPT using qudratic programing problem.To create a G matrix, i need to differentiate the equation and compute the values.For differentiation i used Sympy.mpmath and lambda function as given below.I am getting the output in mpf format.Please suggest me a way to convert mpf to python float format that supports CVXOPT.
Thankyou</p>

```<code>dg1 = np.array([sp.mpmath.diff(lambda x1,x2,x3,x4,x5:0.75*x2/x4,(0.3,1.45,5,1.1,0.25),ft[i]) for i in range(n)])
>>>array([mpf('0.0'), mpf('0.68181818181818177'), mpf('0.0'),
   mpf('-0.89876033057851223'), mpf('0.0')], dtype=object)
</code>```

Body:
I am working on CVXOPT using qudratic programing problem.To create a G matrix, i need to differentiate the equation and compute the values.For differentiation i used Sympy.mpmath and lambda function as given below.I am getting the output in mpf format.Please suggest me a way to convert mpf to python float format that supports CVXOPT.
Thankyou

dg1 = np.array([sp.mpmath.diff(lambda x1,x2,x3,x4,x5:0.75*x2/x4,(0.3,1.45,5,1.1,0.25),ft[i]) for i in range(n)])
>>>array([mpf('0.0'), mpf('0.68181818181818177'), mpf('0.0'),
   mpf('-0.89876033057851223'), mpf('0.0')], dtype=object)

Body:
Wrap your sp.mpmath.diff call with float(...):

dg1 = np.array([float(sp.mpmath.diff(lambda x1,x2,x3,x4,x5:0.75*x2/x4,
                                     (0.3,1.45,5,1.1,0.25),ft[i])) for i in range(n)])

>>>array([0.        , 0.68181818, 0.        , -0.89876033, 0.        ])


问:
Arduino Bluetooth Serial
I keep getting weird problems working with the Arduino bluetooth, and before I go buy another I wanted to see if anyone had some insight.

Despite setting the Serial monitor and Arduino baud rates both to 9600, I get a mismatch and all the outputted characters are garbled. Additionally, when I try and connect from a Windows computer, using Serial.println("Words") gets caught in Serial.read(), and Serial.read() ends up returning "w" from "Words" (I know because changing the first letter results in a different value from Serial.read(). I'm very confused, and any help would be hugely appreciated.

答:
How did you connect the Bluetooth module ?

Sometimes the USB and Bluetooth module fight for control of the rx/tx.

If you use an Arduino mega, you could use the Serial1's tx/rx pins, or simply use SoftwareSerial library.

Title: Arduino Bluetooth Serial


问:
How to deploy ear file in to artifactory non maven application
We are trying to deploy the ear file in to my artifactory for non maven Java project.
here we are building the application using apache ant. please any one can suggest how can i deploy the my ear file in to artifactory using any scripts.writing something in to build.xml.</p>

答:
You can use the old maven-ant-tasks package to do the upload of the artifact and the pom file.
Check this: http://maven.apache.org/ant-tasks/

You can use the writepom function to define the pom and than create a target to execute the artifact:deploy task from the package.

It's really an easy setup approach.

Example:

```<code><target name="artifactory-deployment">
<artifact_jf:pom id="tmp.pom" groupid="${artifact.groupid}" artifactid="${artifact.name}" version="1.0" packaging="ear" name="${artifact.name}"         />
<artifact_jf:writepom pomRefId="tmp.pom" file="pom.xml"/>
<artifact_jf:deploy file="build/ears/artifact.ear">
    <remoteRepository url="http://localhost:8081/artifactory/libs-release-local">
        <authentication username="artifactory-username" password="artifactory-password" />
    </remoteRepository>
    <pom file="pom.xml" />
</artifact_jf:deploy>
</code>```

Body:
You can use the old maven-ant-tasks package to do the upload of the artifact and the pom file.
Check this: http://maven.apache.org/ant-tasks/

You can use the writepom function to define the pom and than create a target to execute the artifact:deploy task from the package.

It's really an easy setup approach.

Example:

<target name="artifactory-deployment">
<artifact_jf:pom id="tmp.pom" groupid="${artifact.groupid}" artifactid="${artifact.name}" version="1.0" packaging="ear" name="${artifact.name}"         />
<artifact_jf:writepom pomRefId="tmp.pom" file="pom.xml"/>
<artifact_jf:deploy file="build/ears/artifact.ear">
    <remoteRepository url="http://localhost:8081/artifactory/libs-release-local">
        <authentication username="artifactory-username" password="artifactory-password" />
    </remoteRepository>
    <pom file="pom.xml" />
</artifact_jf:deploy>


问:
How to prevent server blocking php
I'm currently developing a php daemon for connecting and retreiving data from social networks like facebook and twitter. This script allready works but I have some concerns about it.

It's possible to create an infinite amount of accounts that the script has to process and (right now) it runs every 5 minutes to create a 'near' realtime experience. So my concern is that, when, let's say 5000 accounts, have been created and have to be monitored. The script slows down and maybe wil run longer than the 5 minute interval. Is there any way to work around this problem? And better, is there any good way (with php, possible with javascript) to create a better 'near' realtime experience?

Any advice will be great!

Thanks in advance

答:
set the max execution time to zero and include it
enclose your script in a inite loop:

```<code>set_time_limit(0);
while(true){
/your code
}
</code>```

You should however include some way to end the process gracefully.
Some popular ways to do this is by checking if a env var was set or if a specific file exists.

```<code>set_time_limit(0);
while(true){
/your code
if(file_exist(KILL_SWITCH_FILE))break;
}
</code>```

Another approach would be setting a flag when(in a filem,in a sql database,...) that your script is running and removing it when your done.
That way you can check if another instance of your script is still running.

Title: How to prevent server blocking php

Body:
set the max execution time to zero and include it
enclose your script in a inite loop:

set_time_limit(0);
while(true){
/your code
}

You should however include some way to end the process gracefully.
Some popular ways to do this is by checking if a env var was set or if a specific file exists.

set_time_limit(0);
while(true){
/your code
if(file_exist(KILL_SWITCH_FILE))break;
}

Another approach would be setting a flag when(in a filem,in a sql database,...) that your script is running and removing it when your done.
That way you can check if another instance of your script is still running.


问:
Stuck on Some Javascript - Displaying Image on Mouseover of text
I'm trying to replicate the functionality of this page http://www.annedeckerarchitects.com/recognition/publications/ in a simpler way. The functionality I'm referring to is mousing over on something on the right and changing the image on the left.

What I have; https://jsfiddle.net/7j2zkndx/3/

html:

```<code><img class="global-image" />
<div class="scrolling-list">
<ul>
    <li data-link="http://i.imgur.com/ne3L7hy.jpg">Link Test <a href="#">click for more</a></li>
    <li data-link="http://i.imgur.com/mwa1Wwl.jpg">Link Test 2 <a href="#">click for more</a></li>
</ul>
</div>
</code>```

javascript;

```<code>var globalImage = $(".global-image").first();
$(".scrolling-list>li").each(function() {
    var list = this;
    var img = document.CreateElement("img");
    img.src = $(list).getAttribute("data-link");
    img.addEventListener("load", function() {
        list.addEventListener("mouseOver", function() {
            globalImage.src = $(list).getAttribute("data-link");
        });
    });
}();
</code>```

css;

```<code>.scrolling-list {
    width: 600px;
    height: 600px;
    overflow: scroll;
}
.global-image. .scrolling-list {
    display: inline-block;
}
</code>```

I'm honestly at a loss why it isn't working. It would be best to assume I'm a novice in JS.

Thanks.

答:
Another solution, if you want to bind :

HTML :

```<code><img class="global-image" />
<div>
    <ul class="scrolling-list">
        <li data-link="https://i.imgur.com/ne3L7hy.jpg">Link Test <a href="#" class="aToBind">click for more</a></li>
        <li data-link="https://i.imgur.com/mwa1Wwl.jpg">Link Test 2 <a href="#" class="aToBind">click for more</a></li>
    </ul>
</div>
</code>```

Javascript :

```<code>$("a.aToBind").mouseover(function(){
    let liParent = $(this).parent("li");
    $(".global-image").attr("src", $(liParent).attr("data-link"));
})
</code>```

The class "aToBind" is only use to separate these "a" from other "a" in the rest of script.

Body:
I'm trying to replicate the functionality of this page http://www.annedeckerarchitects.com/recognition/publications/ in a simpler way. The functionality I'm referring to is mousing over on something on the right and changing the image on the left.

What I have; https://jsfiddle.net/7j2zkndx/3/

html:

Link Test click for more

Link Test 2 click for more

javascript;

var globalImage = $(".global-image").first();
$(".scrolling-list>li").each(function() {
    var list = this;
    var img = document.CreateElement("img");
    img.src = $(list).getAttribute("data-link");
    img.addEventListener("load", function() {
        list.addEventListener("mouseOver", function() {
            globalImage.src = $(list).getAttribute("data-link");
        });
    });
}();

css;

.scrolling-list {
    width: 600px;
    height: 600px;
    overflow: scroll;
}
.global-image. .scrolling-list {
    display: inline-block;
}

I'm honestly at a loss why it isn't working. It would be best to assume I'm a novice in JS.

Thanks.

Body:
Another solution, if you want to bind :

HTML :

<img class="global-image" />
<div>
    <ul class="scrolling-list">
        <li data-link="https://i.imgur.com/ne3L7hy.jpg">Link Test <a href="#" class="aToBind">click for more</a></li>
        <li data-link="https://i.imgur.com/mwa1Wwl.jpg">Link Test 2 <a href="#" class="aToBind">click for more</a></li>
    </ul>
</div>

Javascript :

$("a.aToBind").mouseover(function(){
    let liParent = $(this).parent("li");
    $(".global-image").attr("src", $(liParent).attr("data-link"));
})

The class "aToBind" is only use to separate these "a" from other "a" in the rest of script.


问:
Bootstrap col offset not working
I am using the bootstrap to draw my page. I want to put the 'Title' not started with the line. But the col-md-offset-4 does not work.

```<code><div class="container">
<div class="jumbotron">
<div class="row">
  <div class="col-md-12">
    <h1 class="text-center">Beyond forever</h1>
    <h2 class="text-center"><em>My favorite band</em></h2>
    <div class="thumbnail text-center"><img src="http://res.cloudinary.com/deqlvmd9w/image/upload/v1494666517/beyond_ihkzoj.jpg"/>
    </div>
  </div>
  <div class="col-md-8 col-md-offset-4">
    <h3>Title</h3>
  </div>
</div>
</code>```

Here's the link https://jsfiddle.net/heshijinghuang/opsv0e09/

答: Thanks for all your reply. The issue has been solved. It is because boostrap 4 using different offset style(offset-sm-2）In bootstrap 3, it's col-offset-sm-2.</p>

Title: Bootstrap col offset not working

Body:
I am using the bootstrap to draw my page. I want to put the 'Title' not started with the line. But the col-md-offset-4 does not work.

Beyond forever

My favorite band

Title

Here's the link https://jsfiddle.net/heshijinghuang/opsv0e09/


问:
Excel to Access Import Error
Purpose:
To import data from excel to ms access (.mdb) database.

Reference: https://www.mikesdotnetting.com/article/79/import-data-from-excel-to-access-with-asp-net

Technology: C#.net Windows Forms

Error: "The Microsoft Jet database engine cannot find the input table or query 'Persons$'.  Make sure it exists and that its name is spelled correctly."

Code:

```<code> private void button6_Click(object sender, EventArgs e)
        {
            string Access = @"c:\exportdb\DestinationDB.mdb";
            string connect = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\exportdb\DestinationDB.mdb;";

            using (OleDbConnection conn = new OleDbConnection(connect))
            {
                using (OleDbCommand cmd = new OleDbCommand())
                {
                    cmd.Connection = conn;
                    cmd.CommandText = "INSERT INTO [MS Access;Database=" + Access + "].[Persons] SELECT * FROM [Persons$]";
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }
            }
        }
</code>```

Note:
I have created a MS Access database named "DestinationDB.mdb" with table name as "Persons" with the following fields:
ContactID,  FirstName,  SecondName, Age

Thereafter i have exported the same to excel in order to retain the header structure.

Once this excel is exported, i added some 10 records to it manually.

Both the files are located under "c://exportdb/source.xls" & "c://exportdb/DestinationDB.mdb".

Excel Snapshot:

Ms Access Snapshot:

Please help me to resolve the error stated above.

Thanks!

答:
The error sounds correct.  It looks like Persons$ is in the spreadsheet but you've opened a connection to the database (you can't do a "insert into select from" because they're not in the same database or linked).  You will likely need to open up a connection to both (then query one, insert into the other).  Something like the below pseudo code would work:

1.) Open a connection to the access database like you have.

2.) Open a separate connection to the spreadsheet.

3.) Query the Persons$ in the spreadsheet, return say a DataReader (ExecuteReader).

4.) Iterate over the DataReader and run an insert statement for each row (inserting into the access database).  Use a parameterized statement for this to protect against SQL injection/things that will mess the SQL up inadvertently.  You're talking from one data source and putting in into the other record by record.

If you're concerned the entire batch of records making it in, use a transaction and rollback if there are any errors.  That will ensure you get all or nothing.

Title: Excel to Access Import Error

Body:
Purpose:
To import data from excel to ms access (.mdb) database.

Reference: https://www.mikesdotnetting.com/article/79/import-data-from-excel-to-access-with-asp-net

Technology: C#.net Windows Forms

Error: "The Microsoft Jet database engine cannot find the input table or query 'Persons$'.  Make sure it exists and that its name is spelled correctly."

Code:

 private void button6_Click(object sender, EventArgs e)
        {
            string Access = @"c:\exportdb\DestinationDB.mdb";
            string connect = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\exportdb\DestinationDB.mdb;";

            using (OleDbConnection conn = new OleDbConnection(connect))
            {
                using (OleDbCommand cmd = new OleDbCommand())
                {
                    cmd.Connection = conn;
                    cmd.CommandText = "INSERT INTO [MS Access;Database=" + Access + "].[Persons] SELECT * FROM [Persons$]";
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }
            }
        }

Note:
I have created a MS Access database named "DestinationDB.mdb" with table name as "Persons" with the following fields:
ContactID,  FirstName,  SecondName, Age

Thereafter i have exported the same to excel in order to retain the header structure.

Once this excel is exported, i added some 10 records to it manually.

Both the files are located under "c://exportdb/source.xls" & "c://exportdb/DestinationDB.mdb".

Excel Snapshot:

Ms Access Snapshot:

Please help me to resolve the error stated above.

Thanks!


问:
How to send data from client to only socket server
I know that if I emit data on a socket, the data would be emitted to the all connected clients.

io.emit("test", data)

For instance if I run the command above, actually the data reaches to the all clients. But only test channel listeners handle it.

To prevent that, I use rooms. I use code like the following:

io.in("test").emit(data)

So, what if a client send data to the server, then will data be reached to the all clients?

Note: I also use socket.io-redis to make cluster.

答:
This code will send to all client in "roomName"

io.to(roomName).emit('new msg', {data:'hello every clients'});


问:
How to make sheet dynamic
Seeking for input on this. On the following code, what I'm doing is copying data from a sheet MayData.csv and pasting into Master2017.xlsx.

Master2017 is the main spreadsheet and contains data that is updated monthly.
Hence, the MayData.csv will change depending on the month (JuneData.csv, JulyData.csv, and so on...)

How can I make it such that the xxxData.csv is dynamic? Right now I try running the Macros but have to change the name of the sheet every time.

Here is what the code more or less looks like (I included only portion of it just to be brief):

```<code>Dim intChoice As Long
Dim strPath As String
Dim intUsedRows As Integer
Dim intCounter As Integer
Dim Lastrow As Long

'Open Selected File
Workbooks.Open (strPath)
Columns("C:D").Select
Selection.Delete Shift:=xlToLeft
Columns("F:H").Select
Selection.Delete Shift:=xlToLeft
Columns("G:H").Select
Selection.Delete Shift:=xlToLeft
Columns("B:B").Select
Windows("Master 2017.xlsx").Activate
Windows("MayData.csv").Activate
Columns("B:E").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Windows("Master 2017.xlsx").Activate
Windows("MayData.csv").Activate
Columns("I:S").Select
</code>```

答:
Is the user selecting the CSV file? If Yes then when you open it you can set a workbook variable so you can refer to it later. </p>

```<code>Dim wb As Workbook
'...
Set wb = Workbooks.Open(strPath)
'...
With wb.Sheets(1)
    .Columns("C:D").Delete Shift:=xlToLeft
    .Columns("F:H").Delete Shift:=xlToLeft
    .Columns("G:H").Delete Shift:=xlToLeft
End With
'...
</code>```

Title: How to make sheet dynamic

Body:
Seeking for input on this. On the following code, what I'm doing is copying data from a sheet MayData.csv and pasting into Master2017.xlsx.

Master2017 is the main spreadsheet and contains data that is updated monthly.
Hence, the MayData.csv will change depending on the month (JuneData.csv, JulyData.csv, and so on...)

How can I make it such that the xxxData.csv is dynamic? Right now I try running the Macros but have to change the name of the sheet every time.

Here is what the code more or less looks like (I included only portion of it just to be brief):

Dim intChoice As Long
Dim strPath As String
Dim intUsedRows As Integer
Dim intCounter As Integer
Dim Lastrow As Long

'Open Selected File
Workbooks.Open (strPath)
Columns("C:D").Select
Selection.Delete Shift:=xlToLeft
Columns("F:H").Select
Selection.Delete Shift:=xlToLeft
Columns("G:H").Select
Selection.Delete Shift:=xlToLeft
Columns("B:B").Select
Windows("Master 2017.xlsx").Activate
Windows("MayData.csv").Activate
Columns("B:E").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Windows("Master 2017.xlsx").Activate
Windows("MayData.csv").Activate
Columns("I:S").Select

Body:
Is the user selecting the CSV file? If Yes then when you open it you can set a workbook variable so you can refer to it later.

Dim wb As Workbook
'...
Set wb = Workbooks.Open(strPath)
'...
With wb.Sheets(1)
    .Columns("C:D").Delete Shift:=xlToLeft
    .Columns("F:H").Delete Shift:=xlToLeft
    .Columns("G:H").Delete Shift:=xlToLeft
End With
'...


问:
Actions on Google perform operation in local network
Trying to create an action on Google that communicates with devices in my local network.

So my question is, is that even possible, to perform an operation directly through google home, without a need to have a webhook in a server somewhere??

and if so, and i will need to have a webhook, what is the best way to make the webhook communicate with my phone, other than push notifications.

答:
If you want to control anything on your home network then you will have to run the fulfillment server in your house or let an external fulfillment server connect to something in your house. Either way you will need to poke a hole on your home firewall or use something like ngrok or bst proxy.

Then you will be in your home network and you can do your things on your local devices.

You should be more specific about the communication with your phone. What exactly are you trying to accomplish?


问:
How do I turn this data into a time series in R?
I am having some issues getting this data to be a time series for a holt-winter model. I don't know what to do next.</p>

```<code>library(reshape)
library(tidyr)

tempdata = as.matrix(read.table("https://d37djvu3ytnwxt.cloudfront.net/assets/courseware/v1/592f3be3e90d2bdfe6a69f62374a1250/asset-v1:GTx+ISYE6501x+2T2017+type@asset+block/temps.txt", header = TRUE, row.names = 1))

#melt data for time series

tempdata.ts <- melt(tempdata, id=1:1)

#concatenate Date and Year

tempdata.ts <- tempdata.ts %>% unite(col = "Date", c(X1, X2))
</code>```

答:
I suppose you want to fit HoltWinters from stats. This function requires ts object.

```<code>library(dplyr)
library(tidyr)
library(lubridate)
</code>```

First, reshape data:

```<code>file <- "https://d37djvu3ytnwxt.cloudfront.net/assets/courseware/v1/592f3be3e90d2bdfe6a69f62374a1250/asset-v1:GTx+ISYE6501x+2T2017+type@asset+block/temps.txt"

read.table(file, header = TRUE, row.names = 1) %>%
 as.data.frame() %>%
 mutate(DayMonth = rownames(.)) %>%
 gather(Date, Value, -DayMonth) %>%
 unite("Date", c(DayMonth, Date) ) %>%
 mutate(Date = dmy(Date) ) -> tempData
</code>```

Create time-series object:

```<code>tsData <- as.ts(
 tempData$Value, start = min(tempData$Date), end = max(tempData$Date),
 frequency = 365)
</code>```

Body:
I am having some issues getting this data to be a time series for a holt-winter model. I don't know what to do next.

library(reshape)
library(tidyr)

tempdata = as.matrix(read.table("https://d37djvu3ytnwxt.cloudfront.net/assets/courseware/v1/592f3be3e90d2bdfe6a69f62374a1250/asset-v1:GTx+ISYE6501x+2T2017+type@asset+block/temps.txt", header = TRUE, row.names = 1))

#melt data for time series

tempdata.ts <- melt(tempdata, id=1:1)

#concatenate Date and Year

tempdata.ts <- tempdata.ts %>% unite(col = "Date", c(X1, X2))

Body:
I suppose you want to fit HoltWinters from stats. This function requires ts object.

library(dplyr)
library(tidyr)
library(lubridate)

First, reshape data:

file <- "https://d37djvu3ytnwxt.cloudfront.net/assets/courseware/v1/592f3be3e90d2bdfe6a69f62374a1250/asset-v1:GTx+ISYE6501x+2T2017+type@asset+block/temps.txt"

read.table(file, header = TRUE, row.names = 1) %>%
 as.data.frame() %>%
 mutate(DayMonth = rownames(.)) %>%
 gather(Date, Value, -DayMonth) %>%
 unite("Date", c(DayMonth, Date) ) %>%
 mutate(Date = dmy(Date) ) -> tempData

Create time-series object:

tsData <- as.ts(
 tempData$Value, start = min(tempData$Date), end = max(tempData$Date),
 frequency = 365)


问:
How to add .aar dependency in library module?
I am having one .aar file of one library module.

I want to use it as a library or dependency in my other project's library module.

How do I do it?

I tried options provided at below links:

http://kevinpelgrims.com/blog/2014/05/18/reference-a-local-aar-in-your-android-project/

It works only if I add .aar reference in my project's application module. But not working in library module.

Thanks.

答:
Follow this setting and you will able to add .aar dependency to library module

build.gradle (Project: ....)

```<code>allprojects {
    repositories {
        jcenter()
        mavenCentral()
        flatDir {
            dirs 'libs'
            dirs project(':library_module').file('libs')
        }
    }
}
</code>```

build.gradle (Module: app)

```<code>dependencies {
    ...
    compile project(':library_module')
}
</code>```

build.gradle (Module: library_module)

```<code>dependencies {
    ...
    compile(name:'aar_file_name', ext:'aar')
}
</code>```

settings.gradle (Project Settings)

```<code>include ':app', ':library_module'
</code>```

Body:
Follow this setting and you will able to add .aar dependency to library module

build.gradle (Project: ....)

allprojects {
    repositories {
        jcenter()
        mavenCentral()
        flatDir {
            dirs 'libs'
            dirs project(':library_module').file('libs')
        }
    }
}

build.gradle (Module: app)

dependencies {
    ...
    compile project(':library_module')
}

build.gradle (Module: library_module)

dependencies {
    ...
    compile(name:'aar_file_name', ext:'aar')
}

settings.gradle (Project Settings)

include ':app', ':library_module'


问:
storing the contents in a array and displaying
I have written code to generate a prime number within a range. And then trying to store the generated prime number in an array:

```<code> if(prime)
   printf("\n%d", n);
 prime_array[k]=n;
 k++;
</code>```

Then trying to print the contents of array:

```<code>for(z=0;z<6;z++)
  printf("%d\n",prime_array[z]);
</code>```

The output that I get is incorrect. What is wrong?

答:
Assuming everything else is correct, you should consider the following: printf goes inside if block, but everything else doesn't. It probably should be:

```<code>if(prime) {
  printf("\n%d", n);
  prime_array[k]=n;
  k++;
}
</code>```

Body:
I have written code to generate a prime number within a range. And then trying to store the generated prime number in an array:

 if(prime)
   printf("\n%d", n);
 prime_array[k]=n;
 k++;

Then trying to print the contents of array:

for(z=0;z<6;z++)
  printf("%d\n",prime_array[z]);

The output that I get is incorrect. What is wrong?

Body:
Assuming everything else is correct, you should consider the following: printf goes inside if block, but everything else doesn't. It probably should be:

if(prime) {
  printf("\n%d", n);
  prime_array[k]=n;
  k++;
}


问:
Azure Runbook Error, AzureRmStorageAccountKey Cannot Index into null array
I am trying to run this command within an Azure Run book

(Get-AzureRmStorageAccountKey -Name $defaultStorageAccountName -ResourceGroupName $defaultResourceGroupName).Value[0]

It runs fine on my local machine and I can see the Storage Account Key. However, when I run the same command in Azure Runbook it throws the following error

```<code>Cannot index into a null array
</code>```

If I just run Get-AzureRmStorageAccountKey -Name $defaultStorageAccountName -ResourceGroupName $defaultResourceGroupName in the Azure Runbook, it runs fine and I can see the Keys. It is just when I am selecting an element from an Array that it fails and throws an error.

The PowerShell version is 5 on my local machine and on Azure Runbook.

Update:

My issue was resolved after updating the Modules from the Gallery in my automation account.

答:
According to your description, I test your cmdlets in my runbook, I could get storage key.

You could use the following commands to login your subscriptions.

```<code>Write-Verbose "Get connection asset: $ConnectionAssetName" -Verbose
$connectionName = Get-AutomationConnection -Name "AzureRunAsConnection"
$AzureCredentialAssetName = "AzureRunAsConnection"
try
{
    # Get the connection "AzureRunAsConnection "
    $servicePrincipalConnection=Get-AutomationConnection -Name $AzureCredentialAssetName

    "Logging in to Azure..."
    Add-AzureRmAccount `
        -ServicePrincipal `
        -TenantId $servicePrincipalConnection.TenantId `
        -ApplicationId $servicePrincipalConnection.ApplicationId `
        -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
    if (!$servicePrincipalConnection)
    {
        $ErrorMessage = "Connection $connectionName not found."
        throw $ErrorMessage
    } else{
        Write-Error -Message $_.Exception
        throw $_.Exception
    }
}

$key=(Get-AzureRmStorageAccountKey -Name <storage account name> -ResourceGroupName <resource group name>).Value[0]
"The storage account key is $key"
</code>```

More information please refer to this link.
Update

You need update Azure Storage account module version in automation account, then you could solve this issue.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to run this command within an Azure Run book

(Get-AzureRmStorageAccountKey -Name $defaultStorageAccountName -ResourceGroupName $defaultResourceGroupName).Value[0]

It runs fine on my local machine and I can see the Storage Account Key. However, when I run the same command in Azure Runbook it throws the following error

Cannot index into a null array

If I just run Get-AzureRmStorageAccountKey -Name $defaultStorageAccountName -ResourceGroupName $defaultResourceGroupName in the Azure Runbook, it runs fine and I can see the Keys. It is just when I am selecting an element from an Array that it fails and throws an error.

The PowerShell version is 5 on my local machine and on Azure Runbook.

Update:

My issue was resolved after updating the Modules from the Gallery in my automation account.

Body:
According to your description, I test your cmdlets in my runbook, I could get storage key.

You could use the following commands to login your subscriptions.

Write-Verbose "Get connection asset: $ConnectionAssetName" -Verbose
$connectionName = Get-AutomationConnection -Name "AzureRunAsConnection"
$AzureCredentialAssetName = "AzureRunAsConnection"
try
{
    # Get the connection "AzureRunAsConnection "
    $servicePrincipalConnection=Get-AutomationConnection -Name $AzureCredentialAssetName

    "Logging in to Azure..."
    Add-AzureRmAccount `
        -ServicePrincipal `
        -TenantId $servicePrincipalConnection.TenantId `
        -ApplicationId $servicePrincipalConnection.ApplicationId `
        -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
    if (!$servicePrincipalConnection)
    {
        $ErrorMessage = "Connection $connectionName not found."
        throw $ErrorMessage
    } else{
        Write-Error -Message $_.Exception
        throw $_.Exception
    }
}

$key=(Get-AzureRmStorageAccountKey -Name <storage account name> -ResourceGroupName <resource group name>).Value[0]
"The storage account key is $key"

More information please refer to this link.
Update

You need update Azure Storage account module version in automation account, then you could solve this issue.


问:
Why does pushing to one array affect another?
Consider the following code snippet:

var arr1 = "john".split('');
console.log(arr1); // [ 'j', 'o', 'h', 'n' ]
var arr2 = arr1.reverse();
console.log(arr1); // [ 'n', 'h', 'o', 'j' ]
var arr3 = "jones".split('');
arr2.push(arr3);
console.log(arr1); // [ 'n', 'h', 'o', 'j', [ 'j', 'o', 'n', 'e', 's' ] ]```

In the last console.log, why does pushing to arr2 affect arr1? Why does arr1 change when it's not modified, only arr2 is modified?

答:
There are two modifications to arr1 taking place on your code.

var arr2 = arr1.reverse();

The function Array.prototype.reverse() reverses an array in place. This means that arr1 will be reversed itself.

Also, when assigning objects, you are only passing a reference to them, so arr2 is actually arr1 (reversed) after this line.

arr2.push(arr3);

Because you assigned arr2 as a reference to arr1, in this line you are actually modifying arr1, being equivalent to writing arr1.push(arr3).

To create a new object from an array, you can use the function Array.prototype.slice(), since this method returns a copy of an array.

var arr1 = "john".split('');
console.log(arr1); // [ 'j', 'o', 'h', 'n' ]
var arr2 = arr1.slice().reverse();
console.log(arr1); // [ 'j', 'o', 'h', 'n' ]
var arr3 = "jones".split('');
arr2.push(arr3);
console.log(arr1);  // [ 'j', 'o', 'h', 'n' ]```

Body:
Consider the following code snippet:

var arr1 = "john".split('');
console.log(arr1); // [ 'j', 'o', 'h', 'n' ]
var arr2 = arr1.reverse();
console.log(arr1); // [ 'n', 'h', 'o', 'j' ]
var arr3 = "jones".split('');
arr2.push(arr3);
console.log(arr1); // [ 'n', 'h', 'o', 'j', [ 'j', 'o', 'n', 'e', 's' ] ]

In the last console.log, why does pushing to arr2 affect arr1? Why does arr1 change when it's not modified, only arr2 is modified?


问:
difference between inbound and outbound web service
What is the difference between inbound and outbound web service?
In inbound I must consuming a wsdl? or should I expose my service?

Is there a difference between the type of communication? Synchronous or asynchronous?

答:
Explanation#1:

Inbound / Call-In: - Receiving Request

Outbound / Call-Out: - Sending Response

Mid Server - Acts as interface between SN and a outer network

Explanation#2:

Inbound means that other applications make calls to ServiceNow's REST API to get information from SN, or create/update records.

Outbound means that ServiceNow makes calls to other applications' REST API to get information from the other application or create/update records.

Explanation#3:

inbound is basically when some other tool hits your instance(wsdl) with a payload and you process it and acknowledge it. EG, if an incident gets created in a third party tool then an incident gets created in a service now . Here we accept the request and process it.

When we hit any other tool then its outbound. EG exactly opposite to the above eg, when an incident gets created in Service now, a similar incident should get created on the other tool. Here we prepare the payload and hit the other tool's wsdl.

You can get videos here:

Integration Best Practices - Inbound Web Service - YouTube

Integration Best Practices - Outbound Web Service - YouTube

Resource Link: https://community.servicenow.com/thread/178997


问:
Generation of Class Diagram from XMI

Situation

I have a PHP project with lots of classes with lots of relationships in lots of folders following the Zend Naming Convention.

I use the NetBeans IDE 7.1.
I work under Windows 7.

Goal

I need to see a graphical representation of the class relationships, possibly in varying depths and varying degrees of complexity. Also, it would be nice if the classes in the diagram are clickable. I do not necessarily need to generate documentation.

Attempts

1. Within NetBeans

NetBeans is an awesome IDE with lots of features. In fact, it recognizes class dependencies, and it would be wise to assume that it has some sort of way to graphically view this relationship, natively, or through a plugin. Such a plugin exists, but is for version 5.5. I have 7.1, and it's not compatible. Fail.

2. Enterprise Architect

A simple google search brings up Enterprise Architect as an all-capable, completely comprehensive tool for solving such problems. So, I download and install. I'm not going to go to the detail of how I couldn't understand how to do anything, and how the tutorials are bragging about what the software can do, but rarely say how.

So, I imported the source. It generated many different classes and parsed all the members. Also, it generated the class diagrams. "Perfect!", I though, but alas. The class diagrams only show relationships between classes, the files of which were in the same source folder, despite the relationships being visibly registered in the classes' properties. A search for documentation on how I could merge all these diagrams into one was unsuccessful. Fail.

NOTE: I created a parallel thread before this one here.

3. PHP_UML

Found this PEAR tool. Looked good. So, I read through documentation on how to install it for my setup from various sources, and ran it. First, I used the html output format. Great! Lots of documentation with an index, bla bla bla. However, the best it could do in the direction I want was this:

Needless to say, I guess, that this is a very poor, super simplified version of what I actually need. Conclusion: fail.

4. Enterprise Architect + PHP_UML

However, PHP_UML can also generate XMI. Wow. Very nice. I can store my relationships and view them in different ways and exchange with other people.

So, I imported it into Enterprise Architect. Result: same as before with Enterprise Architect alone, only no class diagrams. Just the classes. As far as I've read about it, I can now manually create the relationships. Epic fail.

5. ArgoUML + PHP_UML

Somewhere through my search for solution I stumbled upon someone's comment that said they use ArgoUML. Downloaded and installed. XMI imported with some hassle (had to change version explicitly to 1). Fail (see Attempt 3).

Conclusion

Such a seemingly trivial task, and yet, so difficult. Do I have to go through this whole list, trying out each application?

答:
(Edit : This answer is an alternative for people that want to generate UML class diagram from a PHP project, it doesn't explains how to read XMI files)

Goal

I need to see a graphical representation of the class relationships,
  possibly in varying depths and varying degrees of complexity. Also, it
  would be nice if the classes in the diagram are clickable. I do not
  necessarily need to generate documentation.

If your goal was to generate a class diagram from a PHP project, I found a better solution than use PHP_UML. What you probably want is BoUML, with this software, you can select a PHP project folder and reverse engineering it. Then create a class diagram. When you drag&drop the class on it, the relations are there unlike AlgoUML (If I'm not wrong). XMI files are no longer useful in this case.

Title: Generation of Class Diagram from XMI


问:
Is there a way to tell mercurial 'delete all files that are deleted in local' during a merge?
I've been assigned the task to do a huge merge, ~1500 commits, on a mercurial project.

In the local fork we have deleted about ~200 files, right now I need to press d and enter for each file:

```<code>remote changed file/that/is/deleted/in/local which local deleted
use (c)hanged version or leave (d)eleted?
</code>```

Is there a way to tell mercurial to choose to delete all those files?

答:
As per the second answer and its comments in Resolving conflicts: how to accept "their" changes automatically?,

```<code>hg merge --tool internal:local
</code>```

will work.

Body:
I've been assigned the task to do a huge merge, ~1500 commits, on a mercurial project.

In the local fork we have deleted about ~200 files, right now I need to press d and enter for each file:

remote changed file/that/is/deleted/in/local which local deleted
use (c)hanged version or leave (d)eleted?

Is there a way to tell mercurial to choose to delete all those files?

Body:
As per the second answer and its comments in Resolving conflicts: how to accept "their" changes automatically?,

hg merge --tool internal:local

will work.


答:
The reverse() method in JavaScript mutates the array. This means that it changes the data in place—in the arr1 variable—and then returns a reference to that array. So arr2 is just a reference to arr1, rather than a new set of data.

If you want completely new data, you can do as they say in this StackOverflow question:

```<code>var arr2 = arr1.slice().reverse();
</code>```

That will slice a new set of data and then reverse it, hence returning a new array instead of a reference to the first array.

Example:

var array = ['a', 'b', 'c', 'd', 'e'];

var notmutated = array.slice();
console.log('not mutated:', notmutated);

var mutated = array.reverse();
console.log('mutated: ', array);```

Title: Why does pushing to one array affect another?

Body:
The reverse() method in JavaScript mutates the array. This means that it changes the data in place—in the arr1 variable—and then returns a reference to that array. So arr2 is just a reference to arr1, rather than a new set of data.

If you want completely new data, you can do as they say in this StackOverflow question:

var arr2 = arr1.slice().reverse();

That will slice a new set of data and then reverse it, hence returning a new array instead of a reference to the first array.

Example:

var array = ['a', 'b', 'c', 'd', 'e'];

var notmutated = array.slice();
console.log('not mutated:', notmutated);

var mutated = array.reverse();
console.log('mutated: ', array);


问:
Divide rows with date in SQL Server 2014
I have a problem with SQL. I have the following table:

```<code>declare @t table (START_DATE datetime,
                  END_DATE datetime,
                  GROSS_SALES_PRICE decimal(10,2)
                 );

insert into @t
values ('2014-08-06 00:00:00.000', '2014-10-06 23:59:59.000', 29.99),
       ('2014-09-06 00:00:00.000', '2014-09-09 23:59:59.000', 32.99),
       ('2014-09-10 00:00:00.000', '2014-09-30 23:59:59.000', 32.99),
       ('2014-10-07 00:00:00.000', '2049-12-31 23:59:59.000', 34.99)
</code>```

I would like to separate the dates which overlaps. For example I have in the first row START_DATE 2014-08-06 and END_DATE 2014-10-06. We can see that the dates from the second and the third row are inside this period of time from first row.

So I would like to separate them as follows:

```<code>declare @t2 table (START_DATE datetime,
                   END_DATE datetime,
                   GROSS_SALES_PRICE decimal(10,2)
                  );

insert into @t2
values ('2014-08-06 00:00:00.000', '2014-09-05 23:59:59.000', 29.99),
       ('2014-09-06 00:00:00.000', '2014-09-09 23:59:59.000', 32.99),
       ('2014-09-10 00:00:00.000', '2014-09-30 23:59:59.000', 32.99),
       ('2014-10-01 00:00:00.000', '2014-10-06 23:59:59.000', 29.99),
       ('2014-10-07 00:00:00.000', '2049-12-31 23:59:59.000', 34.99)
</code>```

So the second and the third rows remained unchanged. The first row should have new END_DATE. We also have new row. The GROSS_SALES_PRICE should remain as it is in internal period. Thanks for help. I am using SQL Server 2014

Body:
I have a problem with SQL. I have the following table:

declare @t table (START_DATE datetime,
                  END_DATE datetime,
                  GROSS_SALES_PRICE decimal(10,2)
                 );

insert into @t
values ('2014-08-06 00:00:00.000', '2014-10-06 23:59:59.000', 29.99),
       ('2014-09-06 00:00:00.000', '2014-09-09 23:59:59.000', 32.99),
       ('2014-09-10 00:00:00.000', '2014-09-30 23:59:59.000', 32.99),
       ('2014-10-07 00:00:00.000', '2049-12-31 23:59:59.000', 34.99)

I would like to separate the dates which overlaps. For example I have in the first row START_DATE 2014-08-06 and END_DATE 2014-10-06. We can see that the dates from the second and the third row are inside this period of time from first row.

So I would like to separate them as follows:

declare @t2 table (START_DATE datetime,
                   END_DATE datetime,
                   GROSS_SALES_PRICE decimal(10,2)
                  );

insert into @t2
values ('2014-08-06 00:00:00.000', '2014-09-05 23:59:59.000', 29.99),
       ('2014-09-06 00:00:00.000', '2014-09-09 23:59:59.000', 32.99),
       ('2014-09-10 00:00:00.000', '2014-09-30 23:59:59.000', 32.99),
       ('2014-10-01 00:00:00.000', '2014-10-06 23:59:59.000', 29.99),
       ('2014-10-07 00:00:00.000', '2049-12-31 23:59:59.000', 34.99)

So the second and the third rows remained unchanged. The first row should have new END_DATE. We also have new row. The GROSS_SALES_PRICE should remain as it is in internal period. Thanks for help. I am using SQL Server 2014

Body:
In addition to using datetime2 type instead of datetime, I'd recommend you to use [Closed; Open) intervals instead of [Closed; Closed]. In other words, use 2014-08-06 00:00:00.000, 2014-09-06 00:00:00.000 instead of 2014-08-06 00:00:00.000, 2014-09-05 23:59:59.000. Specifically, because 59.999 will be rounded to 00.000 for the datetime type, but will not for datetime2(3). You don't want to depend on such internal details of the data types.

Also, [Closed; Open) intervals are much easier to deal with in the queries as you'll see below.

The main idea is to put all start and end dates (boundaries) together in one list with a flag that indicates whether it is a beginning or end of the interval. When a running total of the flag turns into zero, it means that all overlapping intervals have ended.

Sample data

I extended your sample data with several cases of overlapping intervals.

declare @t table
(START_DATE datetime2(0),
END_DATE datetime2(0),
GROSS_SALES_PRICE decimal(10,2)
);

insert into @t
values
-- |------|                                    11
('2001-01-01 00:00:00', '2001-01-10 00:00:00', 11),

-- |------|                                    10
--     |------|                                20
('2010-01-01 00:00:00', '2010-01-10 00:00:00', 10),
('2010-01-05 00:00:00', '2010-01-20 00:00:00', 20),

-- |----------|                                30
--     |------|                                40
('2010-02-01 00:00:00', '2010-02-20 00:00:00', 30),
('2010-02-05 00:00:00', '2010-02-20 00:00:00', 40),

-- |----------|                                50
-- |----------|                                60
('2010-03-01 00:00:00', '2010-03-20 00:00:00', 50),
('2010-03-01 00:00:00', '2010-03-20 00:00:00', 60),

-- |----------|                                70
--   |------|                                  80
('2010-04-01 00:00:00', '2010-04-20 00:00:00', 70),
('2010-04-05 00:00:00', '2010-04-15 00:00:00', 80),

-- |-----------------------------|             29.99
--      |---------|                            32.99
--                |---------|                  32.99
--                               |----------|  34.99
('2014-08-06 00:00:00', '2014-10-07 00:00:00', 29.99),
('2014-09-06 00:00:00', '2014-09-10 00:00:00', 32.99),
('2014-09-10 00:00:00', '2014-10-01 00:00:00', 32.99),
('2014-10-07 00:00:00', '2050-01-01 00:00:00', 34.99);

Query

WITH
CTE_Boundaries
AS
(
    SELECT
        START_DATE AS dt
        ,+1 AS Flag
        ,GROSS_SALES_PRICE AS Price
    FROM @T

    UNION ALL

    SELECT
        END_DATE AS dt
        ,-1 AS Flag
        ,GROSS_SALES_PRICE AS Price
    FROM @T
)
,CTE_Intervals
AS
(
    SELECT
        dt
        ,Flag
        ,Price
        ,SUM(Flag) OVER (ORDER BY dt, Flag ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS SumFlag
        ,LEAD(dt) OVER (ORDER BY dt, Flag) AS NextDate
        ,LEAD(Price) OVER (ORDER BY dt, Flag) AS NextPrice
    FROM CTE_Boundaries
)
SELECT
    dt AS StartDate
    ,NextDate AS EndDate
    ,CASE WHEN Flag = 1 THEN Price ELSE NextPrice END AS Price
FROM CTE_Intervals
WHERE
    SumFlag > 0
    AND dt <> NextDate
ORDER BY StartDate
;

Result

+---------------------+---------------------+-------+
|      StartDate      |       EndDate       | Price |
+---------------------+---------------------+-------+
| 2001-01-01 00:00:00 | 2001-01-10 00:00:00 | 11.00 |
| 2010-01-01 00:00:00 | 2010-01-05 00:00:00 | 10.00 |
| 2010-01-05 00:00:00 | 2010-01-10 00:00:00 | 20.00 |
| 2010-01-10 00:00:00 | 2010-01-20 00:00:00 | 20.00 |
| 2010-02-01 00:00:00 | 2010-02-05 00:00:00 | 30.00 |
| 2010-02-05 00:00:00 | 2010-02-20 00:00:00 | 40.00 |
| 2010-03-01 00:00:00 | 2010-03-20 00:00:00 | 60.00 |
| 2010-04-01 00:00:00 | 2010-04-05 00:00:00 | 70.00 |
| 2010-04-05 00:00:00 | 2010-04-15 00:00:00 | 80.00 |
| 2010-04-15 00:00:00 | 2010-04-20 00:00:00 | 70.00 |

this is your sample data:

| 2014-08-06 00:00:00 | 2014-09-06 00:00:00 | 29.99 |
| 2014-09-06 00:00:00 | 2014-09-10 00:00:00 | 32.99 |
| 2014-09-10 00:00:00 | 2014-10-01 00:00:00 | 32.99 |
| 2014-10-01 00:00:00 | 2014-10-07 00:00:00 | 29.99 |
| 2014-10-07 00:00:00 | 2050-01-01 00:00:00 | 34.99 |
+---------------------+---------------------+-------+

Intermediary result of CTE_Intervals

Examine these to understand how the query works

+---------------------+------+-------+---------+---------------------+-----------+
|         dt          | Flag | Price | SumFlag |      NextDate       | NextPrice |
+---------------------+------+-------+---------+---------------------+-----------+
| 2001-01-01 00:00:00 |    1 | 11.00 |       1 | 2001-01-10 00:00:00 | 11.00     |
| 2001-01-10 00:00:00 |   -1 | 11.00 |       0 | 2010-01-01 00:00:00 | 10.00     |
| 2010-01-01 00:00:00 |    1 | 10.00 |       1 | 2010-01-05 00:00:00 | 20.00     |
| 2010-01-05 00:00:00 |    1 | 20.00 |       2 | 2010-01-10 00:00:00 | 10.00     |
| 2010-01-10 00:00:00 |   -1 | 10.00 |       1 | 2010-01-20 00:00:00 | 20.00     |
| 2010-01-20 00:00:00 |   -1 | 20.00 |       0 | 2010-02-01 00:00:00 | 30.00     |
| 2010-02-01 00:00:00 |    1 | 30.00 |       1 | 2010-02-05 00:00:00 | 40.00     |
| 2010-02-05 00:00:00 |    1 | 40.00 |       2 | 2010-02-20 00:00:00 | 30.00     |
| 2010-02-20 00:00:00 |   -1 | 30.00 |       1 | 2010-02-20 00:00:00 | 40.00     |
| 2010-02-20 00:00:00 |   -1 | 40.00 |       0 | 2010-03-01 00:00:00 | 50.00     |
| 2010-03-01 00:00:00 |    1 | 50.00 |       1 | 2010-03-01 00:00:00 | 60.00     |
| 2010-03-01 00:00:00 |    1 | 60.00 |       2 | 2010-03-20 00:00:00 | 50.00     |
| 2010-03-20 00:00:00 |   -1 | 50.00 |       1 | 2010-03-20 00:00:00 | 60.00     |
| 2010-03-20 00:00:00 |   -1 | 60.00 |       0 | 2010-04-01 00:00:00 | 70.00     |
| 2010-04-01 00:00:00 |    1 | 70.00 |       1 | 2010-04-05 00:00:00 | 80.00     |
| 2010-04-05 00:00:00 |    1 | 80.00 |       2 | 2010-04-15 00:00:00 | 80.00     |
| 2010-04-15 00:00:00 |   -1 | 80.00 |       1 | 2010-04-20 00:00:00 | 70.00     |
| 2010-04-20 00:00:00 |   -1 | 70.00 |       0 | 2014-08-06 00:00:00 | 29.99     |
| 2014-08-06 00:00:00 |    1 | 29.99 |       1 | 2014-09-06 00:00:00 | 32.99     |
| 2014-09-06 00:00:00 |    1 | 32.99 |       2 | 2014-09-10 00:00:00 | 32.99     |
| 2014-09-10 00:00:00 |   -1 | 32.99 |       1 | 2014-09-10 00:00:00 | 32.99     |
| 2014-09-10 00:00:00 |    1 | 32.99 |       2 | 2014-10-01 00:00:00 | 32.99     |
| 2014-10-01 00:00:00 |   -1 | 32.99 |       1 | 2014-10-07 00:00:00 | 29.99     |
| 2014-10-07 00:00:00 |   -1 | 29.99 |       0 | 2014-10-07 00:00:00 | 34.99     |
| 2014-10-07 00:00:00 |    1 | 34.99 |       1 | 2050-01-01 00:00:00 | 34.99     |
| 2050-01-01 00:00:00 |   -1 | 34.99 |       0 | NULL                | NULL      |
+---------------------+------+-------+---------+---------------------+-----------+


问:
Using password_hash PASSWORD_DEFAULT legacy concerns
From the php page: http://php.net/manual/en/function.password-hash.php

PASSWORD_DEFAULT - Use the bcrypt algorithm (default as of PHP 5.5.0). Note that this constant is designed to change over time as new and stronger algorithms are added to PHP. For that reason, the length of the result from using this identifier can change over time. Therefore, it is recommended to store the result in a database column that can expand beyond 60 characters (255 characters would be a good choice).

Would this mean that if I password_verify a password with a later version e.g. PHP8, it might not be able to decipher the stored password correctly? Or is all that information safely embedded already and all I have to do is store the output of password_hash into my DB and just call password_verify for validation without worries?

答:
Yes, all the information is safely embedded, provided that your database doesn't truncate the encrypted password. Which is pretty much a given, I'd think.

What that warning is driving home is that, for your future self's sanity, you store the information in a field whose length is flexible. Historically, like with MD5, one might have chosen CHAR(32). But with bcrypt, you need to choose something more flexible. That might be:

VARCHAR(255)

CHAR(60), with this column being the last one in the table, so that extending its length might not require the RDBMS to reshuffle table.


问:
How to store a number into an NFC tag?
I'm Vietnamese, so my English is not good. I have an RFID sensor. I want to store data into a block of the NFC tag.

My project is to add one score for the tag when the tag is read. But I can't insert the data as int type (to add the score). But when inserting data into a block, it requests an array of byte type.

I don't know how to convert an int type into an array byte type.
This project is on Arduino.

答:
Use the lowByte and highByte functions or use a simple bitshift. </p>

```<code>int asInt = 1234;
byte asByte[2];

asByte[0] = asInt >> 8;
asByte[1] = asInt & 0xFF;
</code>```

Title: How to store a number into an NFC tag?

Body:
Use the lowByte and highByte functions or use a simple bitshift.

int asInt = 1234;
byte asByte[2];

asByte[0] = asInt >> 8;
asByte[1] = asInt & 0xFF;