问:
import JSON file to MS SQL server
I make an API call to a URL using C# and it returns JSon response and i download the json file.

i would like to write the json data to database for use by a web application.
how can i import the json file into sql or write it direct from my c# program to db . am using sql 2016

My JSon file looks as follows :

```<code>{

    "Items": [
    {
        "LocalTimestamp": "2017-07-05T18:59:29+02:00",
        "Id": 653914348,
        "Description": "Trip Shutdown",
        "Processed": false,
        "Position": [
            27.90225,
            -26.07706
        ]
    },
    {
        "LocalTimestamp": "2017-07-05T08:41:08+02:00",
        "Id": 653709051,
        "Description": "Trip Startup",
        "Processed": false,
        "Position": [
            27.90229,
            -26.07753
        ]
    },
    {
        "LocalTimestamp": "2017-07-05T07:42:19+02:00",
        "Id": 653692142,
        "Description": "Trip Shutdown",
        "Processed": false,
        "Position": [
            27.90228,
            -26.07708
        ]
    },
    {
        "LocalTimestamp": "2017-07-05T07:21:47+02:00",
        "Id": 653683088,
        "Description": "Trip Startup",
        "Processed": false,
        "Position": [
            27.9222,
            -26.04318
        ]
    },
    {
        "LocalTimestamp": "2017-07-05T07:21:00+02:00",
        "Id": 653682830,
        "Description": "Trip Shutdown",
        "Processed": false,
        "Position": [
            27.92348,
            -26.04612
        ]
    },
    {
        "LocalTimestamp": "2017-07-04T10:15:35+02:00",
        "Id": 653330923,
        "Description": "Trip Shutdown",
        "Processed": false,
        "Position": [
            27.997,
            -26.05747
        ]
    },
    {
        "LocalTimestamp": "2017-07-04T09:41:19+02:00",
        "Id": 653320268,
        "Description": "Trip Startup",
        "Processed": false,
        "Position": [
            28.02899,
            -26.20546
        ]
    },
    {
        "LocalTimestamp": "2017-07-04T09:32:54+02:00",
        "Id": 653317769,
        "Description": "Trip Shutdown",
        "Processed": false,
        "Position": [
            28.0293,
            -26.20549
        ]
    },
    {
        "LocalTimestamp": "2017-07-03T18:40:43+02:00",
        "Id": 653089737,
        "Description": "Trip Shutdown",
        "Processed": false,
        "Position": [
            27.90228,
            -26.07707
        ]
    },
    {
        "LocalTimestamp": "2017-07-03T18:29:01+02:00",
        "Id": 653086470,
        "Description": "Trip Startup",
        "Processed": false,
        "Position": [
            27.94599,
            -26.07828
        ]
    },
    {
        "LocalTimestamp": "2017-07-03T18:26:30+02:00",
        "Id": 653085810,
        "Description": "Trip Shutdown",
        "Processed": false,
        "Position": [
            27.94662,
            -26.07807
        ]
    },
    {
        "LocalTimestamp": "2017-07-03T18:15:50+02:00",
        "Id": 653082613,
        "Description": "Trip Startup",
        "Processed": false,
        "Position": [
            27.98847,
            -26.05269
        ]
    },
    {
        "LocalTimestamp": "2017-07-03T18:13:15+02:00",
        "Id": 653082018,
        "Description": "Trip Shutdown",
        "Processed": false,
        "Position": [
            27.99036,
            -26.05341
        ]
    }
 ],
 "HasMoreResults": false
}
</code>```

答:
Ok. As i have mentioned in my comment, you have to de-serialize the json string which you received to object/class and save that class/object properties to database using c#.

In database, you need to create tables based on your "json string structure" or "class/object".

According to your json string the class should be like below

```<code>public class Item
{
    public string LocalTimestamp { get; set; }
    public int Id { get; set; }
    public string Description { get; set; }
    public bool Processed { get; set; }
    public List<double> Position { get; set; }
}

public class AllItems
{
    public List<Item> Items { get; set; }
    public bool HasMoreResults { get; set; }
}
</code>```

To de-serialize the json string, below is the code and for that, you need the namespace "System.Web.Script.Serialization".

```<code>string jsonstring = @"define your json string here";
//Deserialize the json string to the object/class format
var serializer = new JavaScriptSerializer();
AllItems allItemsObj = serializer.Deserialize<AllItems>(jsonstring);
</code>```

Create your database table as per the json string structure

```<code>CREATE TABLE AllItemsTable (
    ItemIdPrimary int NOT NULL IDENTITY(1,1),
    LocalTimestamp nvarchar(255),
    Id int,
    Description nvarchar(255),
    Processed nvarchar(255),
    Position1 nvarchar(50),
    Position2 nvarchar(50)

    PRIMARY KEY (ItemIdPrimary)
);
</code>```

Here the complete code to de-serialize the json string and save data
  to database.

For jsonstring, i have added a json file named as "test1.json" inside
  the application and copied your json string to the json file.Late i am
  consuming the json from that file("test1.json")

```<code>using System;
using System.Collections.Generic;
using System.IO;
using System.Web.Script.Serialization;
using System.Data.SqlClient;
using System.Configuration;

namespace DeserializeJson2ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            //Get the Json string
            string jsonstring = File.ReadAllText(@"D:\My Apps\Console Applications\DeserializeJson2ConsoleApp\DeserializeJson2ConsoleApp\test1.json");
            //Deserialize the json string to the object/class format
            var serializer = new JavaScriptSerializer();
            AllItems allItemsObj = serializer.Deserialize<AllItems>(jsonstring);
            //Save the deserilized object/class to database
            //Get your connection string defined inside the Web.config(for web application) / App.config(for console/windows/wpf/classlibrary application) file
            string myConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
            //Create your Sql Connection here
            using (SqlConnection con = new SqlConnection(myConnectionString))
            {
                //Open the sql connection
                con.Open();
                //Loop each items and save to database
                foreach (var item in allItemsObj.Items)
                {
                    //Save/Insert to database
                    if(SaveToDatabase(con, item))
                    {
                        Console.WriteLine("Success : " + item.Description + " Saved into database");
                    }
                    else
                    {
                        Console.WriteLine("Error : " + item.Description + " unable to Saved into database");
                    }
                }
            }
            Console.Read();
        }

        /// <summary>
        /// Insert to database
        /// </summary>
        /// <param name="con"></param>
        /// <param name="aItemObj"></param>
        /// <returns></returns>
        static bool SaveToDatabase(SqlConnection con,Item aItemObj)
        {
            try
            {
                string insertQuery = @"Insert into AllItemsTable(LocalTimestamp,Id,Description,Processed,Position1,Position2) Values(@LocalTimestamp,@Id,@Description,@Processed,@Position1,@Position2)";
                using (SqlCommand cmd = new SqlCommand(insertQuery, con))
                {
                    cmd.Parameters.Add(new SqlParameter("@LocalTimestamp",aItemObj.LocalTimestamp));
                    cmd.Parameters.Add(new SqlParameter("@Id", aItemObj.Id));
                    cmd.Parameters.Add(new SqlParameter("@Description", aItemObj.Description));
                    cmd.Parameters.Add(new SqlParameter("@Processed", aItemObj.Processed));
                    for(int index=0;index<aItemObj.Position.Count;index++)
                    {
                        if(index==0)
                            cmd.Parameters.Add(new SqlParameter("@Position1", aItemObj.Position[index].ToString()));
                        else
                            cmd.Parameters.Add(new SqlParameter("@Position2", aItemObj.Position[index].ToString()));
                    }
                    cmd.ExecuteNonQuery();
                }
                return true;
            }
            catch (Exception objEx)
            {
                return false;
            }
        }
    }

    public class Item
    {
        public string LocalTimestamp { get; set; }
        public int Id { get; set; }
        public string Description { get; set; }
        public bool Processed { get; set; }
        public List<double> Position { get; set; }
    }

    public class AllItems
    {
        public List<Item> Items { get; set; }
        public bool HasMoreResults { get; set; }
    }
}
</code>```

And here is the message in console after data saved to the database.

And here is the data which has been saved to the database.

Hope, it solves your problem. Revert me back if you have any issues.

Title: import JSON file to MS SQL server

Body:
I make an API call to a URL using C# and it returns JSon response and i download the json file.

i would like to write the json data to database for use by a web application.
how can i import the json file into sql or write it direct from my c# program to db . am using sql 2016

My JSon file looks as follows :

{

    "Items": [
    {
        "LocalTimestamp": "2017-07-05T18:59:29+02:00",
        "Id": 653914348,
        "Description": "Trip Shutdown",
        "Processed": false,
        "Position": [
            27.90225,
            -26.07706
        ]
    },
    {
        "LocalTimestamp": "2017-07-05T08:41:08+02:00",
        "Id": 653709051,
        "Description": "Trip Startup",
        "Processed": false,
        "Position": [
            27.90229,
            -26.07753
        ]
    },
    {
        "LocalTimestamp": "2017-07-05T07:42:19+02:00",
        "Id": 653692142,
        "Description": "Trip Shutdown",
        "Processed": false,
        "Position": [
            27.90228,
            -26.07708
        ]
    },
    {
        "LocalTimestamp": "2017-07-05T07:21:47+02:00",
        "Id": 653683088,
        "Description": "Trip Startup",
        "Processed": false,
        "Position": [
            27.9222,
            -26.04318
        ]
    },
    {
        "LocalTimestamp": "2017-07-05T07:21:00+02:00",
        "Id": 653682830,
        "Description": "Trip Shutdown",
        "Processed": false,
        "Position": [
            27.92348,
            -26.04612
        ]
    },
    {
        "LocalTimestamp": "2017-07-04T10:15:35+02:00",
        "Id": 653330923,
        "Description": "Trip Shutdown",
        "Processed": false,
        "Position": [
            27.997,
            -26.05747
        ]
    },
    {
        "LocalTimestamp": "2017-07-04T09:41:19+02:00",
        "Id": 653320268,
        "Description": "Trip Startup",
        "Processed": false,
        "Position": [
            28.02899,
            -26.20546
        ]
    },
    {
        "LocalTimestamp": "2017-07-04T09:32:54+02:00",
        "Id": 653317769,
        "Description": "Trip Shutdown",
        "Processed": false,
        "Position": [
            28.0293,
            -26.20549
        ]
    },
    {
        "LocalTimestamp": "2017-07-03T18:40:43+02:00",
        "Id": 653089737,
        "Description": "Trip Shutdown",
        "Processed": false,
        "Position": [
            27.90228,
            -26.07707
        ]
    },
    {
        "LocalTimestamp": "2017-07-03T18:29:01+02:00",
        "Id": 653086470,
        "Description": "Trip Startup",
        "Processed": false,
        "Position": [
            27.94599,
            -26.07828
        ]
    },
    {
        "LocalTimestamp": "2017-07-03T18:26:30+02:00",
        "Id": 653085810,
        "Description": "Trip Shutdown",
        "Processed": false,
        "Position": [
            27.94662,
            -26.07807
        ]
    },
    {
        "LocalTimestamp": "2017-07-03T18:15:50+02:00",
        "Id": 653082613,
        "Description": "Trip Startup",
        "Processed": false,
        "Position": [
            27.98847,
            -26.05269
        ]
    },
    {
        "LocalTimestamp": "2017-07-03T18:13:15+02:00",
        "Id": 653082018,
        "Description": "Trip Shutdown",
        "Processed": false,
        "Position": [
            27.99036,
            -26.05341
        ]
    }
 ],
 "HasMoreResults": false
}

Body:
Ok. As i have mentioned in my comment, you have to de-serialize the json string which you received to object/class and save that class/object properties to database using c#.

In database, you need to create tables based on your "json string structure" or "class/object".

According to your json string the class should be like below

public class Item
{
    public string LocalTimestamp { get; set; }
    public int Id { get; set; }
    public string Description { get; set; }
    public bool Processed { get; set; }
    public List<double> Position { get; set; }
}

public class AllItems
{
    public List<Item> Items { get; set; }
    public bool HasMoreResults { get; set; }
}

To de-serialize the json string, below is the code and for that, you need the namespace "System.Web.Script.Serialization".

string jsonstring = @"define your json string here";
//Deserialize the json string to the object/class format
var serializer = new JavaScriptSerializer();
AllItems allItemsObj = serializer.Deserialize<AllItems>(jsonstring);

Create your database table as per the json string structure

CREATE TABLE AllItemsTable (
    ItemIdPrimary int NOT NULL IDENTITY(1,1),
    LocalTimestamp nvarchar(255),
    Id int,
    Description nvarchar(255),
    Processed nvarchar(255),
    Position1 nvarchar(50),
    Position2 nvarchar(50)

    PRIMARY KEY (ItemIdPrimary)
);

Here the complete code to de-serialize the json string and save data
  to database.

For jsonstring, i have added a json file named as "test1.json" inside
  the application and copied your json string to the json file.Late i am
  consuming the json from that file("test1.json")

using System;
using System.Collections.Generic;
using System.IO;
using System.Web.Script.Serialization;
using System.Data.SqlClient;
using System.Configuration;

namespace DeserializeJson2ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            //Get the Json string
            string jsonstring = File.ReadAllText(@"D:\My Apps\Console Applications\DeserializeJson2ConsoleApp\DeserializeJson2ConsoleApp\test1.json");
            //Deserialize the json string to the object/class format
            var serializer = new JavaScriptSerializer();
            AllItems allItemsObj = serializer.Deserialize<AllItems>(jsonstring);
            //Save the deserilized object/class to database
            //Get your connection string defined inside the Web.config(for web application) / App.config(for console/windows/wpf/classlibrary application) file
            string myConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
            //Create your Sql Connection here
            using (SqlConnection con = new SqlConnection(myConnectionString))
            {
                //Open the sql connection
                con.Open();
                //Loop each items and save to database
                foreach (var item in allItemsObj.Items)
                {
                    //Save/Insert to database
                    if(SaveToDatabase(con, item))
                    {
                        Console.WriteLine("Success : " + item.Description + " Saved into database");
                    }
                    else
                    {
                        Console.WriteLine("Error : " + item.Description + " unable to Saved into database");
                    }
                }
            }
            Console.Read();
        }

        /// <summary>
        /// Insert to database
        /// </summary>
        /// <param name="con"></param>
        /// <param name="aItemObj"></param>
        /// <returns></returns>
        static bool SaveToDatabase(SqlConnection con,Item aItemObj)
        {
            try
            {
                string insertQuery = @"Insert into AllItemsTable(LocalTimestamp,Id,Description,Processed,Position1,Position2) Values(@LocalTimestamp,@Id,@Description,@Processed,@Position1,@Position2)";
                using (SqlCommand cmd = new SqlCommand(insertQuery, con))
                {
                    cmd.Parameters.Add(new SqlParameter("@LocalTimestamp",aItemObj.LocalTimestamp));
                    cmd.Parameters.Add(new SqlParameter("@Id", aItemObj.Id));
                    cmd.Parameters.Add(new SqlParameter("@Description", aItemObj.Description));
                    cmd.Parameters.Add(new SqlParameter("@Processed", aItemObj.Processed));
                    for(int index=0;index<aItemObj.Position.Count;index++)
                    {
                        if(index==0)
                            cmd.Parameters.Add(new SqlParameter("@Position1", aItemObj.Position[index].ToString()));
                        else
                            cmd.Parameters.Add(new SqlParameter("@Position2", aItemObj.Position[index].ToString()));
                    }
                    cmd.ExecuteNonQuery();
                }
                return true;
            }
            catch (Exception objEx)
            {
                return false;
            }
        }
    }

    public class Item
    {
        public string LocalTimestamp { get; set; }
        public int Id { get; set; }
        public string Description { get; set; }
        public bool Processed { get; set; }
        public List<double> Position { get; set; }
    }

    public class AllItems
    {
        public List<Item> Items { get; set; }
        public bool HasMoreResults { get; set; }
    }
}

And here is the message in console after data saved to the database.

And here is the data which has been saved to the database.

Hope, it solves your problem. Revert me back if you have any issues.


来源: stackexchange

问:
Ruuning external jar on talend
I have created a java program which just displays some messages.
And created its .jar file. I want to put that jar file on talend.
I did it using the tlibrary component. But now how do I run it.
I tried connecting it to other components like tjavarow.

The jar simply has a code which displays hello world.
Any help will be appreciated.

答:
Create a routine in the code tab in talend
Right click on the routine to edit the routine libraries and add your jar.

call this routine in the tJava.

ContentLicense: CC BY-SA 3.0

Title: Ruuning external jar on talend


问:
Which terminal command to get just IP address and nothing else?
I'm trying to use just the IP address (inet) as a parameter in a script I wrote.

Is there an easy way in a unix terminal to get just the IP address, rather than looking through ifconfig?

答:
```<code>hostname -I
</code>```

This command will give you the exact IP address as you want in Ubuntu. Note the flag is uppercase.

Body:
hostname -I

This command will give you the exact IP address as you want in Ubuntu. Note the flag is uppercase.

ContentLicense: CC BY-SA 4.0


问:
How to fetch last row of a webtable in selenium
I have a webtable for which I have to fetch the last row . The problem is that the webtable is dynamic so I don't know the row number.I have tried below code but the row number is static there which will fail.</p>

```<code>List<WebElement> rows=driver.findElements(By.xpath("//table[1]/tbody/tr[5]"));
</code>```

答:
int lastRowcount=driver.findElement(By.xpath("//table[1]/tbody/")).findElements(By.tagName("tr")).size();

    WebElement Lastrow =driver.findElement(By.xpath("//table[1]/tbody/tr["+lastRowcount+"]"));

In first Line we get the Last Row count from the table.

On second line we get the Last row Element from the table.

Body:
I have a webtable for which I have to fetch the last row . The problem is that the webtable is dynamic so I don't know the row number.I have tried below code but the row number is static there which will fail.

List<WebElement> rows=driver.findElements(By.xpath("//table[1]/tbody/tr[5]"));


问:
Interesting Applications of Interfaces
Why are interfaces useful?

Actually, I have a [small] idea of why interfaces are useful/necessary but...

What are [interesting or realistic] applications of interfaces?

答:
They allow polymorphism without some of the bad sides of inheritance.

What do I mean by bad sides of inheritance?

Code and Data inherited down a long chain (making it less obvious).

Inherited members that are over-ridden somewhere in the inheritance tree.

How can you use polymorphism?

To avoid repeating yourself. Create functions, switches, or conditionals which use the interface instead of the objects that implement the interface.

Java Specific

In Java, it often makes sense to use interfaces as a way to get multiple-inheritance.

This makes sense if something naturally fits into two categories and you have separate behavior expected for both of them.

Some Java Examples from the Web

http://home.cogeco.ca/~ve3ll/jatutor5.htm

http://java.freehep.org/lib/freehep/doc/root/index.html

http://www.codeguru.com/java/tij/tij0080.shtml

OwnerDisplayName: koldfyre

ContentLicense: CC BY-SA 2.5

Title: Interesting Applications of Interfaces

OwnerDisplayName: John Mulder

LastEditorDisplayName: John Mulder


问:
Make Qlabel clickable or double clickable in Qt
I am beginner in Qt, now I want to make my label clickable, I have searched so much online, but no one gives my a real example of how they made it. So can someone teach me step by step? Now my basic thinking is creating a new .c file and new .h file respectively and then include them into my mainwindow.c and then connect it with the existing label in ui form. These are what I was trying to do, but can not make it. Hope someone can teach and better put the step picture in the command, thanks.
Here is the clicklabel.h code:

```<code>#ifndef CLICKEDLABEL_H
#define CLICKEDLABEL_H

#include <QWidget>
#include <QLabel>

class ClickedLabel : public QLabel
{
    Q_OBJECT
public:
    ClickedLabel(QWidget *parent=0): QLabel(parent){}
    ~ClickedLabel() {}
signals:
    void clicked(ClickedLabel* click);
protected:
    void mouseReleaseEvent(QMouseEvent*);
};

#endif // CLICKEDLABEL_H
</code>```

This the clicklabel.c code:

```<code>#include "clicklabel.h"
void ClickedLabel::mouseReleaseEvent(QMouseEvent *)
{
    emit clicked(this);
}
</code>```

These are what I added into my mainwindow.c( the name of the label is click_test):

```<code>void data_labeling::on_label_clicked()
{
    QString path="/home/j/Pictures/images.jpeg";
    QPixmap cat(path);
    connect(ui->click_test, SIGNAL(clicked()), this,
SLOT(on_label_clicked()));
    ui->click_test->setPixmap(cat);
    ui->click_test->resize(cat.width(),cat.height());

}
</code>```

Of course I have promoted it to clicklabel.h and also I have added void on_label_click() to my mainwindow.h under private slots, but nothing happened.

答:
You can use QPushButton instead, but if you desperately need QLabel, you can do this:

clickable.h

```<code>class Clickable :public QLabel
    {
        Q_OBJECT
    signals:
        void clicked();
    public:
        void mousePressEvent(QMouseEvent* event);

        using QLabel::QLabel;
    };
</code>```

clickable.cpp

```<code>void Clickable::mousePressEvent(QMouseEvent* event)
{
    emit clicked();
}
</code>```

UPDATE:

This implementation I used in my source code. I can't paste complete code, but here is the part where I used it.

source.h

```<code>...
private:
    QLabel* label1;
    QLabel* label2;
...
</code>```

source.cpp

```<code>...
label1 = new Clickable("label1 text", this);
label2 = new Clickable("label2 text", this);
...
connect(label1 , SIGNAL(clicked()), this, SLOT(label1clicked()));
connect(label2 , SIGNAL(clicked()), this, SLOT(label1clicked()));
...
</code>```

Body:
I am beginner in Qt, now I want to make my label clickable, I have searched so much online, but no one gives my a real example of how they made it. So can someone teach me step by step? Now my basic thinking is creating a new .c file and new .h file respectively and then include them into my mainwindow.c and then connect it with the existing label in ui form. These are what I was trying to do, but can not make it. Hope someone can teach and better put the step picture in the command, thanks.
Here is the clicklabel.h code:

#ifndef CLICKEDLABEL_H
#define CLICKEDLABEL_H

#include <QWidget>
#include <QLabel>

class ClickedLabel : public QLabel
{
    Q_OBJECT
public:
    ClickedLabel(QWidget *parent=0): QLabel(parent){}
    ~ClickedLabel() {}
signals:
    void clicked(ClickedLabel* click);
protected:
    void mouseReleaseEvent(QMouseEvent*);
};

#endif // CLICKEDLABEL_H

This the clicklabel.c code:

#include "clicklabel.h"
void ClickedLabel::mouseReleaseEvent(QMouseEvent *)
{
    emit clicked(this);
}

These are what I added into my mainwindow.c( the name of the label is click_test):

void data_labeling::on_label_clicked()
{
    QString path="/home/j/Pictures/images.jpeg";
    QPixmap cat(path);
    connect(ui->click_test, SIGNAL(clicked()), this,
SLOT(on_label_clicked()));
    ui->click_test->setPixmap(cat);
    ui->click_test->resize(cat.width(),cat.height());

}

Of course I have promoted it to clicklabel.h and also I have added void on_label_click() to my mainwindow.h under private slots, but nothing happened.

Body:
You can use QPushButton instead, but if you desperately need QLabel, you can do this:

clickable.h

class Clickable :public QLabel
    {
        Q_OBJECT
    signals:
        void clicked();
    public:
        void mousePressEvent(QMouseEvent* event);

        using QLabel::QLabel;
    };

clickable.cpp

void Clickable::mousePressEvent(QMouseEvent* event)
{
    emit clicked();
}

UPDATE:

This implementation I used in my source code. I can't paste complete code, but here is the part where I used it.

source.h

...
private:
    QLabel* label1;
    QLabel* label2;
...

source.cpp

...
label1 = new Clickable("label1 text", this);
label2 = new Clickable("label2 text", this);
...
connect(label1 , SIGNAL(clicked()), this, SLOT(label1clicked()));
connect(label2 , SIGNAL(clicked()), this, SLOT(label1clicked()));
...


问:
Priority in Go select statement workaround
I wish to have a go routine listening on two channels, blocked when both channels are drained. However, if both channels contains data, I want one to be drained before the other is handled.

In the working example below I wish all out to be drained before exit is handled. I use a select-statement which doesn't have any priority order. How might I get around the problem, making all 10 out-values be handled before the exit?

```<code>package main

import "fmt"

func sender(out chan int, exit chan bool){
    for i := 1; i <= 10; i++ {
        out <- i
    }
    exit <- true
}

func main(){
    out := make(chan int, 10)
    exit := make(chan bool)

    go sender(out, exit)

    L:
    for {
        select {
            case i := <-out:
                fmt.Printf("Value: %d\n", i)
            case <-exit:
                fmt.Println("Exiting")
                break L
        }
    }
    fmt.Println("Did we get all 10? Most likely not")
}
</code>```

答:
In my case, I really wanted to prioritise data from one channel over another, and not just have an out-of-band exit signal. For the benefit of anyone else with the same issue I think this approach works without the potential race condition:</p>

```<code>OUTER:
for channelA != nil || channelB != nil {

    select {

    case typeA, ok := <-channelA:
        if !ok {
            channelA = nil
            continue OUTER
        }
        doSomething(typeA)

    case nodeIn, ok := <-channelB:
        if !ok {
            channelB = nil
            continue OUTER
        }

        // Looped non-blocking nested select here checks that channelA
        // really is drained before we deal with the data from channelB
        NESTED:
        for {
            select {
            case typeA, ok := <-channelA:
                if !ok {
                    channelA = nil
                    continue NESTED
                }
                doSomething(typeA)

            default:
                // We are free to process the typeB data now
                doSomethingElse(typeB)
                break NESTED
            }
        }
    }

}
</code>```

Body:
I wish to have a go routine listening on two channels, blocked when both channels are drained. However, if both channels contains data, I want one to be drained before the other is handled.

In the working example below I wish all out to be drained before exit is handled. I use a select-statement which doesn't have any priority order. How might I get around the problem, making all 10 out-values be handled before the exit?

package main

import "fmt"

func sender(out chan int, exit chan bool){
    for i := 1; i <= 10; i++ {
        out <- i
    }
    exit <- true
}

func main(){
    out := make(chan int, 10)
    exit := make(chan bool)

    go sender(out, exit)

    L:
    for {
        select {
            case i := <-out:
                fmt.Printf("Value: %d\n", i)
            case <-exit:
                fmt.Println("Exiting")
                break L
        }
    }
    fmt.Println("Did we get all 10? Most likely not")
}

Body:
In my case, I really wanted to prioritise data from one channel over another, and not just have an out-of-band exit signal. For the benefit of anyone else with the same issue I think this approach works without the potential race condition:

OUTER:
for channelA != nil || channelB != nil {

    select {

    case typeA, ok := <-channelA:
        if !ok {
            channelA = nil
            continue OUTER
        }
        doSomething(typeA)

    case nodeIn, ok := <-channelB:
        if !ok {
            channelB = nil
            continue OUTER
        }

        // Looped non-blocking nested select here checks that channelA
        // really is drained before we deal with the data from channelB
        NESTED:
        for {
            select {
            case typeA, ok := <-channelA:
                if !ok {
                    channelA = nil
                    continue NESTED
                }
                doSomething(typeA)

            default:
                // We are free to process the typeB data now
                doSomethingElse(typeB)
                break NESTED
            }
        }
    }

}


问:
Get data for month wise in mongodb
I want to get data to each month. in my table data is stored like this:-

```<code>   "patient" : [
    {
        "status" : 'arrived',
         start_time: '2017-08-17T09:17:00.000Z

    },
    {
        "status" : 'arraived',
         start_time: '2017-08-16T07:17:00.000Z
    },
   {
        "status" : 'arrived',
         start_time: '2017-07-12T09:17:00.000Z

    },
    {
        "status" : 'arraived',
         start_time: '2017-07-05T08:10:00.000Z
    },
    {
        "status" : 'arrived',
         start_time: '2017-06-02T09:17:00.000Z

    },
    {
        "status" : 'arraived',
         start_time: '2017-05-05T08:16:00.000Z
    }
    ]
</code>```

etc,
and I want to sum of patient of each month (jan to des), like  this :-

```<code>    {
      "month" : 8,
      "count" : 2
   }and like this month 1 to 12
</code>```

答:
I assume, patient array is associated with a customer and the date is stored in mongo ISO format.

So, the actual document would look like :

```<code>{
    name: "stackOverflow",
    "patient" : [
    {
        "status" : 'arrived',
         "start_time": ISODate("2017-08-17T09:17:00.000Z")

    },
    {
        "status" : 'arraived',
         "start_time": ISODate("2017-08-16T07:17:00.000Z")
    },
   {
        "status" : 'arrived',
         "start_time": ISODate("2017-07-12T09:17:00.000Z")

    },
    {
        "status" : 'arraived',
         "start_time": ISODate("2017-07-05T08:10:00.000Z")
    },
    {
        "status" : 'arrived',
         "start_time": ISODate("2017-06-02T09:17:00.000Z")

    },
    {
        "status" : 'arraived',
         "start_time": ISODate("2017-05-05T08:16:00.000Z")
    }
    ]
}
</code>```

here is a sample query which you can try -

```<code>db.test.aggregate([
{$unwind: "$patient"},
{ $group: {
    _id: {name: "$name", month: {$month: "$patient.start_time"}},
    count: { $sum: 1}
}},
{$group: {
    _id: "$_id.name",
    patient: {$push: {month: "$_id.month", count: "$count"}}
}}
])
</code>```

Sample output:

```<code>{
    "_id" : "stackOverflow",
    "patient" : [
        {
            "month" : 5,
            "count" : 1
        },
        {
            "month" : 6,
            "count" : 1
        },
        {
            "month" : 7,
            "count" : 2
        },
        {
            "month" : 8,
            "count" : 2
        }
    ]
}
</code>```

You can change query according to your use-case. hope this will help you!

Title: Get data for month wise in mongodb

Body:
I want to get data to each month. in my table data is stored like this:-

   "patient" : [
    {
        "status" : 'arrived',
         start_time: '2017-08-17T09:17:00.000Z

    },
    {
        "status" : 'arraived',
         start_time: '2017-08-16T07:17:00.000Z
    },
   {
        "status" : 'arrived',
         start_time: '2017-07-12T09:17:00.000Z

    },
    {
        "status" : 'arraived',
         start_time: '2017-07-05T08:10:00.000Z
    },
    {
        "status" : 'arrived',
         start_time: '2017-06-02T09:17:00.000Z

    },
    {
        "status" : 'arraived',
         start_time: '2017-05-05T08:16:00.000Z
    }
    ]

etc,
and I want to sum of patient of each month (jan to des), like  this :-

    {
      "month" : 8,
      "count" : 2
   }and like this month 1 to 12

Body:
I assume, patient array is associated with a customer and the date is stored in mongo ISO format.

So, the actual document would look like :

{
    name: "stackOverflow",
    "patient" : [
    {
        "status" : 'arrived',
         "start_time": ISODate("2017-08-17T09:17:00.000Z")

    },
    {
        "status" : 'arraived',
         "start_time": ISODate("2017-08-16T07:17:00.000Z")
    },
   {
        "status" : 'arrived',
         "start_time": ISODate("2017-07-12T09:17:00.000Z")

    },
    {
        "status" : 'arraived',
         "start_time": ISODate("2017-07-05T08:10:00.000Z")
    },
    {
        "status" : 'arrived',
         "start_time": ISODate("2017-06-02T09:17:00.000Z")

    },
    {
        "status" : 'arraived',
         "start_time": ISODate("2017-05-05T08:16:00.000Z")
    }
    ]
}

here is a sample query which you can try -

db.test.aggregate([
{$unwind: "$patient"},
{ $group: {
    _id: {name: "$name", month: {$month: "$patient.start_time"}},
    count: { $sum: 1}
}},
{$group: {
    _id: "$_id.name",
    patient: {$push: {month: "$_id.month", count: "$count"}}
}}
])

Sample output:

{
    "_id" : "stackOverflow",
    "patient" : [
        {
            "month" : 5,
            "count" : 1
        },
        {
            "month" : 6,
            "count" : 1
        },
        {
            "month" : 7,
            "count" : 2
        },
        {
            "month" : 8,
            "count" : 2
        }
    ]
}

You can change query according to your use-case. hope this will help you!


问:
Variable size of map container filled completely with map (preferably in leaflet)
I am making a responsive website and I have a map utility in it. The map container responds to changing screen sizes. I want to fill the map container div completely with map. Is this possible?

Eg. container sizes (width x height) - 10 x 50, 40 x 200, 800 x 100, 1500 x 200, 200 x 1600.

The problem is that raster map tiles come in squares (256 x 256, 512 x 512) - aspect ratio 1, and I am not so sure about vector tiles for crazy aspect ratios.

Would like to know, if the map pros out there have solved a similar problem. Thanks.

答:
Two Things (assuming leaflet.js is used) -

Define the size of map container in em, rem or px.

Call map.invalidateSize(), where

var map= L.map("map_container_id", {center: [lat, lng]});

once map has been loaded on to map container.

map.invalidateSize() updates the map on change of size.


问:
Get the value that is not matched with matching element from array with two elements
I have array of two elements

```<code>var a = ['a','b'];
</code>```

I have remover variable as var remover = 'a'

i want the result variable as var result = 'b'

i tried it as

```<code>var current_id = 'windows123456';
var allIds = People.Ids();  // this will have ['windows123456','windows123']
var index = allIds.indexOf(current_id);
  if (index >= 0) {
      allIds.splice( index, 1 );
  }
console.log(allIds[0]); //windows123
</code>```

Any Easy way to do this??

答:
If you only need to do this for two-element arrays, this will work:

```<code>var result = a.find(item => item != remover);
</code>```

If you need to work with longer arrays, this returns ['b']:

```<code>var result = a.filter(item => item != remover);
</code>```

Body:
I have array of two elements

var a = ['a','b'];

I have remover variable as var remover = 'a'

i want the result variable as var result = 'b'

i tried it as

var current_id = 'windows123456';
var allIds = People.Ids();  // this will have ['windows123456','windows123']
var index = allIds.indexOf(current_id);
  if (index >= 0) {
      allIds.splice( index, 1 );
  }
console.log(allIds[0]); //windows123

Any Easy way to do this??

Body:
If you only need to do this for two-element arrays, this will work:

var result = a.find(item => item != remover);

If you need to work with longer arrays, this returns ['b']:

var result = a.filter(item => item != remover);


问:
DateTime.ParseExact returns wrong date for the 'dd/MM/yyyy h:mm tt' format
I need to convert datetime from MM/dd/yyyy h:mm:ss tt format to the dd/MM/yyyy h:mm:ss tt

My code

```<code> var date = ((DateTime)model.WorkshopDate).ToString("dd/MM/yyyy h:mm:ss tt");

 var resultDate = DateTime.ParseExact(date, "dd/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
</code>```

In result date = 25/12/2017 12:00:00 AM

But resultDate = 12/25/2017 12:00:00 AM .

How can i parse it right?

答:
here

```<code>var date = ((DateTime)model.WorkshopDate).ToString("dd/MM/yyyy h:mm:ss tt");
</code>```

you are implicitly asking to display the date in "dd/MM/yyyy h:mm:ss tt"

```<code>var resultDate = DateTime.ParseExact(date, "dd/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
</code>```

here system default format is using to display the date.

if you want to display both as same

```<code>Console.WriteLine(date);
Console.WriteLine(resultDate.ToString("dd/MM/yyyy h:mm:ss tt"));
</code>```

Body:
I need to convert datetime from MM/dd/yyyy h:mm:ss tt format to the dd/MM/yyyy h:mm:ss tt

My code

 var date = ((DateTime)model.WorkshopDate).ToString("dd/MM/yyyy h:mm:ss tt");

 var resultDate = DateTime.ParseExact(date, "dd/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);

In result date = 25/12/2017 12:00:00 AM

But resultDate = 12/25/2017 12:00:00 AM .

How can i parse it right?

Body:
here

var date = ((DateTime)model.WorkshopDate).ToString("dd/MM/yyyy h:mm:ss tt");

you are implicitly asking to display the date in "dd/MM/yyyy h:mm:ss tt"

var resultDate = DateTime.ParseExact(date, "dd/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);

here system default format is using to display the date.

if you want to display both as same

Console.WriteLine(date);
Console.WriteLine(resultDate.ToString("dd/MM/yyyy h:mm:ss tt"));


问:
Performance of Java enums
I was thinking about using enum type to manage i18n in a Java game I'm developing but I was curious about performance issues that can occur when working with enums that have lots of elements (thousands I think).

Actually I'm trying something like:

```<code>public enum Text {
  STRING1,
  STRING2,
  STRING3;

  public String text() {
    return text;
  }

  public String setText() {
    this.text = text;
  }
}
</code>```

Then to load them I can just fill the fields:

```<code>static
{
  Text.STRING1.setText("My localized string1");
  Text.STRING2.setText("My localized string2");
  Text.STRING3.setText("My localized string3");
}
</code>```

Of course when I'll have to manage many languages I'll load them from a file.

What I'm asking is

is an obect allocated (in addition to the string) for every element? (I guess yes, since enums are implemented with objects)

how is the right element retrieved from the enum? is it static at compile time? (I mean when somewhere I use Text.STRING1.text()). So it should be constant complexity or maybe they are just replaced during the compiling phase..

in general, is it a good approach or should I look forward something else?

Thanks

答:
Kudos for showing me a compiler error I have never seen before. When compiling the source file generated by:

```<code>public static void main(String[] args) throws Exception {
    PrintWriter w = new PrintWriter("C:\\test.java");
    w.println("enum Test {");
    for (int i = 0; i < 3000; i++) {
        w.println("c" + i + ",");
    }
    w.println("}");
    w.close();
}
</code>```

eclipse says

The code for the static initializer is
  exceeding the 65535 bytes limit

Same test with a mere 2000 constants compiles flawlessly.

Of course, if you have that many constants, it would be a good idea to organize them into more than one source file.

Yes, one (and only one) object is allocated for every enum constant. With 2000 constants, that's a whopping 16KB memory :-)  (on Sun's 32-bit VM, other VMs might differ a little)

Each enum constant is an object, and each of them has a field text. The field is not final, and hence not subject to inlining. Yes, field access is constant-time.

However, in general it's wierd having mutable state in an enum. It's possible, though.

Good approaches include:

Delegate to a ResourceBundle as AlexR shows. Disadvantage: You have to manually manage the resource files. If you do that, I recommend a UnitTest to detect mistyped/missing/superfluous resource keys, or even a command line utility to append the missing keys to the resource file so you don't have to (mis-)type them.

If you only support a few languages, you can alternatively store all languages in the enum:

```<code>enum Message {
    Hello("Hello", "Hallo", "Salut");

    String en;
    String de;
    String fr;

    Message(String en, String de, String fr) {
        this.en = en;
        this.fr = fr;
        this.it = it;
    }
</code>```

Disadvantages: No editing by laymen (needs a compiler), and the source file encoding had better support all special characters in the target language (unicode escapes are awkward ...). Also, the source file gets cluttered if you have more than 3 or 4 languages.

Advantages: Adding/Deleting texts is a snap, and the compiler catches all typos in the name of the text, and the "resource file" is always consistent.

Either way, you should use MessageFormat as the tutorial R.Bemrose links to in his answer explains.

And finally, when working with Enums you might find the values() method handy:

```<code>for (Text t : Text.values()) {

}
</code>```

Title: Performance of Java enums

Body:
I was thinking about using enum type to manage i18n in a Java game I'm developing but I was curious about performance issues that can occur when working with enums that have lots of elements (thousands I think).

Actually I'm trying something like:

public enum Text {
  STRING1,
  STRING2,
  STRING3;

  public String text() {
    return text;
  }

  public String setText() {
    this.text = text;
  }
}

Then to load them I can just fill the fields:

static
{
  Text.STRING1.setText("My localized string1");
  Text.STRING2.setText("My localized string2");
  Text.STRING3.setText("My localized string3");
}

Of course when I'll have to manage many languages I'll load them from a file.

What I'm asking is

is an obect allocated (in addition to the string) for every element? (I guess yes, since enums are implemented with objects)

how is the right element retrieved from the enum? is it static at compile time? (I mean when somewhere I use Text.STRING1.text()). So it should be constant complexity or maybe they are just replaced during the compiling phase..

in general, is it a good approach or should I look forward something else?

Thanks

Body:
Kudos for showing me a compiler error I have never seen before. When compiling the source file generated by:

public static void main(String[] args) throws Exception {
    PrintWriter w = new PrintWriter("C:\\test.java");
    w.println("enum Test {");
    for (int i = 0; i < 3000; i++) {
        w.println("c" + i + ",");
    }
    w.println("}");
    w.close();
}

eclipse says

The code for the static initializer is
  exceeding the 65535 bytes limit

Same test with a mere 2000 constants compiles flawlessly.

Of course, if you have that many constants, it would be a good idea to organize them into more than one source file.

Yes, one (and only one) object is allocated for every enum constant. With 2000 constants, that's a whopping 16KB memory :-)  (on Sun's 32-bit VM, other VMs might differ a little)

Each enum constant is an object, and each of them has a field text. The field is not final, and hence not subject to inlining. Yes, field access is constant-time.

However, in general it's wierd having mutable state in an enum. It's possible, though.

Good approaches include:

Delegate to a ResourceBundle as AlexR shows. Disadvantage: You have to manually manage the resource files. If you do that, I recommend a UnitTest to detect mistyped/missing/superfluous resource keys, or even a command line utility to append the missing keys to the resource file so you don't have to (mis-)type them.

If you only support a few languages, you can alternatively store all languages in the enum:

enum Message {
    Hello("Hello", "Hallo", "Salut");

    String en;
    String de;
    String fr;

    Message(String en, String de, String fr) {
        this.en = en;
        this.fr = fr;
        this.it = it;
    }

Disadvantages: No editing by laymen (needs a compiler), and the source file encoding had better support all special characters in the target language (unicode escapes are awkward ...). Also, the source file gets cluttered if you have more than 3 or 4 languages.

Advantages: Adding/Deleting texts is a snap, and the compiler catches all typos in the name of the text, and the "resource file" is always consistent.

Either way, you should use MessageFormat as the tutorial R.Bemrose links to in his answer explains.

And finally, when working with Enums you might find the values() method handy:

for (Text t : Text.values()) {

}


问:
text with input in one row
I have div with input field and text

Here is code

.form-control {
    display: block;
    width: 100%;
    height: 34px;
    position: relative;
    padding: 6px 12px;
    font-size: 14px;
    line-height: 1.42857143;
    color: #555;
    margin: 0 auto;
    background-color: #fff;
    border-color: #1f66b4;
    border-style: solid;
    border-width: 3px;
    background-image: none;
    border-radius: 4px;
    -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
    -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
    -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
    transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="width:50%;height:100%;float: left;padding-left:20%">
            <form style="text-align:center;">
                <b>dfsdfsdfsdf</b>
                <input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" style="margin: 30px auto 0;border-radius:50px;border-width: 1px;">
            </form>
        </div></code>```

But text is over input.

I need to make text in one row with input.
How I can do this?

答:
            <form style="text-align:center;">
                <lable> dfsdfsdfsdf
                <input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" style="margin: 30px auto 0;border-radius:50px;border-width: 1px;">
            </form>

```

Title: text with input in one row

Body:
I have div with input field and text

Here is code

.form-control {
    display: block;
    width: 100%;
    height: 34px;
    position: relative;
    padding: 6px 12px;
    font-size: 14px;
    line-height: 1.42857143;
    color: #555;
    margin: 0 auto;
    background-color: #fff;
    border-color: #1f66b4;
    border-style: solid;
    border-width: 3px;
    background-image: none;
    border-radius: 4px;
    -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
    -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
    -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
    transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
}

            <form style="text-align:center;">
                dfsdfsdfsdf
                <input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" style="margin: 30px auto 0;border-radius:50px;border-width: 1px;">
            </form>

But text is over input.

I need to make text in one row with input.
How I can do this?

Body:
    <div style="width:50%;height:100%;float: left;padding-left:20%">
            <form style="text-align:center;">
                <lable> dfsdfsdfsdf</label>
                <input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" style="margin: 30px auto 0;border-radius:50px;border-width: 1px;">
            </form>
        </div>


问:
Horizontal scrollbar removal in IE when using Responsive bootstrap table
I created a responsive table with bootstrap 3.3.2
The issue was the presence of horizontal scroll bar always at the bottom of the table.
As per the below link
https://github.com/twbs/bootstrap/issues/10711

I used container-fluid in table so the issue resolved in Crome but in IE it is still showing.
Any idea to remove horizontal scrollbar in IE when it reaches 100% width?

答:
change the class row by container-fluid

             Sidebar Content

        Test content

```

Body:
change the class row by container-fluid

<div class="container-fluid">
    <div class="col-md-3">
        <div class="sectionLeft">
             Sidebar Content
        </div>
    </div>
    <div class="col-md-9">
        Test content
    </div>
</div>


问:
How I can publish NPM package with a name different one in package.json?
My package.json has

```<code>{
  "name": "package_name",
  "version": "1.0.1"
}
</code>```

I want publish the package with name example_name. How I can do this?

答:
When you run npm publish its look at your package.json, So the best thing to do is to change the name in the package.json, run npm publish and then change it back to the your desired name.

You of course can write a script that will do it for you if you need to do it many times

Body:
My package.json has

{
  "name": "package_name",
  "version": "1.0.1"
}

I want publish the package with name example_name. How I can do this?


问:
Can't get onClick() call back after setStateListAnimator(null)
The title is pretty self-explanatory, I have a button for which I call setStateListAnimator(null);. I've also registered for an OnClickListener callback. The problem is whenever I call setStateListAnimator(null) I don't get callback for onClick().

```<code><Button android:id="@+id/urlSubmittButton"
    android:layout_below="@id/editLyout"
    android:layout_width="150dp"
    android:layout_height="45dp"
    android:text="Add"
    android:layout_marginTop="10dp"
    android:textSize="18sp"
    android:layout_centerHorizontal="true"
    android:gravity="center"
    android:padding="5dp" />
</code>```

and in my Fragment:

```<code>urlSubmitButton = (Button) mView.findViewById(R.id.urlSubmittButton);

urlSubmitButton.setClickable(true);
urlSubmitButton.setEnabled(true);
urlSubmitButton.setOnClickListener(this);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    urlSubmitButton.setStateListAnimator(null);
}
</code>```

As you can see, I tried setting the Button clickable and enabled, it doesn't change the behavior. However commenting simply that line of code works the charm.

Is this intended behavior for API 24? Because so far I've only been able to reproduce this issue in API 24 device. If not, then is there any other way of stopping stateListAnimator which causes a water-drop-ripple-effect in Button when clicked?

答:
If not, then is there any other way of stopping stateListAnimator which causes a water-drop-ripple-effect in Button when clicked?

First of all, I don't think stateListAnimator is somehow connected with ripple effect. Ripple is just a background set to the Button, whereas stateListAnimator specifies what animation to perform based on the current state of the view. See states in StateListDrawable.

In order to completely hide the ripple effect apply this to the style of your activity:

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
  ...
  <item name="selectableItemBackground">@null</item>
  <item name="selectableItemBackgroundBorderless">@null</item>
</style>
</code>```

Body:
The title is pretty self-explanatory, I have a button for which I call setStateListAnimator(null);. I've also registered for an OnClickListener callback. The problem is whenever I call setStateListAnimator(null) I don't get callback for onClick().

<Button android:id="@+id/urlSubmittButton"
    android:layout_below="@id/editLyout"
    android:layout_width="150dp"
    android:layout_height="45dp"
    android:text="Add"
    android:layout_marginTop="10dp"
    android:textSize="18sp"
    android:layout_centerHorizontal="true"
    android:gravity="center"
    android:padding="5dp" />

and in my Fragment:

urlSubmitButton = (Button) mView.findViewById(R.id.urlSubmittButton);

urlSubmitButton.setClickable(true);
urlSubmitButton.setEnabled(true);
urlSubmitButton.setOnClickListener(this);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    urlSubmitButton.setStateListAnimator(null);
}

As you can see, I tried setting the Button clickable and enabled, it doesn't change the behavior. However commenting simply that line of code works the charm.

Is this intended behavior for API 24? Because so far I've only been able to reproduce this issue in API 24 device. If not, then is there any other way of stopping stateListAnimator which causes a water-drop-ripple-effect in Button when clicked?

Body:
If not, then is there any other way of stopping stateListAnimator which causes a water-drop-ripple-effect in Button when clicked?

First of all, I don't think stateListAnimator is somehow connected with ripple effect. Ripple is just a background set to the Button, whereas stateListAnimator specifies what animation to perform based on the current state of the view. See states in StateListDrawable.

In order to completely hide the ripple effect apply this to the style of your activity:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
  ...
  <item name="selectableItemBackground">@null</item>
  <item name="selectableItemBackgroundBorderless">@null</item>
</style>


问:
how to put row onto another one? / CSS
on the image as you can see 'Sezon' and 'Poza sezonem' blocks are on another blocks(ND-CZW, PT-SB)

I'm trying to write html code of this image. how can I put Sezon,poza sezonem blocks on the blocks below?

```<code><div class="parent">
<tr>
<td style="text-align: center;background-color: #E96165;color: #fff">Ilosc
gosci</td>
<td class="baslik1">Sezon</td>
<td class="baslik1">Poza sezonem</td>
<td class="baslik1">Poza sezonem 2</td>
</tr>
<tr>
<td class="baslik2"> </td>
<td class="baslik2">ND-CZW</td>
<td class="baslik2">PT-SB</td>
<td class="baslik2">ND-CZW</td>
</tr>
</div>
</code>```

答:
I would use Flexbox with absolute positioning like this:

.parent {
  display: flex;
}

.table {
  display: flex;
  flex-direction: column;
  box-shadow: 0 20px 30px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23);
  background: lightgrey;
}

.table:nth-child(2) {
  z-index: 2;
}
.table:nth-child(3) {
  z-index: 3;
}

.table > div {
  display: flex;
  flex-direction: row;
}

.cell {
  box-sizing: border-box;
  display: flex;
  height: 60px;
  width: 200px;
  border-bottom: 1px solid grey;
}

.cell--head {
  height: 60px;
  position: relative;
}

.cell--logo {
  background-color: #E96165;
  color: #fff;
  padding: 0;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cell--head > div {
  padding-top: 30px;
}

.cell > div {
  flex: 1;
  text-align: center;
  border-left: 1px solid grey;
  padding: 20px;
}

.cell > div:first-of-type {
  border-left: 0;
}

.label {
  position: absolute;
  top: -2px;
  background: black;
  color: white;
  transform: translate(-50%, 0%);
  left: 50%;
  padding: 5px;
  font-size: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="table">
    <div class="cell cell--logo">
      Ilosc gosci
    </div>
    <div class="cell">
      Ilosc gosci
    </div>
  </div>
  <div class="table">
    <div class="cell cell--head">
      <span class="label">Sezon</span>
      <div>ND-CZW</div>
      <div>ND-CZW</div>
    </div>
    <div class="cell">
      <div>245 pln</div>
      <div>245 pln</div>
    </div>
  </div>
  <div class="table">
    <div class="cell cell--head">
      <span class="label">Poza sezonem</span>
      <div>ND-CZW</div>
      <div>ND-CZW</div>
    </div>
    <div class="cell">
      <div>245 pln</div>
      <div>245 pln</div>
    </div>
  </div>
  <div>
    <td class="baslik2"></td>
    <td class="baslik2"></td>
    <td class="baslik2"></td>
    <td class="baslik2"></td>
  </div>
  </div>
</div></code>```

Title: how to put row onto another one? / CSS

Body:
on the image as you can see 'Sezon' and 'Poza sezonem' blocks are on another blocks(ND-CZW, PT-SB)

I'm trying to write html code of this image. how can I put Sezon,poza sezonem blocks on the blocks below?

Ilosc
gosci
Sezon
Poza sezonem
Poza sezonem 2

ND-CZW
PT-SB
ND-CZW

Body:
I would use Flexbox with absolute positioning like this:

.parent {
  display: flex;
}

.table {
  display: flex;
  flex-direction: column;
  box-shadow: 0 20px 30px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23);
  background: lightgrey;
}

.table:nth-child(2) {
  z-index: 2;
}
.table:nth-child(3) {
  z-index: 3;
}

.table > div {
  display: flex;
  flex-direction: row;
}

.cell {
  box-sizing: border-box;
  display: flex;
  height: 60px;
  width: 200px;
  border-bottom: 1px solid grey;
}

.cell--head {
  height: 60px;
  position: relative;
}

.cell--logo {
  background-color: #E96165;
  color: #fff;
  padding: 0;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cell--head > div {
  padding-top: 30px;
}

.cell > div {
  flex: 1;
  text-align: center;
  border-left: 1px solid grey;
  padding: 20px;
}

.cell > div:first-of-type {
  border-left: 0;
}

.label {
  position: absolute;
  top: -2px;
  background: black;
  color: white;
  transform: translate(-50%, 0%);
  left: 50%;
  padding: 5px;
  font-size: 10px;
}

<div class="parent">
  <div class="table">
    <div class="cell cell--logo">
      Ilosc gosci
    </div>
    <div class="cell">
      Ilosc gosci
    </div>
  </div>
  <div class="table">
    <div class="cell cell--head">
      <span class="label">Sezon</span>
      <div>ND-CZW</div>
      <div>ND-CZW</div>
    </div>
    <div class="cell">
      <div>245 pln</div>
      <div>245 pln</div>
    </div>
  </div>
  <div class="table">
    <div class="cell cell--head">
      <span class="label">Poza sezonem</span>
      <div>ND-CZW</div>
      <div>ND-CZW</div>
    </div>
    <div class="cell">
      <div>245 pln</div>
      <div>245 pln</div>
    </div>
  </div>
  <div>
    <td class="baslik2"></td>
    <td class="baslik2"></td>
    <td class="baslik2"></td>
    <td class="baslik2"></td>
  </div>
  </div>
</div>


问:
How to download a file from a server using Java Socket?
I have an assignment about uploading and downloading a file to a server. I managed to do the uploading part using Java Sockets however I am having a hard time doing the downloading part. I should use Range: for downloading parellel. In my request, I should have the Range: header. But I don't understand how I will receive the file with that HTTP GET request. All the examples I have seen was about uploading a file. I already did it. I can upload .exe, image, .pdf, anything and when I download them back (by my browser), there are no errors. Can you help me with the downloading part? Can you give me an example beacuse I really didn't get it.</p>

答: You need to read the HTTP response from the same socket on which you put the request. As a starting point, just print it out. When you are familiar with it, start parsing it. The file will be in there.</p>


问:
Docker to run new container - list of all mapped ports?
When running a new container, we specify a port RUN_PORT:EXPOSED_PORT to map with the host machine. This will fail if RUN_PORT is already used.

So my question is how to list all the mapped port - so that we can pick up the port number out of the list.

p.s.

I'm using Ubuntu 16.04

答:
Do the following command

```<code>sudo netstat -tlnp | grep ":RUN_PORT"
</code>```

Replace RUN_PORT with the actual port to see which application is blocking it.

Body:
Do the following command

sudo netstat -tlnp | grep ":RUN_PORT"

Replace RUN_PORT with the actual port to see which application is blocking it.


问:
Linking a third model in EF CORE
This is the EF CORE setup I have at the moment.

Telephone model

```<code>[ForeignKey("TelNoTypeID")]
public int? TelNoTypeID { get; set; }
public DropDown TelNoType { get; set; }
</code>```

Person model

```<code>public ICollection<Telephone> TelephoneIDs { get; set; }
</code>```

I've also tried using

```<code>public virtual ICollection<Telephone> TelephoneIDs { get; set; }
</code>```

DropDown model

```<code>public int DropDownID { get; set; }
public string DisplayText { get; set; }
</code>```

Person controller

```<code>public async Task<IActionResult> Details(int? id)
{
    var person = await _context.Persons
        .Include(p => p.Gender)
        .Include(p => p.Title)
        .Include(p => p.AddressIDs)
        .Include(p => p.TelephoneIDs)
        .SingleOrDefaultAsync(m => m.PersonID == id);
</code>```

So a collection of Telephone numbers are stored against the Person model.

This brings back from the database and displays on the screen the numeric value from the field

```<code>Telephones.TelNoTypeID
</code>```

The equivalent SQL to what I have is

```<code>select Telephones.TelNoTypeID from Person
inner join Telephones on Telephones.PersonID = Person.PersonID
</code>```

I need to display the linked text value instead which is stored in

```<code>DropDown.displaytext
</code>```

The equivalent SQL to what I need is

```<code>select DropDown.displaytext from Person
inner join Telephones on Telephones.PersonID = Person.PersonID
inner join DropDown on DropDown.DropDownID = Telephones.TelNoTypeID
</code>```

I've tried using

```<code>.ThenInclude(p => p.<something>)
</code>```

but the Dot notation just refers to the generic collection properties/methods, not back to my person, dropdown or telephone models

I've linked the Person model directly to the Dropdown model using and displaying the dropdown.displaytext with

Person model

```<code>[ForeignKey("GenderID")]
public int? GenderID { get; set; }
public virtual DropDown Gender { get; set; }
</code>```

but despite putting the same code into telephone, it's not working

How can I link a third model (DropDown) to a second model (Telephone)?

Thanks

答:
I was trying to link to the DropDown model, turns out I needed to link to the property, so

```<code>    var person = await _context.Persons
        .Include(p => p.Gender)
        .Include(p => p.Title)
        .Include(p => p.AddressIDs)
        .Include(p => p.TelephoneIDs)
            .ThenInclude(p => p.TelNoType)
        //.Include("TelephoneIDs.TelNoType.DisplayText")
        .SingleOrDefaultAsync(m => m.PersonID == id);
</code>```

I don't understand why, I'm presuming it's because the links already exist between the 3 models and the ThenInclude points to the exact property I'm trying to link with/to.

Title: Linking a third model in EF CORE

Body:
This is the EF CORE setup I have at the moment.

Telephone model

[ForeignKey("TelNoTypeID")]
public int? TelNoTypeID { get; set; }
public DropDown TelNoType { get; set; }

Person model

public ICollection<Telephone> TelephoneIDs { get; set; }

I've also tried using

public virtual ICollection<Telephone> TelephoneIDs { get; set; }

DropDown model

public int DropDownID { get; set; }
public string DisplayText { get; set; }

Person controller

public async Task<IActionResult> Details(int? id)
{
    var person = await _context.Persons
        .Include(p => p.Gender)
        .Include(p => p.Title)
        .Include(p => p.AddressIDs)
        .Include(p => p.TelephoneIDs)
        .SingleOrDefaultAsync(m => m.PersonID == id);

So a collection of Telephone numbers are stored against the Person model.

This brings back from the database and displays on the screen the numeric value from the field

Telephones.TelNoTypeID

The equivalent SQL to what I have is

select Telephones.TelNoTypeID from Person
inner join Telephones on Telephones.PersonID = Person.PersonID

I need to display the linked text value instead which is stored in

DropDown.displaytext

The equivalent SQL to what I need is

select DropDown.displaytext from Person
inner join Telephones on Telephones.PersonID = Person.PersonID
inner join DropDown on DropDown.DropDownID = Telephones.TelNoTypeID

I've tried using

.ThenInclude(p => p.<something>)

but the Dot notation just refers to the generic collection properties/methods, not back to my person, dropdown or telephone models

I've linked the Person model directly to the Dropdown model using and displaying the dropdown.displaytext with

Person model

[ForeignKey("GenderID")]
public int? GenderID { get; set; }
public virtual DropDown Gender { get; set; }

but despite putting the same code into telephone, it's not working

How can I link a third model (DropDown) to a second model (Telephone)?

Thanks

Body:
I was trying to link to the DropDown model, turns out I needed to link to the property, so

    var person = await _context.Persons
        .Include(p => p.Gender)
        .Include(p => p.Title)
        .Include(p => p.AddressIDs)
        .Include(p => p.TelephoneIDs)
            .ThenInclude(p => p.TelNoType)
        //.Include("TelephoneIDs.TelNoType.DisplayText")
        .SingleOrDefaultAsync(m => m.PersonID == id);

I don't understand why, I'm presuming it's because the links already exist between the 3 models and the ThenInclude points to the exact property I'm trying to link with/to.


问:
Calendar.getInstance gives wrong date
I create few small methods as an Util class, like the following code:

```<code>public class Util
{
  public static final String DATETIME_PATTERN="YYYY/MM/DD - HH:mm:ss";

  public static String getDateTime()
  {
    SimpleDateFormat sdf=new SimpleDateFormat(DATETIME_PATTERN);
    return sdf.format(getToday());
  }

  public static Date getToday()
  {
    //Calendar today=Calendar.getInstance(); //didn't help
    Calendar today=Calendar.getInstance(Locale.TAIWAN); //didn't fix
    //Calendar today=Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00")); //didn't fix as well
    return today.getTime();
  }
}
</code>```

And, did a very simple run, like this:

```<code>//run in main class
System.out.println("Generating sitemap.xml, please wait..."+Util.getDateTime());
</code>```

The result is a quite weird date -> 2017/07/187

```<code>//Console result:
Generating sitemap.xml, please wait...2017/07/187 - 15:27:21
</code>```

Searched for similar question, and tried TimeZone, Locale, but didn't help.
Any suggestions ?

BTW, here's my environment:

Windows7 x86

JDK 1.8.0.131 x86

eclipse oxygen x86

答:
It's a problem with the way you are formatting the date.
Try changing it to this</p>

```<code>  public static final String DATETIME_PATTERN="yyyy/MM/dd - HH:mm:ss";
</code>```

Title: Calendar.getInstance gives wrong date

Body:
I create few small methods as an Util class, like the following code:

public class Util
{
  public static final String DATETIME_PATTERN="YYYY/MM/DD - HH:mm:ss";

  public static String getDateTime()
  {
    SimpleDateFormat sdf=new SimpleDateFormat(DATETIME_PATTERN);
    return sdf.format(getToday());
  }

  public static Date getToday()
  {
    //Calendar today=Calendar.getInstance(); //didn't help
    Calendar today=Calendar.getInstance(Locale.TAIWAN); //didn't fix
    //Calendar today=Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00")); //didn't fix as well
    return today.getTime();
  }
}

And, did a very simple run, like this:

//run in main class
System.out.println("Generating sitemap.xml, please wait..."+Util.getDateTime());

The result is a quite weird date -> 2017/07/187

//Console result:
Generating sitemap.xml, please wait...2017/07/187 - 15:27:21

Searched for similar question, and tried TimeZone, Locale, but didn't help.
Any suggestions ?

BTW, here's my environment:

Windows7 x86

JDK 1.8.0.131 x86

eclipse oxygen x86

Body:
It's a problem with the way you are formatting the date.
Try changing it to this

  public static final String DATETIME_PATTERN="yyyy/MM/dd - HH:mm:ss";


问:
Creating outlets and actions on object from Interface Builder
In the initial lecture "1. Introduction to Mac OS X, Cocoa touch, Objective-C and Tools" the students are instructed to drag an "Object" into interface builder and set the class actions and outlets. I do not seem to have this ability in my interface builder. Was it removed or disabled in more recent versions?</p>

答:
The class actions and outlets panes have been moved to the library window in newer versions of Interface Builder

Click on the Classes tab, then search for your class.

Click on your class, then use the drop-down menu to select outlets or actions.


问:
How to split a string into command line arguments like the shell in python?
I have command line arguments in a string and I need to split it to feed to argparse.ArgumentParser.parse_args.

I see that the documentation uses string.split() plentifully. However in complex cases, this does not work, such as

```<code>--foo "spaces in brakets"  --bar escaped\ spaces
</code>```

Is there a functionality to do that in python?

(A similar question for java was asked here).

答: This is what shlex.split was created for.

Body:
I have command line arguments in a string and I need to split it to feed to argparse.ArgumentParser.parse_args.

I see that the documentation uses string.split() plentifully. However in complex cases, this does not work, such as

--foo "spaces in brakets"  --bar escaped\ spaces

Is there a functionality to do that in python?

(A similar question for java was asked here).


问:
Can I slow down the speed of a batch file?
I am trying to write an ASCII movie in batch, and I need the script to echo a new line at about 10-15 lines per second (hopefully that's not too confusing). By default, the script goes insanely fast, making the whole thing more difficult to see.

What I would like to do is be able to set the execution speed of the batch file, and NOT the computer itself.

Here's an example of what I'd like:

```<code>@echo off
REM Below command sets script execution speed in lines per second
setspeed=10lps
REM Ten lines of 03 begin
echo The time is 13:20:03
echo The time is 13:20:03
echo The time is 13:20:03
echo The time is 13:20:03
echo The time is 13:20:03
echo The time is 13:20:03
echo The time is 13:20:03
echo The time is 13:20:03
echo The time is 13:20:03
REM Ten lines of 03 end
REM Ten lines of 04 begin
echo The time is 13:20:04
echo The time is 13:20:04
.....
</code>```

Thanks!

答:
I like using choice commands. For instance:

```<code>@echo off
echo this is one line
choice /c q /d q /t 1 >nul
echo this is the second line
</code>```

You can change the number after /t to set the seconds to wait. You can also press Q to skip the wait at any time.

Body:
I am trying to write an ASCII movie in batch, and I need the script to echo a new line at about 10-15 lines per second (hopefully that's not too confusing). By default, the script goes insanely fast, making the whole thing more difficult to see.

What I would like to do is be able to set the execution speed of the batch file, and NOT the computer itself.

Here's an example of what I'd like:

@echo off
REM Below command sets script execution speed in lines per second
setspeed=10lps
REM Ten lines of 03 begin
echo The time is 13:20:03
echo The time is 13:20:03
echo The time is 13:20:03
echo The time is 13:20:03
echo The time is 13:20:03
echo The time is 13:20:03
echo The time is 13:20:03
echo The time is 13:20:03
echo The time is 13:20:03
REM Ten lines of 03 end
REM Ten lines of 04 begin
echo The time is 13:20:04
echo The time is 13:20:04
.....

Thanks!

Body:
I like using choice commands. For instance:

@echo off
echo this is one line
choice /c q /d q /t 1 >nul
echo this is the second line

You can change the number after /t to set the seconds to wait. You can also press Q to skip the wait at any time.


问:
How to merge two user tables and associated usermeta tables
I have 2 similar databases both having user and usermeta tables. I need to merge these tables.
So there are 2 user tables like these

and 2 usermeta tables like these

from which I want to generate the merged user and usermeta tables

I am able to merge the user tables (obviously!) by just inserting the values from user table 2 (without IDs) to user table 1, giving me me the new user table 1 and the lookup between old and new IDs of the added users

What is a good way of now replacing the old user_id values in usermeta 2 table data, so that i can insert them in the usermeta 1 table to merge it i.e. I want to get this from usermeta 2

I can do it in Excel/CSV through vlookup, but sometimes converting data from SQL to Excel/CSV and back is tricky

答:
If you want to use the autoincrement feature to get the new id (by inserting the data without id), you HAVE TO add a column with the old primary key to your new user table (which you can drop after your merge is done). The primary key identifies a row, and if you remove it, you will not be able to link your old and your new ids anymore. So use e.g.

```<code>insert into newuser (id, email, ..., old_id)
select null, email, ... , id
from user2
</code>```

Your lookup table is now automatically available, and will simply be select id, old_id from newuser. Since you want to let MySQL decide on the new (autoincrement) id during the merge, you obviously cannot generate a lookup table before the merge.

Using this information, to insert the meta values from your second database, you can then use e.g.

```<code>insert into newusermeta (id, user_id, ..., old_id)
select null, lookup.id, ... usermeta2.id
from usermeta2
left join (select id, old_id from newuser) as lookup
on lookup.old_id = usermeta2.id
</code>```

Your meta-lookuptable in the form you had it in your question will similarly be

```<code>select newmeta.id, newmeta.user_id, newmeta.old_id, newuser.old_id
from newmeta
left join newuser on newmeta.user_id = newuser.id
</code>```

although you actually don't need the 2 userids there. Since everywhere you have to replace a metaid, it would be just the metaid without the userid, and so select id, old_id from newmeta should suffice.

The left join is used only in case you have corrupt data (e.g. meta data without users). If you are sure all parents exist, you can use a normal join (but it will then silently ignore any metadata without parents).

Things can get a lot more complicated that this though. Consider e.g. duplicates. You might have a unique index on email to prevent duplicates. If you have a user with that email in both tables, you cannot simply merge them by getting a new primary key anymore, because it will still violate the unique constraint. But you cannot simply ignore one either, as they can be different users (e.g. friends or family sharing an email) or have different details (e.g. order history or a different address because they moved). It's up to you to handle such situations and prepare your data. There is no general receipt for solving this, and actually there is a whole industry that specializes in just cleaning up such data.

An alternative to getting new ids via autoincrement would e.g. be to add a fixed value per key (which you have to define once or calculate on the fly) when you insert them, e.g. add +2 to everywhere you are using the userid, and +4 everywhere you are using the metaid, e.g.

```<code>insert into newusermeta (id, user_id, ...)
select id, user_id, ... from usermeta1
union select id+4, user_id+2, ... from usermeta2
</code>```

Here you could generate the lookup tables before the merge (since you instead of MySQL define the new keys), although they wouldn't serve much purpose, since you just add a fixed number.

Or you can update the data in (a copy of) database 2 before you merge it. Add on update cascade to every foreign key you are using (or now creating). Then simply update the primary keys, e.g.

```<code>update user2 set id = id + 2 order by id desc;
update usermeta2 set id = id + 4 order by id desc;
</code>```

and it will update the user_id in the metatable on its own. This has the advantage that the database will be consistent before you merge it. It will not work for MyISAM-tables though, as they don't support foreign keys.

Body:
If you want to use the autoincrement feature to get the new id (by inserting the data without id), you HAVE TO add a column with the old primary key to your new user table (which you can drop after your merge is done). The primary key identifies a row, and if you remove it, you will not be able to link your old and your new ids anymore. So use e.g.

insert into newuser (id, email, ..., old_id)
select null, email, ... , id
from user2

Your lookup table is now automatically available, and will simply be select id, old_id from newuser. Since you want to let MySQL decide on the new (autoincrement) id during the merge, you obviously cannot generate a lookup table before the merge.

Using this information, to insert the meta values from your second database, you can then use e.g.

insert into newusermeta (id, user_id, ..., old_id)
select null, lookup.id, ... usermeta2.id
from usermeta2
left join (select id, old_id from newuser) as lookup
on lookup.old_id = usermeta2.id

Your meta-lookuptable in the form you had it in your question will similarly be

select newmeta.id, newmeta.user_id, newmeta.old_id, newuser.old_id
from newmeta
left join newuser on newmeta.user_id = newuser.id

although you actually don't need the 2 userids there. Since everywhere you have to replace a metaid, it would be just the metaid without the userid, and so select id, old_id from newmeta should suffice.

The left join is used only in case you have corrupt data (e.g. meta data without users). If you are sure all parents exist, you can use a normal join (but it will then silently ignore any metadata without parents).

Things can get a lot more complicated that this though. Consider e.g. duplicates. You might have a unique index on email to prevent duplicates. If you have a user with that email in both tables, you cannot simply merge them by getting a new primary key anymore, because it will still violate the unique constraint. But you cannot simply ignore one either, as they can be different users (e.g. friends or family sharing an email) or have different details (e.g. order history or a different address because they moved). It's up to you to handle such situations and prepare your data. There is no general receipt for solving this, and actually there is a whole industry that specializes in just cleaning up such data.

An alternative to getting new ids via autoincrement would e.g. be to add a fixed value per key (which you have to define once or calculate on the fly) when you insert them, e.g. add +2 to everywhere you are using the userid, and +4 everywhere you are using the metaid, e.g.

insert into newusermeta (id, user_id, ...)
select id, user_id, ... from usermeta1
union select id+4, user_id+2, ... from usermeta2

Here you could generate the lookup tables before the merge (since you instead of MySQL define the new keys), although they wouldn't serve much purpose, since you just add a fixed number.

Or you can update the data in (a copy of) database 2 before you merge it. Add on update cascade to every foreign key you are using (or now creating). Then simply update the primary keys, e.g.

update user2 set id = id + 2 order by id desc;
update usermeta2 set id = id + 4 order by id desc;

and it will update the user_id in the metatable on its own. This has the advantage that the database will be consistent before you merge it. It will not work for MyISAM-tables though, as they don't support foreign keys.


问:
Google Place API keyword vs name
I am using the Google Places API and I am making a request that looks like this.

```<code>https://maps.googleapis.com/maps/api/place/radarsearch/json?location=[LOCATION]&radius=500&keyword=[STORE_NAME]&key=[API_KEY]
</code>```

The issue is that when I use the keyword in the request, the keyword looks for the value I provide in the name, address and anywhere else in the google content for a place. How can I do it so that I can give the store name and have it only search in the name field. I don't care about looking in the address.

Let me know if this doesn't make sense.

答:
Places API Radar Search has just been deprecated, and will be retired in a year.

Please see full details in blog post Removing Place Add, Delete & Radar Search features.

On a related note, for both Radar Search and Nearby Search, the name parameter is just equivalent to keyword:

name — A term to be matched against all content that Google has indexed for this place. Equivalent to keyword. The name field is no longer restricted to place names. Values in this field are combined with values in the keyword field and passed as part of the same search string. We recommend using only the keyword parameter for all search terms.

Title: Google Place API keyword vs name

Body:
I am using the Google Places API and I am making a request that looks like this.

https://maps.googleapis.com/maps/api/place/radarsearch/json?location=[LOCATION]&radius=500&keyword=[STORE_NAME]&key=[API_KEY]

The issue is that when I use the keyword in the request, the keyword looks for the value I provide in the name, address and anywhere else in the google content for a place. How can I do it so that I can give the store name and have it only search in the name field. I don't care about looking in the address.

Let me know if this doesn't make sense.


问:
LINQ query to create a list of objects where each object contains a list
I have XML describing some data like this:

```<code><People>
    <Person>
        <Name>Alice</Name>
        <Dogs>
            <Dog>Labrador</Dog>
            <Dog>German Shepherd</Dog>
        </Dogs>
    </Person>
    <Person>
        <Name>Bob</Name>
        <Dogs>
            <Dog>Poodle</Dog>
        </Dogs>
    </Person>
</People>
</code>```

And some classes:

```<code>class Person
{
   public string Name { get; set; }
   public List<Dog> Dogs { get; set; }
}

class Dogs
{
    public string Type { get; set; }
}
</code>```

I want to use linq to XML to query this data, so that I can create a set of Person objects with the Dog collection for each populated. How do I do this? Something like:

```<code> var doc = XDocument.Load("Test.xml");
 var enumerableOfPeople = from u in doc.Root.Descendants("Person")
                    select new Person() { Name = u.Element("Name").Value,
                                          Dogs = /* WHAT GOES HERE */ };
</code>```

答:
This will populate the Dogs:</p>

```<code>var enumerableOfPeople = from u in doc.Root.Descendants("Person")
                         select new Person()
                         {
                               Name = u.Element("Name").Value,
                               Dogs = (from d in u.Element("Dogs").Descendants("Dog")
                                       select new Dog() { Type = d.Value }).ToList()
                         };
</code>```

Body:
I have XML describing some data like this:

<People>
    <Person>
        <Name>Alice</Name>
        <Dogs>
            <Dog>Labrador</Dog>
            <Dog>German Shepherd</Dog>
        </Dogs>
    </Person>
    <Person>
        <Name>Bob</Name>
        <Dogs>
            <Dog>Poodle</Dog>
        </Dogs>
    </Person>
</People>

And some classes:

class Person
{
   public string Name { get; set; }
   public List<Dog> Dogs { get; set; }
}

class Dogs
{
    public string Type { get; set; }
}

I want to use linq to XML to query this data, so that I can create a set of Person objects with the Dog collection for each populated. How do I do this? Something like:

 var doc = XDocument.Load("Test.xml");
 var enumerableOfPeople = from u in doc.Root.Descendants("Person")
                    select new Person() { Name = u.Element("Name").Value,
                                          Dogs = /* WHAT GOES HERE */ };

Body:
This will populate the Dogs:

var enumerableOfPeople = from u in doc.Root.Descendants("Person")
                         select new Person()
                         {
                               Name = u.Element("Name").Value,
                               Dogs = (from d in u.Element("Dogs").Descendants("Dog")
                                       select new Dog() { Type = d.Value }).ToList()
                         };


问:
JOOq sparse update
I am using Jax-RS and Jooq.
I'd like to know how I should implement REST PATCH using sparse data.

Let's say I have some PoJo. I get a JSON PATCH (http://www.restapitutorial.com/lessons/httpmethods.html) request with an incomplete object which only contains those fields which are supposed to change.

How would I write such a handler?

I tried accepting the actual Pojo object. My first thought was "if a field is null, i don't update it". This was my first problem.

```<code>public Resource update(@PathParam("id") UUID id, Resource resource) {
    ResourceRecord record = dslContext.newRecord(RESOURCE, resource);
    dslContext.update(RESOURCE).set(resource).where(RESOURCE.ID.eq(id)).execute();

    // or

    memberDao.update(member);

    return resourceDao.findById(id);
}
</code>```

While trying things and searching online I thought "what about setting something to null deliberately?". So it has to depend on the presence of the field in the request.

My last idea was:

```<code>public Resource update(@PathParam("id") UUID id, Map<String, Object> changes) {
    dslContext.update(RESOURCE).set(changes).where(RESOURCE.ID.eq(id)).execute();
    return resourceDao.findById(id);
}
</code>```

which does not work, of course (set(Map< Field, ...>)).

But I'm kinda stuck and the interwebz was full of answers for different problems but I didn't find any case where someone tried the same thing.

In my mind I was playing around with reflection and loops which feels some kind of aweful. I'd like to know how I would write that code as easy as possible.

答:
I tried accepting the actual Pojo object. My first thought was "if a field is null, i don't update it". This was my first problem.

That's not how jOOQ works. The rationale is described in this blog post here. In particular, your specific line of code here:

```<code>ResourceRecord record = dslContext.newRecord(RESOURCE, resource);
</code>```

Will set all the ResourceRecord.changed() flags to true, regardless if they are null or not (so, regardless if their value has been modified through setting them from the POJO). In terms of REST, this corresponds to PUT, much more than to PATCH.

This is much better:

```<code>public Resource update(@PathParam("id") UUID id, Map<String, Object> changes) {
    dslContext.update(RESOURCE)
              .set(translate(RESOURCE, changes))
              .where(RESOURCE.ID.eq(id))
              .execute();
    return resourceDao.findById(id);
}
</code>```

You'll need a translate() function that translates your Map<String, Object> to a Map<Field<?>, Object>, looking up the field names in RESOURCE.

This should work out of the box, of course, an is currently inconsistent with remaining API. A fix is on the way: https://github.com/jOOQ/jOOQ/issues/6388

In the meantime, you can just pass the map to DSLContext.newRecord(Table, Object), which will call Record.fromMap() internally

Title: JOOq sparse update

Body:
I am using Jax-RS and Jooq.
I'd like to know how I should implement REST PATCH using sparse data.

Let's say I have some PoJo. I get a JSON PATCH (http://www.restapitutorial.com/lessons/httpmethods.html) request with an incomplete object which only contains those fields which are supposed to change.

How would I write such a handler?

I tried accepting the actual Pojo object. My first thought was "if a field is null, i don't update it". This was my first problem.

public Resource update(@PathParam("id") UUID id, Resource resource) {
    ResourceRecord record = dslContext.newRecord(RESOURCE, resource);
    dslContext.update(RESOURCE).set(resource).where(RESOURCE.ID.eq(id)).execute();

    // or

    memberDao.update(member);

    return resourceDao.findById(id);
}

While trying things and searching online I thought "what about setting something to null deliberately?". So it has to depend on the presence of the field in the request.

My last idea was:

public Resource update(@PathParam("id") UUID id, Map<String, Object> changes) {
    dslContext.update(RESOURCE).set(changes).where(RESOURCE.ID.eq(id)).execute();
    return resourceDao.findById(id);
}

which does not work, of course (set(Map< Field, ...>)).

But I'm kinda stuck and the interwebz was full of answers for different problems but I didn't find any case where someone tried the same thing.

In my mind I was playing around with reflection and loops which feels some kind of aweful. I'd like to know how I would write that code as easy as possible.

Body:
I tried accepting the actual Pojo object. My first thought was "if a field is null, i don't update it". This was my first problem.

That's not how jOOQ works. The rationale is described in this blog post here. In particular, your specific line of code here:

ResourceRecord record = dslContext.newRecord(RESOURCE, resource);

Will set all the ResourceRecord.changed() flags to true, regardless if they are null or not (so, regardless if their value has been modified through setting them from the POJO). In terms of REST, this corresponds to PUT, much more than to PATCH.

This is much better:

public Resource update(@PathParam("id") UUID id, Map<String, Object> changes) {
    dslContext.update(RESOURCE)
              .set(translate(RESOURCE, changes))
              .where(RESOURCE.ID.eq(id))
              .execute();
    return resourceDao.findById(id);
}

You'll need a translate() function that translates your Map<String, Object> to a Map<Field<?>, Object>, looking up the field names in RESOURCE.

This should work out of the box, of course, an is currently inconsistent with remaining API. A fix is on the way: https://github.com/jOOQ/jOOQ/issues/6388

In the meantime, you can just pass the map to DSLContext.newRecord(Table, Object), which will call Record.fromMap() internally


问:
Use tapi32.dll methods which takes source and destination phone number
I consume the tapi32.dll to make a function in such way that it should ask me for a from extension phone number and a to extension phone number.

I require that the source and destination phone numbers are entered manually to then get a call connected.

This is the method call I am using:

```<code>[DllImport("tapi32.dll")]
public static extern int tapiRequestMakeCall(
    string destAddress,
    string appName,
    string calledParty,
    string comment);
</code>```

Can anyone help me how to do this?

答:
This is not possible with tapiRequestMakeCall. This function only delegates the call to a another application that finally places the call.

If you want to do this all by your own, you need to do more than just calling this function. Below the description for Tapi 1.x and 2.x

lineOpen to open a line. With this call you already defined the "from" extension, with the line you are opening.

You need to call lineMakeCall. Again you have choices here to select a line and/or address. Again this may defined the from extension (depends on your TSP)

With lineMakeCall you may offer some LINECALLPARAMS were you can define more dteails to the call you are placing.

Using Tapi 3.0 (COM interface) is identical to the above. In this case you have corresponding objects to open a line and place a call.

Body:
I consume the tapi32.dll to make a function in such way that it should ask me for a from extension phone number and a to extension phone number.

I require that the source and destination phone numbers are entered manually to then get a call connected.

This is the method call I am using:

[DllImport("tapi32.dll")]
public static extern int tapiRequestMakeCall(
    string destAddress,
    string appName,
    string calledParty,
    string comment);

Can anyone help me how to do this?


问:
Echo the bottom line of a CSV
I am attempting to echo the bottom line only of a .csv file. I echo the file in reverse order (as shown below) but I'm not sure how to only echo the top line of this. Please note that the csv variable, constantly changing.

Here is my php:

<?php
$file = file("file.csv");
$file = array_reverse($file);
foreach($file as $f){
    echo $f."
";
}
?>```

答:
```<code><?php
$file = file("file.csv");
$last_line=count($file)-1;
echo $file[$last_line];
?>
</code>```

Title: Echo the bottom line of a CSV


问:
Publishing a C# console application as an Azure web job
I've got a console application, with logging, scheduling, etc., running on a VM. It works with Entity Framework, Azure SQL Server, Azure blob storage and a bunch of external APIs.

I'd like to turn it into a service.

I understand that this can be done with worker roles, but looking at various tutorials for worker roles, it seems like it would be a ton of work to rewrite the whole thing.

If I just publish it as a web job, will this be secure, assuming I don't have any exposed endpoints? I need to make sure that nobody outside our active directory can access it.

Is there a way that I can create a dummy app service which will have no endpoints and publish it there?

答:
what exactly your exe is? will someone invoke it and scheduled to run on a regular intervals?
we have couple of options here, if the processing logic is not a complex one you can go for Azure functions which uses WebJobs SDK itself but doesn't require an App Service to be configured for it.
or you can go for Azure Scheduler which can take your executable and run at a scheduled intervals.</p>


问:
How does Wordpress deal with / compile SASS?
Really simple answer possible but I've not had the chance to work with SASS yet and especially not in Wordpress so bear with me.

I'm working on a site that has been developed in Wordpress and need to make some edits to the CSS (just increase an element's min-height from 54px to 64px at the moment). It has been done using SASS and folders have been set up for the partials and imported via a main.scss.

Where I've got stuck is that I don't understand what I need to change or action to make the _general.scss file (imported via main.scss and in a folder) compile to update the style for this element. I've changed the value from 54px to 64px as it has saved in the _general.scss but this isn't reflected via the browser (if you view the actual scss page) hence it doesn't update the style.

I know I need to recompile it some how ...but how?

Sorry in advance for what is a newbie question from an experienced coder! (embarrassing!)

答:
You do not necessarily need to edit the CSS of the template. You always have other options at your disposal.

you can either create a child theme and make changes in it

you can also create a custom style sheet and import the main stylesheet in your style sheet and put your code into your stylesheet

or you can simply download a plugin which will allow you to put your custom css in the backend of wordpress and the plugin will import the custom css in the end of the main css file.

Following is a link to a plugin that will give you a window to add your custom css into:
https://wordpress.org/plugins/simple-custom-css/

Please use this and do not get messed up with SASS.


问:
Unable to open the URL into new tab even using target ="_blank"
I'm unable to open the URL into new tab. Kindly help.

Javascript :

var trackOutboundLink = function(url) {
  ga('send', 'event', 'outbound', 'click', url, {
    'transport': 'beacon',
    'hitCallback': function() {
      document.location = url;
    }
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Twitter</code>```

Thanks

答:
you are setting return false; in onclick and using document.location.

Try to change document.location to window.open function

JavaScript

```<code>var trackOutboundLink = function(url) {
  ga('send', 'event', 'outbound', 'click', url, {
    'transport': 'beacon',
    'hitCallback': function() {
      window.open(url);
    }
  });
}
</code>```

HTML

```<code><a href="https://twitter.com/" class="fa-twitter" target="_blank" onclick="trackOutboundLink('https://twitter.com/'); return false;"><span class="label">Twitter</span></a>
</code>```

Body:
I'm unable to open the URL into new tab. Kindly help.

Javascript :

var trackOutboundLink = function(url) {
  ga('send', 'event', 'outbound', 'click', url, {
    'transport': 'beacon',
    'hitCallback': function() {
      document.location = url;
    }
  });
}

Twitter

Thanks

Body:
you are setting return false; in onclick and using document.location.

Try to change document.location to window.open function

JavaScript

var trackOutboundLink = function(url) {
  ga('send', 'event', 'outbound', 'click', url, {
    'transport': 'beacon',
    'hitCallback': function() {
      window.open(url);
    }
  });
}

HTML

<a href="https://twitter.com/" class="fa-twitter" target="_blank" onclick="trackOutboundLink('https://twitter.com/'); return false;"><span class="label">Twitter</span></a>