问:
Convert Json String to C# Object List
I want to convert a json string to a Object list. Please help me. it would be more helpful if done by NewtonJson.

I tried, but its not working. I dont want all the values of that json. just which are mentioned in the MatrixModel

This is a Object

```<code>public class MatrixModel
{
    public string S1 { get; set; }
    public string S2 { get; set; }
    public string S3 { get; set; }
    public string S4 { get; set; }
    public string S5 { get; set; }
    public string S6 { get; set; }
    public string S7 { get; set; }
    public string S8 { get; set; }
    public string S9 { get; set; }
    public string S10 { get; set; }
    public int ScoreIfNoMatch { get; set; }
}
</code>```

This is the Json String

```<code>    "[
      {
        "Question": {
          "QuestionId": 49,
          "QuestionText": "Whats your name?",
          "TypeId": 1,
          "TypeName": "MCQ",
          "Model": {
            "options": [
              {
                "text": "Rahul",
                "selectedMarks": "0"
              },
              {
                "text": "Pratik",
                "selectedMarks": "9"
              },
              {
                "text": "Rohit",
                "selectedMarks": "0"
              }
            ],
            "maxOptions": 10,
            "minOptions": 0,
            "isAnswerRequired": true,
            "selectedOption": "1",
            "answerText": "",
            "isRangeType": false,
            "from": "",
            "to": "",
            "mins": "02",
            "secs": "04"
          }
        },
        "CheckType": "",
        "S1": "",
        "S2": "",
        "S3": "",
        "S4": "",
        "S5": "",
        "S6": "",
        "S7": "",
        "S8": "",
        "S9": "Pratik",
        "S10": "",
        "ScoreIfNoMatch": "2"
      },
      {
        "Question": {
          "QuestionId": 51,
          "QuestionText": "Are you smart?",
          "TypeId": 3,
          "TypeName": "True-False",
          "Model": {
            "options": [
              {
                "text": "True",
                "selectedMarks": "7"
              },
              {
                "text": "False",
                "selectedMarks": "0"
              }
            ],
            "maxOptions": 10,
            "minOptions": 0,
            "isAnswerRequired": false,
            "selectedOption": "3",
            "answerText": "",
            "isRangeType": false,
            "from": "",
            "to": "",
            "mins": "01",
            "secs": "04"
          }
        },
        "CheckType": "",
        "S1": "",
        "S2": "",
        "S3": "",
        "S4": "",
        "S5": "",
        "S6": "",
        "S7": "True",
        "S8": "",
        "S9": "",
        "S10": "",
        "ScoreIfNoMatch": "2"
      }
    ]"
</code>```

答:
Please make sure that all properties are both the getter and setter. In case, any property is getter only, it will cause the reverting the List to original data as the JSON string is typed.

Please refer to the following code snippet for the same:
Model:

```<code> public class Person
{
    public int ID { get; set; }
    // following 2 lines are cause of error
    //public string Name { get { return string.Format("{0} {1}", First, Last); } }
    //public string Country { get { return Countries[CountryID]; } }
    public int CountryID { get; set; }
    public bool Active { get; set; }
    public string First { get; set; }
    public string Last { get; set; }
    public DateTime Hired { get; set; }
}
public class ModelObj
    {
        public string Str { get; set; }
        public List<Person> Persons { get; set; }
    }
</code>```

Controller:

```<code> [HttpPost]
    public ActionResult Index(FormCollection collection)
    {
        var data = new ModelObj();
        data.Str = (string)collection.GetValue("Str").ConvertTo(typeof(string));
        var personsString = (string)collection.GetValue("Persons").ConvertTo(typeof(string));
        using (var textReader = new StringReader(personsString))
        {
            using (var reader = new JsonTextReader(textReader))
            {
                data.Persons = new JsonSerializer().Deserialize(reader, typeof(List<Person>)) as List<Person>;
            }
        }

        return View(data);
    }
</code>```

Title: Convert Json String to C# Object List

Body:
I want to convert a json string to a Object list. Please help me. it would be more helpful if done by NewtonJson.

I tried, but its not working. I dont want all the values of that json. just which are mentioned in the MatrixModel

This is a Object

public class MatrixModel
{
    public string S1 { get; set; }
    public string S2 { get; set; }
    public string S3 { get; set; }
    public string S4 { get; set; }
    public string S5 { get; set; }
    public string S6 { get; set; }
    public string S7 { get; set; }
    public string S8 { get; set; }
    public string S9 { get; set; }
    public string S10 { get; set; }
    public int ScoreIfNoMatch { get; set; }
}

This is the Json String

    "[
      {
        "Question": {
          "QuestionId": 49,
          "QuestionText": "Whats your name?",
          "TypeId": 1,
          "TypeName": "MCQ",
          "Model": {
            "options": [
              {
                "text": "Rahul",
                "selectedMarks": "0"
              },
              {
                "text": "Pratik",
                "selectedMarks": "9"
              },
              {
                "text": "Rohit",
                "selectedMarks": "0"
              }
            ],
            "maxOptions": 10,
            "minOptions": 0,
            "isAnswerRequired": true,
            "selectedOption": "1",
            "answerText": "",
            "isRangeType": false,
            "from": "",
            "to": "",
            "mins": "02",
            "secs": "04"
          }
        },
        "CheckType": "",
        "S1": "",
        "S2": "",
        "S3": "",
        "S4": "",
        "S5": "",
        "S6": "",
        "S7": "",
        "S8": "",
        "S9": "Pratik",
        "S10": "",
        "ScoreIfNoMatch": "2"
      },
      {
        "Question": {
          "QuestionId": 51,
          "QuestionText": "Are you smart?",
          "TypeId": 3,
          "TypeName": "True-False",
          "Model": {
            "options": [
              {
                "text": "True",
                "selectedMarks": "7"
              },
              {
                "text": "False",
                "selectedMarks": "0"
              }
            ],
            "maxOptions": 10,
            "minOptions": 0,
            "isAnswerRequired": false,
            "selectedOption": "3",
            "answerText": "",
            "isRangeType": false,
            "from": "",
            "to": "",
            "mins": "01",
            "secs": "04"
          }
        },
        "CheckType": "",
        "S1": "",
        "S2": "",
        "S3": "",
        "S4": "",
        "S5": "",
        "S6": "",
        "S7": "True",
        "S8": "",
        "S9": "",
        "S10": "",
        "ScoreIfNoMatch": "2"
      }
    ]"

Body:
Please make sure that all properties are both the getter and setter. In case, any property is getter only, it will cause the reverting the List to original data as the JSON string is typed.

Please refer to the following code snippet for the same:
Model:

 public class Person
{
    public int ID { get; set; }
    // following 2 lines are cause of error
    //public string Name { get { return string.Format("{0} {1}", First, Last); } }
    //public string Country { get { return Countries[CountryID]; } }
    public int CountryID { get; set; }
    public bool Active { get; set; }
    public string First { get; set; }
    public string Last { get; set; }
    public DateTime Hired { get; set; }
}
public class ModelObj
    {
        public string Str { get; set; }
        public List<Person> Persons { get; set; }
    }

Controller:

 [HttpPost]
    public ActionResult Index(FormCollection collection)
    {
        var data = new ModelObj();
        data.Str = (string)collection.GetValue("Str").ConvertTo(typeof(string));
        var personsString = (string)collection.GetValue("Persons").ConvertTo(typeof(string));
        using (var textReader = new StringReader(personsString))
        {
            using (var reader = new JsonTextReader(textReader))
            {
                data.Persons = new JsonSerializer().Deserialize(reader, typeof(List<Person>)) as List<Person>;
            }
        }

        return View(data);
    }


来源: stackexchange

问:
I want to combine two dataframe with the same names columns in pandas
I would like to combine these Dataframe:

```<code>df_a = pd.DataFrame(data={
    'Nombre': [Elisa Perez],
    'Fecha': [2/04/2019],
    'Sexo': [np.nan],
    'Nacionalidad': [np.nan],
    'Ciudad': [Roma]})

df_b = pd.DataFrame(data={
    'Nombre': [Elisa Perez],
    'Fecha': [2/04/2019],
    'Sexo': [mujer],
    'Nacionalidad': [Italiana],
    'Ciudad': [Roma]})
</code>```

and I want automatically this result without have to write each columns names in the code:

```<code>    Nombre       Fecha       Sexo       Nacionalidad       Ciudad
0 Elisa Perez  2/04/2019     mujer       Italiana           Roma
</code>```

Thanks!!

答:
Use DataFrame.combine_first with DataFrame.set_index for columns for matching:

```<code>df = (df_b.set_index(['Nombre','Fecha'])
          .combine_first(df_a.set_index(['Nombre','Fecha']))
          .reset_index())
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to combine these Dataframe:

df_a = pd.DataFrame(data={
    'Nombre': [Elisa Perez],
    'Fecha': [2/04/2019],
    'Sexo': [np.nan],
    'Nacionalidad': [np.nan],
    'Ciudad': [Roma]})

df_b = pd.DataFrame(data={
    'Nombre': [Elisa Perez],
    'Fecha': [2/04/2019],
    'Sexo': [mujer],
    'Nacionalidad': [Italiana],
    'Ciudad': [Roma]})

and I want automatically this result without have to write each columns names in the code:

    Nombre       Fecha       Sexo       Nacionalidad       Ciudad
0 Elisa Perez  2/04/2019     mujer       Italiana           Roma

Thanks!!

Body:
Use DataFrame.combine_first with DataFrame.set_index for columns for matching:

df = (df_b.set_index(['Nombre','Fecha'])
          .combine_first(df_a.set_index(['Nombre','Fecha']))
          .reset_index())


问:
Why am I obtaining these alter database error trying to create a DB using a DDL script obtained from SQL Server 2012 on SQL Server 2008?
I am pretty new to SQL Server, and I am finding the following difficulties.

I extract the DDL to create a database from a SQL Server 2012 machine, then I run this DDL creating the database on an old SQL Server 2008 instance, and I am getting the following errors:

Msg 102, Level 15, State 6, Line 1

  Incorrect syntax near 'FILESTREAM'.

Msg 102, Level 15, State 6, Line 1

  Incorrect syntax near 'TARGET_RECOVERY_TIME'.

The first error is on this line:

```<code>ALTER DATABASE [SIGLA-AZIENDA_SIGLA-AOO] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )
GO
</code>```

The second error is on this line:

```<code>ALTER DATABASE [SIGLA-AZIENDA_SIGLA-AOO] SET TARGET_RECOVERY_TIME = 0 SECONDS
GO
</code>```

What could be the causes of these error? Is related to the different version of SQL Server? From what I know the involved project is not using something like BLOB field so I think that FILESTREAM are not mandatory.

How can I try to solve these issues?

答:
Because the SQL Server features supporting is different through the versions.

To solve your problem click the Advanced button from the Set Scripting Options dialog, and change the Script for Server Version to SQL Server 2008, then we can get the script for SQL Server 2008 Database like below:

This msdn link is about another problem similar to yours:
https://social.msdn.microsoft.com/Forums/en-US/e1d75d41-d755-4a43-aaa7-2a109477177b/errors-on-script-while-parsing?forum=sqlexpress

Body:
I am pretty new to SQL Server, and I am finding the following difficulties.

I extract the DDL to create a database from a SQL Server 2012 machine, then I run this DDL creating the database on an old SQL Server 2008 instance, and I am getting the following errors:

Msg 102, Level 15, State 6, Line 1

  Incorrect syntax near 'FILESTREAM'.

Msg 102, Level 15, State 6, Line 1

  Incorrect syntax near 'TARGET_RECOVERY_TIME'.

The first error is on this line:

ALTER DATABASE [SIGLA-AZIENDA_SIGLA-AOO] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )
GO

The second error is on this line:

ALTER DATABASE [SIGLA-AZIENDA_SIGLA-AOO] SET TARGET_RECOVERY_TIME = 0 SECONDS
GO

What could be the causes of these error? Is related to the different version of SQL Server? From what I know the involved project is not using something like BLOB field so I think that FILESTREAM are not mandatory.

How can I try to solve these issues?


问:
Is there a reference document for async aware AppCompatActivity overrides?
I would like to know if there is a reference document that carefully lists all AppCompatActivity overrides that may be declared async.

For instance, I could mark:

protected override void OnCreate(Android.OS.Bundle savedInstanceState)

async like this:

protected override async void OnCreate(Android.OS.Bundle savedInstanceState)

As you can see I'm using async void, not async Task. So Because it is probably the top level async method, it is marked async void.

If there is something out there that goes beyond the scope of AppCompatActivity, that would be a must.

答: It's quite common to make event handlers async void but in this case it's possible that OnResume runs before the Activity is fully initialised in async OnCreate . Since we have no control over whether OnCreate is awaited, the only proper solution is to move long running tasks out with initialisation which is probably a good idea anyway.</p>


问:
how secure is the Ticket.UserData in User.Identity in asp.net
My website uses ASP.NET's forms authentication and i am inserting user specific information into the UserData portion of the authentication ticket/cookie. Since the UserData is inside the authentication ticket it is encrypted like so

```<code>authCookie.Value = FormsAuthentication.Encrypt(newTicket);
</code>```

Now I am not too worried about the data being compromised at this point since it's encrypted. but i noticed that the data is available in unencrypted form like this

```<code>FormsIdentity fid = User.Identity as FormsIdentity;
string plainTextUserData = fid.Ticket.UserData;
</code>```

The data itself is not too important. i am still ok even if other people can see it. but i cannot allow people to hijack this information and start using it as their own. for example, i don't want one user to be logged in pretending to be a different user (based on the userID contained in UserData

Is this something I have to worry about?

Edit 1:

The reason i want to do this is so i can stop using sessions and just use cookies and Ticket.UserData

Edit 2:

The data in Ticket.UserData is not changing. it's constant once the user is logged in.

答: It is as secure as the authentication ticket. Since you are using it for the very same purpose, don't worry about it.</p>

ContentLicense: CC BY-SA 2.5

Body:
My website uses ASP.NET's forms authentication and i am inserting user specific information into the UserData portion of the authentication ticket/cookie. Since the UserData is inside the authentication ticket it is encrypted like so

authCookie.Value = FormsAuthentication.Encrypt(newTicket);

Now I am not too worried about the data being compromised at this point since it's encrypted. but i noticed that the data is available in unencrypted form like this

FormsIdentity fid = User.Identity as FormsIdentity;
string plainTextUserData = fid.Ticket.UserData;

The data itself is not too important. i am still ok even if other people can see it. but i cannot allow people to hijack this information and start using it as their own. for example, i don't want one user to be logged in pretending to be a different user (based on the userID contained in UserData

Is this something I have to worry about?

Edit 1:

The reason i want to do this is so i can stop using sessions and just use cookies and Ticket.UserData

Edit 2:

The data in Ticket.UserData is not changing. it's constant once the user is logged in.

LastEditorDisplayName: Rich B

OwnerDisplayName: Freddy Rios


答:
Yes, it is related to the SQL Server version.

FileStream was introduced in 2012 as documented in the Alter database set options page:

<FILESTREAM_option> ::=
  Applies to: SQL Server ( SQL Server 2012 (11.x) through SQL Server 2017)

Same goes for target_recovery_time (documented in the same page):

<target_recovery_time_option> ::=
  Applies to: SQL Server (SQL Server 2012 (11.x) through SQL Server 2017)

Title: Why am I obtaining these alter database error trying to create a DB using a DDL script obtained from SQL Server 2012 on SQL Server 2008?


问:
TCL problem: imported function get bracket({}) added around the "text"
I have a "library" type file that where I define a namespace and export some functions to "print" debug info or "trace" info in TCL.

```<code>proc cputs  { args } {
    puts "Test= $args"
}
</code>```

I import this function in multiple other files.  When I use it everything is fine except it add bracket to the output.

Like if I call cputs "Hi there" it will output {Hi there} instead of Hi there.

Can't find anything to explain that.  I would like to get ride of those brackets.

Any help would be appreciated.

Thanks

答:
If you want to take an arbitrary number of arguments (since args is a special name), you should join or concat things before printing. These two options differ in their treatment of extra whitespace; use the one that suits you.

```<code>proc cputs { args } {
    puts "Test= [join $args]"
}

cputs "Hello there   " "   from an example"
# Test= Hello there      from an example
</code>```

```<code>proc cputs { args } {
    puts "Test= [concat {*}$args]"
}

cputs "Hello there   " "   from an example"
# Test= Hello there from an example
</code>```

Body:
I have a "library" type file that where I define a namespace and export some functions to "print" debug info or "trace" info in TCL.

proc cputs  { args } {
    puts "Test= $args"
}

I import this function in multiple other files.  When I use it everything is fine except it add bracket to the output.

Like if I call cputs "Hi there" it will output {Hi there} instead of Hi there.

Can't find anything to explain that.  I would like to get ride of those brackets.

Any help would be appreciated.

Thanks

Body:
If you want to take an arbitrary number of arguments (since args is a special name), you should join or concat things before printing. These two options differ in their treatment of extra whitespace; use the one that suits you.

proc cputs { args } {
    puts "Test= [join $args]"
}

cputs "Hello there   " "   from an example"
# Test= Hello there      from an example

proc cputs { args } {
    puts "Test= [concat {*}$args]"
}

cputs "Hello there   " "   from an example"
# Test= Hello there from an example


问:
C++ socket option reuse port
I have a problem with a c++ socket.

I'm using CAsyncSocket from MFC that i want to join a multicast group.

Also I need to have multiple listener on this group and here is where i get in trouble.

I found some examples on the web but it doesn't seems to work.

Here is my code:

```<code>//create socket on port 17233
BOOL bRet = Create(17233,SOCK_DGRAM, FD_READ);

//set reuse socket option
BOOL bMultipleApps = TRUE;
bRet = SetSockOpt(SO_REUSEADDR, (void*)&bMultipleApps, sizeof(BOOL), SOL_SOCKET);

//join multicast group
ip_mreq m_mrMReq;           // Contains IP and interface of the host group
m_mrMReq.imr_multiaddr.s_addr = inet_addr((LPCSTR)"224.30.0.1");    /* group addr */
m_mrMReq.imr_interface.s_addr = htons(INADDR_ANY);      /* use default */

int uRes =setsockopt(m_hSocket, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char FAR *)&m_mrMReq, sizeof(m_mrMReq));
</code>```

There are no errors when i run this.

But when i try to run another instance of the app it fails to create a new socket on that port because the port is in use.

I have done this in C# and it worked fine like this:

```<code>IPEndPoint ipep = new IPEndPoint(IPAddress.Any, port);
s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
s.Bind(ipep);
IPAddress ip = IPAddress.Parse(mcastGroup);
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, IPAddress.Any));
s.SetSocketOption(SocketOptionLevel.IP,SocketOptionName.MulticastTimeToLive, int.Parse("1"));
</code>```

So if any body sees a problem with my code or have some tips i will gladly appreciated.

EDIT 1:

Is CAsyncSocket a TCP socket?

EDIT 2:
After reading Can two applications listen to the same port?

I think i made a confusion. I need a Multicast UDP port that can be access by multiple application using SO_REUSEADDR

Edit for Clarification:

```<code>BOOL bRet = Create(17233,SOCK_DGRAM, FD_READ)
</code>```

Creates an UDP socket and bind's to to port 17223.

For SetSockOpt(SO_REUSEADDR, (void*)&bMultipleApps, sizeof(BOOL), SOL_SOCKET); to work you need to set it before binding  as @Hasturkun said.

The final working code looks like this:

```<code>    BOOL bRet = Socket(SOCK_DGRAM, FD_READ);
    if(bRet != TRUE)
    {
        UINT uErr = GetLastError();
        std::cout<<"Error:"<<uErr<<std::endl;
        return FALSE;
    }else{
        std::cout<<"Create sock: OK"<<std::endl;
    }

    //add reuse
    BOOL bMultipleApps = TRUE;      /* allow reuse of local port if needed */
    SetSockOpt(SO_REUSEADDR, (void*)&bMultipleApps, sizeof(BOOL), SOL_SOCKET);

    //bind
    bRet = Bind(17233, NULL);
    if(bRet != TRUE)
    {
        UINT uErr = GetLastError();
        std::cout<<"Error(BIND):"<<uErr<<std::endl;
    }else{
        std::cout<<"BIND sock: OK"<<std::endl;
    }
</code>```

Thanks,

Gabriel

;

答:
If boost is an option for you, consider using Asio for this. It is very straight-forward and this example shows a simple multicast receiver.

The important part for multiple listeners is:

```<code>socket_.set_option(boost::asio::ip::udp::socket::reuse_address(true));
</code>```

If you're unclear what your application is doing, just run netstat and you'll see e.g. the sockets and how they are bound (IP, port and protocol):

```<code>netstat -an
</code>```

...and look for the port you're interested in. If you run multiple applications listening to the same port you should see multiple entries for the same port with UDP as protocol.

ContentLicense: CC BY-SA 3.0

Title: C++ socket option reuse port

Body:
I have a problem with a c++ socket.

I'm using CAsyncSocket from MFC that i want to join a multicast group.

Also I need to have multiple listener on this group and here is where i get in trouble.

I found some examples on the web but it doesn't seems to work.

Here is my code:

//create socket on port 17233
BOOL bRet = Create(17233,SOCK_DGRAM, FD_READ);

//set reuse socket option
BOOL bMultipleApps = TRUE;
bRet = SetSockOpt(SO_REUSEADDR, (void*)&bMultipleApps, sizeof(BOOL), SOL_SOCKET);

//join multicast group
ip_mreq m_mrMReq;           // Contains IP and interface of the host group
m_mrMReq.imr_multiaddr.s_addr = inet_addr((LPCSTR)"224.30.0.1");    /* group addr */
m_mrMReq.imr_interface.s_addr = htons(INADDR_ANY);      /* use default */

int uRes =setsockopt(m_hSocket, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char FAR *)&m_mrMReq, sizeof(m_mrMReq));

There are no errors when i run this.

But when i try to run another instance of the app it fails to create a new socket on that port because the port is in use.

I have done this in C# and it worked fine like this:

IPEndPoint ipep = new IPEndPoint(IPAddress.Any, port);
s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
s.Bind(ipep);
IPAddress ip = IPAddress.Parse(mcastGroup);
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, IPAddress.Any));
s.SetSocketOption(SocketOptionLevel.IP,SocketOptionName.MulticastTimeToLive, int.Parse("1"));

So if any body sees a problem with my code or have some tips i will gladly appreciated.

EDIT 1:

Is CAsyncSocket a TCP socket?

EDIT 2:
After reading Can two applications listen to the same port?

I think i made a confusion. I need a Multicast UDP port that can be access by multiple application using SO_REUSEADDR

Edit for Clarification:

BOOL bRet = Create(17233,SOCK_DGRAM, FD_READ)

Creates an UDP socket and bind's to to port 17223.

For SetSockOpt(SO_REUSEADDR, (void*)&bMultipleApps, sizeof(BOOL), SOL_SOCKET); to work you need to set it before binding  as @Hasturkun said.

The final working code looks like this:

    BOOL bRet = Socket(SOCK_DGRAM, FD_READ);
    if(bRet != TRUE)
    {
        UINT uErr = GetLastError();
        std::cout<<"Error:"<<uErr<<std::endl;
        return FALSE;
    }else{
        std::cout<<"Create sock: OK"<<std::endl;
    }

    //add reuse
    BOOL bMultipleApps = TRUE;      /* allow reuse of local port if needed */
    SetSockOpt(SO_REUSEADDR, (void*)&bMultipleApps, sizeof(BOOL), SOL_SOCKET);

    //bind
    bRet = Bind(17233, NULL);
    if(bRet != TRUE)
    {
        UINT uErr = GetLastError();
        std::cout<<"Error(BIND):"<<uErr<<std::endl;
    }else{
        std::cout<<"BIND sock: OK"<<std::endl;
    }

Thanks,

Gabriel

;

Body:
If boost is an option for you, consider using Asio for this. It is very straight-forward and this example shows a simple multicast receiver.

The important part for multiple listeners is:

socket_.set_option(boost::asio::ip::udp::socket::reuse_address(true));

If you're unclear what your application is doing, just run netstat and you'll see e.g. the sockets and how they are bound (IP, port and protocol):

netstat -an

...and look for the port you're interested in. If you run multiple applications listening to the same port you should see multiple entries for the same port with UDP as protocol.


问:
Regex to extract hashtags with two dot-separated parts
I'm trying to create a regular expression in order to extract some text from strings. I want to extract text from urls or normal text messages e.g.:

```<code>endpoint/?userId=#someuser.id
</code>```

OR

```<code>Hi #someuser.name, how are you?
</code>```

And from both I want to extract exactly #someuser.name from message and #someuser.id from url. There might be be many of those string to extract from the url and messages.

My regular expression currently looks like this:

```<code>(#[^\.]+?\.)([^\W]\w+\b)
</code>```

It works fine, except one for one case and I don't know how to do it - e.g.:

Those strings SHOULD NOT be matched: # .id, #.id. There must be at least one character between # and .. One or more spaces between those characters should not be matched.

How can I do it using my current regex?

答:
```<code>#(\w+)[.](\w+)
</code>```

results two groups, e.g

```<code>endpoint/?userId=#someuser.id -> group[0]=someuser and group[1]=id
</code>```

Body:
I'm trying to create a regular expression in order to extract some text from strings. I want to extract text from urls or normal text messages e.g.:

endpoint/?userId=#someuser.id

OR

Hi #someuser.name, how are you?

And from both I want to extract exactly #someuser.name from message and #someuser.id from url. There might be be many of those string to extract from the url and messages.

My regular expression currently looks like this:

(#[^\.]+?\.)([^\W]\w+\b)

It works fine, except one for one case and I don't know how to do it - e.g.:

Those strings SHOULD NOT be matched: # .id, #.id. There must be at least one character between # and .. One or more spaces between those characters should not be matched.

How can I do it using my current regex?

Body:
#(\w+)[.](\w+)

results two groups, e.g

endpoint/?userId=#someuser.id -> group[0]=someuser and group[1]=id


问:
Stack sticky element after other sticky element with dynamic height
I need to stack few sticky header elements like this:
https://webthemez.com/demo/sticky-multi-header-scroll/index.html

There are solutions for this question in stackover in here. But in my case my sticky headers have dynamic heights. Therefore not possible to hard code top position for stick headers. My code is like below:

html

```<code><div class="sticky-header1">
    Header 1 with dynamic height
</div>
<div>
    Header 1 content
</div>

<div class="sticky-header2">
    Header 2 with dynamic height
</div>
<div>
    Header 2 content
</div>
</code>```

css

```<code>.sticky-header1,
.sticky-header2
{
    position: sticky;
}
</code>```

Is it possible to set stacked sticky header in this scenario? Pure CSS solution is preferred.

答: It is not possible using pure CSS, you when if the known or constant height element and not increase element then it's possible (it's not good). Another way you use simple javascript and just calculation for element height and set CSS position top property.

Body:
I need to stack few sticky header elements like this:
https://webthemez.com/demo/sticky-multi-header-scroll/index.html

There are solutions for this question in stackover in here. But in my case my sticky headers have dynamic heights. Therefore not possible to hard code top position for stick headers. My code is like below:

html

    Header 1 with dynamic height

    Header 1 content

    Header 2 with dynamic height

    Header 2 content

css

.sticky-header1,
.sticky-header2
{
    position: sticky;
}

Is it possible to set stacked sticky header in this scenario? Pure CSS solution is preferred.


问:
String datetime insert into mysql database with codeigniter
I am having following MySQL table

```<code>EventId     ObjectKey   Title           Description     When        Duration        Where           Status
INT         CHAR(36)    VARCHAR(500)    VARCHAR(8000)   DATETIME    VARCHAR(500)    VARCHAR(500)    TINYINT
</code>```

and my PHP array is

```<code>$data = array(
    'Title' => $title,
    'Description' => $description,
    'When' => $when,
    'Duration' => $duration,
    'Where' => $where
);
</code>```

The variable $when contains 02/21/2013. When I try to insert to the table with CodeIgniter

```<code>public function insert_event($guid, $data)
{
    $CI = & get_instance();
    $CI->load->database('default');
    $CI->db->set($data);
    $CI->db->set('ObjectKey', $guid);
    $CI->db->set('Status', 1);
    $vari = $CI->db->insert('Events');
    return $vari;
}
</code>```

Everything inserted correctly except date. Can you help me on this?

答:
Simplest way to store string date in any format in mysql</p>

```<code>$srcFormat = "m/d/Y"; //convert string to php date
$destFormat = "Y-m-d" //convert php date to mysql date string

$data = array(
  'Title' => $title,
  'Description' => $description,
  'When' => DateTime::createFromFormat($srcFormat, $when)->format($destFormat),
  'Duration' => $duration,
  'Where' => $where
);
</code>```

Body:
I am having following MySQL table

EventId     ObjectKey   Title           Description     When        Duration        Where           Status
INT         CHAR(36)    VARCHAR(500)    VARCHAR(8000)   DATETIME    VARCHAR(500)    VARCHAR(500)    TINYINT

and my PHP array is

$data = array(
    'Title' => $title,
    'Description' => $description,
    'When' => $when,
    'Duration' => $duration,
    'Where' => $where
);

The variable $when contains 02/21/2013. When I try to insert to the table with CodeIgniter

public function insert_event($guid, $data)
{
    $CI = & get_instance();
    $CI->load->database('default');
    $CI->db->set($data);
    $CI->db->set('ObjectKey', $guid);
    $CI->db->set('Status', 1);
    $vari = $CI->db->insert('Events');
    return $vari;
}

Everything inserted correctly except date. Can you help me on this?

Body:
Simplest way to store string date in any format in mysql

$srcFormat = "m/d/Y"; //convert string to php date
$destFormat = "Y-m-d" //convert php date to mysql date string

$data = array(
  'Title' => $title,
  'Description' => $description,
  'When' => DateTime::createFromFormat($srcFormat, $when)->format($destFormat),
  'Duration' => $duration,
  'Where' => $where
);


问:
matplotlig speed on plot a gps point on a chart
with the following code I'm trying to add a gps point over a map using a raspberry pi 3:

```<code>from gps import *
import matplotlib.pyplot as plt
import time, inspect, os

logPath = "/home/solergy/IBUZ/LOGS/"
inputMapFilePath = logPath + "srcMap/" + "TBM-min.png"
actualOutMapFilePath = logPath + "Map_GPS"

TRX = -12.653          #top right longitude
TRY = 41.8675            #top right latitude
BLX = -12.6332          #bottom left longitude
BLY = 41.8619             #bottom left latitude

gpsd = gps(mode=WATCH_ENABLE|WATCH_NEWSTYLE)

im = plt.imread(inputMapFilePath)

try:
    while True:
        report = gpsd.next() #
        if report['class'] == 'TPV':
            GPStime =  str(getattr(report,'time',''))
            lat     = str(getattr(report,'lat',0.0))
            lon     = str(getattr(report,'lon',0.0))
            speed   =  str(getattr(report,'speed','nan'))

            # Create Image File
            pos_y = float(lat)
            pos_x = -float(lon)

            actualTime = time.strftime("%H-%M-%S", time.localtime())
            plt.text(BLX, BLY, actualTime)
            plt.imshow(im, extent=[BLX, TRX, BLY, TRY], zorder=1)
            plt.scatter(x=[pos_x], y=[pos_y], s=3, c='r', zorder=2)
            cur_axes = plt.gca()
            cur_axes.axes.get_xaxis().set_visible(False)
            cur_axes.axes.get_yaxis().set_visible(False)
            plt.savefig(actualOutMapFilePath, dpi=150, type="png")
            plt.close('all')
            print (actualTime , GPStime)

except (KeyboardInterrupt, SystemExit): #when you press ctrl+c
    f.close()
    f_now.close()
</code>```

my problem is that I need to update this map at least every second (10Hz is better). The problem is not the gps part but the matplotlib that produce this image. Any idea about how to achieve a higher speed for this code?
Antonio

答:
An obvious optimization would be avoid clearing and redrawing everything at every iteraiton, but instead updating the XY values of the dot. See How to update a plot in matplotlib?

I would expect a considerable speedup (especially from avoiding the plt.imshow call), but it is hard to promise anything about performance without access to the actual data (or even hardware).

Body:
with the following code I'm trying to add a gps point over a map using a raspberry pi 3:

from gps import *
import matplotlib.pyplot as plt
import time, inspect, os

logPath = "/home/solergy/IBUZ/LOGS/"
inputMapFilePath = logPath + "srcMap/" + "TBM-min.png"
actualOutMapFilePath = logPath + "Map_GPS"

TRX = -12.653          #top right longitude
TRY = 41.8675            #top right latitude
BLX = -12.6332          #bottom left longitude
BLY = 41.8619             #bottom left latitude

gpsd = gps(mode=WATCH_ENABLE|WATCH_NEWSTYLE)

im = plt.imread(inputMapFilePath)

try:
    while True:
        report = gpsd.next() #
        if report['class'] == 'TPV':
            GPStime =  str(getattr(report,'time',''))
            lat     = str(getattr(report,'lat',0.0))
            lon     = str(getattr(report,'lon',0.0))
            speed   =  str(getattr(report,'speed','nan'))

            # Create Image File
            pos_y = float(lat)
            pos_x = -float(lon)

            actualTime = time.strftime("%H-%M-%S", time.localtime())
            plt.text(BLX, BLY, actualTime)
            plt.imshow(im, extent=[BLX, TRX, BLY, TRY], zorder=1)
            plt.scatter(x=[pos_x], y=[pos_y], s=3, c='r', zorder=2)
            cur_axes = plt.gca()
            cur_axes.axes.get_xaxis().set_visible(False)
            cur_axes.axes.get_yaxis().set_visible(False)
            plt.savefig(actualOutMapFilePath, dpi=150, type="png")
            plt.close('all')
            print (actualTime , GPStime)

except (KeyboardInterrupt, SystemExit): #when you press ctrl+c
    f.close()
    f_now.close()

my problem is that I need to update this map at least every second (10Hz is better). The problem is not the gps part but the matplotlib that produce this image. Any idea about how to achieve a higher speed for this code?
Antonio


问:
How to compare two @ character in clojure
Please, how can I write this in clojure? I have an @ character and I want to compare it to "@".

eg (= @ "@")

gives error (ClassCastException java.lang.String cannot be cast to java.util.concurrent.Future  clojure.core/deref-future (core.clj:2206))

答:
Why do you get the error? The reader translates your example into ...

```<code>(= (deref "@"))
</code>```

The deref function tests whether the argument is deref-able (implementing IDeref). If not, it treats the argument as a future. It isn't, so it throws the confusing exception. This behaviour is a defect, albeit a minor one.

By the way, (= x) returns true for any x, if it returns at all.

Tim Clemons' answer shows what you can do about this.

Body:
Why do you get the error? The reader translates your example into ...

(= (deref "@"))

The deref function tests whether the argument is deref-able (implementing IDeref). If not, it treats the argument as a future. It isn't, so it throws the confusing exception. This behaviour is a defect, albeit a minor one.

By the way, (= x) returns true for any x, if it returns at all.

Tim Clemons' answer shows what you can do about this.


问:
strange class behavior in the python pattern decorator
I want to impose a Berserk effect on the hero.
Abstract classes: AbstractEffect and AbstractPositive (class heir), can accept the base parameter. Next, AbstractNegative will also be created. I am not sure whether the inheritance scheme is correct (Hero ---> AbstractEffect).

```<code>from abc import ABC, abstractmethod
class Hero:
    def __init__(self):
        self.stats = {"HP": 128}
    def get_stats(self):
        return self.stats.copy()

class AbstractEffect(ABC):
    def __init__(self, base):
        self.base = base
    @abstractmethod
    def get_stats(self):
        return self.base.stats()

class AbstractPositive(AbstractEffect):
    def __init__(self, base):
        self.base = base
    @abstractmethod
    def get_stats(self):
        return self.base.stats()

class Berserk(AbstractPositive):
    def __init__(self, base):
        self.base = base
        self.stats= self.base.stats
        self.stats["HP"] += 7
    def get_stats(self):
        return self.stats

hero = Hero()
brs1 = Berserk(hero)
print('brs1', brs1.get_stats())
brs2 = Berserk(brs1)
print('brs2', brs2.get_stats())
print('brs1', brs1.get_stats())
</code>```

I want to receive

```<code>brs1 {'HP': 135}
brs2 {'HP': 142}
brs1 {'HP': 135}
</code>```

but I get

```<code>brs1 {'HP': 135}
brs2 {'HP': 142}
brs1 {'HP': 142}
</code>```

what's my mistake?

答:
You have been cruelly assaulted by passing by reference.

In your code, you have self.stats = self.base.stats. This does not make a copy. Therefore, self.stats for brs1 and brs2 refer to the same dict. When you instantiate brs2, you change it, and that change is reflected in brs1.

self.stats = self.base.stats.copy() would be a good start, if you don't want this to happen.

That said, I find it rather strange that you want to code status effects in this way...if it were me, I would have each status effect contain only a modifier, and it would be up to the character class to handle resolving those modifiers in turn.

Body:
I want to impose a Berserk effect on the hero.
Abstract classes: AbstractEffect and AbstractPositive (class heir), can accept the base parameter. Next, AbstractNegative will also be created. I am not sure whether the inheritance scheme is correct (Hero ---> AbstractEffect).

from abc import ABC, abstractmethod
class Hero:
    def __init__(self):
        self.stats = {"HP": 128}
    def get_stats(self):
        return self.stats.copy()

class AbstractEffect(ABC):
    def __init__(self, base):
        self.base = base
    @abstractmethod
    def get_stats(self):
        return self.base.stats()

class AbstractPositive(AbstractEffect):
    def __init__(self, base):
        self.base = base
    @abstractmethod
    def get_stats(self):
        return self.base.stats()

class Berserk(AbstractPositive):
    def __init__(self, base):
        self.base = base
        self.stats= self.base.stats
        self.stats["HP"] += 7
    def get_stats(self):
        return self.stats

hero = Hero()
brs1 = Berserk(hero)
print('brs1', brs1.get_stats())
brs2 = Berserk(brs1)
print('brs2', brs2.get_stats())
print('brs1', brs1.get_stats())

I want to receive

brs1 {'HP': 135}
brs2 {'HP': 142}
brs1 {'HP': 135}

but I get

brs1 {'HP': 135}
brs2 {'HP': 142}
brs1 {'HP': 142}

what's my mistake?


问:
grep multiple strings from multiple files and stop processing other files when first match found
I have ca 270 .bz2 log files (25 day logs) and one text file with ca 1500 usernames. What I need to do is find who of theese users are logged in in last 25 days. So I need to grep usernames from list of files and stop grepping when username is found in first file (when first match found).

My code works, but if in first file match found I do not need to process other files, break and search for another username, if it is found i.e. in third file, break and search for another username:

```<code>for i in $(cat /tmp/usernames.txt); do for j in $(ls *.bz2); do
bzgrep -o -m1 $i $j; done; done
</code>```

Here, if in fist file match found it breaks (-m1 flag) and starts searching for the same username in second file, but I do not need that anymore.

Problem: I need to inspect users who are not logged in in last 25 days. So I can reduce their permissions in the application. If user is logged at least once in last 25 days, I do not reduce his permissions.

Question is: I need to find whom of theese usernames exist in my log files. If username is found in one of the files at least one time stop searching for this user and start searching for another user.

Example: if user1 is found in file1, print it and stop searching for this user any more in this or other files. If user2 is found in file8, print it one time and stop searching in file9, file10, file11 ... file250. Hope it makes sense.

答:
You could use a conditional:

```<code>if [ -n "$var" ]; then
     echo "Match!"
     break
fi
</code>```

This structure means that the conditional is True only when $var is not empty. The loop will stop when the condition becomes True.
Good luck!

Body:
I have ca 270 .bz2 log files (25 day logs) and one text file with ca 1500 usernames. What I need to do is find who of theese users are logged in in last 25 days. So I need to grep usernames from list of files and stop grepping when username is found in first file (when first match found).

My code works, but if in first file match found I do not need to process other files, break and search for another username, if it is found i.e. in third file, break and search for another username:

for i in $(cat /tmp/usernames.txt); do for j in $(ls *.bz2); do
bzgrep -o -m1 $i $j; done; done

Here, if in fist file match found it breaks (-m1 flag) and starts searching for the same username in second file, but I do not need that anymore.

Problem: I need to inspect users who are not logged in in last 25 days. So I can reduce their permissions in the application. If user is logged at least once in last 25 days, I do not reduce his permissions.

Question is: I need to find whom of theese usernames exist in my log files. If username is found in one of the files at least one time stop searching for this user and start searching for another user.

Example: if user1 is found in file1, print it and stop searching for this user any more in this or other files. If user2 is found in file8, print it one time and stop searching in file9, file10, file11 ... file250. Hope it makes sense.

Body:
You could use a conditional:

if [ -n "$var" ]; then
     echo "Match!"
     break
fi

This structure means that the conditional is True only when $var is not empty. The loop will stop when the condition becomes True.
Good luck!


问:
Is the 'Click to chat' not working anymore on whatssap?
I cannot create a redirect link in whatssap anymore. It seems to no redirect to chat. In my whatssap, this link does not start a new chat with preflilled text.</p>

```<code>    https://web.whatsapp.com/send?phone=5512 98183-2011&text=oi
</code>```

答: A few days ago WhatsApp had technical issues on chrome & safari (desktop). It last 1 day to fix it. So, I think it's only temporary. I sent them a hint. Maybe you do too.</p>

Body:
I cannot create a redirect link in whatssap anymore. It seems to no redirect to chat. In my whatssap, this link does not start a new chat with preflilled text.

    https://web.whatsapp.com/send?phone=5512 98183-2011&text=oi


问:
Is it good practice to use "using" on a new empty DataTable?
I've been rewriting some old code so that the using statement is used for my DataTables, instead of remembering to Dispose each time:

```<code>using (DataTable dt = BLL.GetDataTable()) {
   foreach(DataRow dr in dt.Rows) {
     // iteration logic
   }
}
</code>```

However in one particular case, the DataTable content differs based on a variable, so I create the initial DataTable and then assign the value afterwards:

```<code>DataTable dt = new DataTable();
switch(foo) {
  case bar:
     dt = BLL.GetDataTable(bar);
     break;
  default:
     dt = BLL.GetDataTable();
     break;
}
// iteration logic here
dt.Dispose();
</code>```

Changing this to use using, I have:

```<code>using (DataTable dt = new DataTable()) {
    switch(foo) {
      case bar:
         dt = BLL.GetDataTable(bar);
         break;
      default:
         dt = BLL.GetDataTable();
         break;
    }
    // iteration logic here
}
</code>```

Is that good practice (i.e. creating the empty DataTable with a using statement)?  I don't know why but it doesn't feel quite right.

答:
As I stated in the comments, your last example won't work. If you want to do something like that, you could move the DataTable generation into a separate function:

```<code>public DataTable GetBLLDataTable()
{
    switch(foo)
    {
        case bar:
            return BLL.GetDataTable(bar);
            break;
        default:
            return BLL.GetDataTable();
            break;
    }
}
</code>```

And then use the DataTable returned by this method in your using statement:

```<code>using (DataTable dt = GetBLLDataTable()) {
    // iteration logic here
}
</code>```

Body:
I've been rewriting some old code so that the using statement is used for my DataTables, instead of remembering to Dispose each time:

using (DataTable dt = BLL.GetDataTable()) {
   foreach(DataRow dr in dt.Rows) {
     // iteration logic
   }
}

However in one particular case, the DataTable content differs based on a variable, so I create the initial DataTable and then assign the value afterwards:

DataTable dt = new DataTable();
switch(foo) {
  case bar:
     dt = BLL.GetDataTable(bar);
     break;
  default:
     dt = BLL.GetDataTable();
     break;
}
// iteration logic here
dt.Dispose();

Changing this to use using, I have:

using (DataTable dt = new DataTable()) {
    switch(foo) {
      case bar:
         dt = BLL.GetDataTable(bar);
         break;
      default:
         dt = BLL.GetDataTable();
         break;
    }
    // iteration logic here
}

Is that good practice (i.e. creating the empty DataTable with a using statement)?  I don't know why but it doesn't feel quite right.

Body:
As I stated in the comments, your last example won't work. If you want to do something like that, you could move the DataTable generation into a separate function:

public DataTable GetBLLDataTable()
{
    switch(foo)
    {
        case bar:
            return BLL.GetDataTable(bar);
            break;
        default:
            return BLL.GetDataTable();
            break;
    }
}

And then use the DataTable returned by this method in your using statement:

using (DataTable dt = GetBLLDataTable()) {
    // iteration logic here
}


问:
Getting OSM tile server to show English labels in openstreetmap
I want to build a small map app, but OSM shows the labels in local languages (Russian, Arabic, etc) .I want all the labels to be in English.
 What is mostly advised is to add the "en tag" but I really cannot find any example of how to do this.

My map object in JS is:

```<code>var map = L.map('map', {
  center: [mapCenterLat, mapCenterLon],
  zoom: 3,
  minZoom: 2
  });
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
</code>```

How should the tag get inserted in the osm url in order to show english labels only?

答:
See Map internationalization in the OSM wiki for a list of raster and vector tile servers that contain multilingual names.

Also take a look at Tiles in the OSM wiki, mapstyle.petschge.de, Leaflet Provider Demo and Map Compare for various OSM-based maps. Some of them have all-English place names.

Body:
I want to build a small map app, but OSM shows the labels in local languages (Russian, Arabic, etc) .I want all the labels to be in English.
 What is mostly advised is to add the "en tag" but I really cannot find any example of how to do this.

My map object in JS is:

var map = L.map('map', {
  center: [mapCenterLat, mapCenterLon],
  zoom: 3,
  minZoom: 2
  });
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);

How should the tag get inserted in the osm url in order to show english labels only?


问:
Failed to connect to XX.XX.XXX.XX port 9200: Connection refused on EC2
I've installed Elasticsearch on an EC2 Ubuntu 14 server.

I can see it's running:

```<code>elastic@ip-xxx-xx-xx-xxx:~$ curl -get localhost:9200
{
  "name" : "ip-xxx-xx-xx-xxx",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "V6axWUV9SoqABC8sX62XMQ",
  "version" : {
    "number" : "7.0.1",
    "build_flavor" : "default",
    "build_type" : "deb",
    "build_hash" : "e4efcb5",
    "build_date" : "2019-04-29T12:57:03.145736Z",
    "build_snapshot" : false,
    "lucene_version" : "8.0.0",
    "minimum_wire_compatibility_version" : "6.7.0",
    "minimum_index_compatibility_version" : "6.0.0-beta1"
  },
  "tagline" : "You Know, for Search"
}
</code>```

I've added it to the security group:

But I can't connect from remote:

```<code>C:\>curl -get http://XX.XX.XXX.XX:9200/
curl: (7) Failed to connect to XX.XX.XXX.XX port 9200: Connection refused
</code>```

netstat -nlp |grep 9200:

```<code>tcp6       0      0 127.0.0.1:9200          :::*                    LISTEN      29467/java
tcp6       0      0 ::1:9200                :::*                    LISTEN      29467/java
</code>```

This is the content of elasticsearch.yml after removing all comments:

```<code>path.data: /var/lib/elasticsearch
path.logs: /var/log/elasticsearch
</code>```

答:
I have solved the problem.

First thing I had to configure was network.host, but very important to notice that it didn't work with the IP I was trying to connect to from the client, because this is the EC2 public IP. I had to use the EC2 private IP.

But then I kept getting the same error, and I've found out that the cluster coordination algorithm has changed in Elasticsearch 7.0 and in order to be safe it requires some specific configuration. Elastic relax that requirement (that is, they run in a less-safe mode) when one binds to localhost only, but if/when one changes network.host they enforce that he configures the cluster safely.

So, since I use a single node cluster, I had to add the following setting to the Discovery section in elasticsearch.yml:

```<code>discovery.type: single-node
</code>```

Body:
I've installed Elasticsearch on an EC2 Ubuntu 14 server.

I can see it's running:

elastic@ip-xxx-xx-xx-xxx:~$ curl -get localhost:9200
{
  "name" : "ip-xxx-xx-xx-xxx",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "V6axWUV9SoqABC8sX62XMQ",
  "version" : {
    "number" : "7.0.1",
    "build_flavor" : "default",
    "build_type" : "deb",
    "build_hash" : "e4efcb5",
    "build_date" : "2019-04-29T12:57:03.145736Z",
    "build_snapshot" : false,
    "lucene_version" : "8.0.0",
    "minimum_wire_compatibility_version" : "6.7.0",
    "minimum_index_compatibility_version" : "6.0.0-beta1"
  },
  "tagline" : "You Know, for Search"
}

I've added it to the security group:

But I can't connect from remote:

C:\>curl -get http://XX.XX.XXX.XX:9200/
curl: (7) Failed to connect to XX.XX.XXX.XX port 9200: Connection refused

netstat -nlp |grep 9200:

tcp6       0      0 127.0.0.1:9200          :::*                    LISTEN      29467/java
tcp6       0      0 ::1:9200                :::*                    LISTEN      29467/java

This is the content of elasticsearch.yml after removing all comments:

path.data: /var/lib/elasticsearch
path.logs: /var/log/elasticsearch

Body:
I have solved the problem.

First thing I had to configure was network.host, but very important to notice that it didn't work with the IP I was trying to connect to from the client, because this is the EC2 public IP. I had to use the EC2 private IP.

But then I kept getting the same error, and I've found out that the cluster coordination algorithm has changed in Elasticsearch 7.0 and in order to be safe it requires some specific configuration. Elastic relax that requirement (that is, they run in a less-safe mode) when one binds to localhost only, but if/when one changes network.host they enforce that he configures the cluster safely.

So, since I use a single node cluster, I had to add the following setting to the Discovery section in elasticsearch.yml:

discovery.type: single-node


问:
When importing tensorflow, I get the following error: No module named 'numpy.core._multiarray_umath'
I have installed Ancaconda3 and Tensorflow. When I try to import Tensorflow in python shell I receive the following error:

ModuleNotFoundError: No module named 'numpy.core._multiarray_umath'
ImportError: numpy.core.multiarray failed to import

The above exception was the direct cause of the following exception:

Traceback (most recent call last):   File "", line 980, in _find_and_load SystemError:
<class '_frozen_importlib._ModuleLockManager'> returned a result with
an error set ImportError: numpy.core._multiarray_umath failed to
import ImportError: numpy.core.umath failed to import

I am not sure what the problem is as numpy is installed on my system and can be successfully imported in python.
I am using Windows10.

答:
Kindly check whether you have installed the numpy package from pip. Because if you are running on conda evironment, then all packages need to be downloaded from there.
Please use the below mentioned statement for this purpose

conda install -c anaconda numpy

Also make sure that the numpy version supports the Python version you are using.


问:
Compare CSV File Records with Python Scrapy Output Data
I'm new to Python and web scraping. Pls excuse me for my ignorance. In this program, I have crawled some urls and saved product name and price to csv file. When I run the script again, I want to read the existing csv records(product name and price) and  if there's a change of the price for any product/s, I want to print a message. I'm struggling with implementing 2nd part of the program, Which is compare values against saved csv records. Please help. Any help would be highly appreciated.

```<code>import scrapy
from time import sleep
import csv, os, json
import random
import os

class spider1(scrapy.Spider):
    name = "spider1"

    with open("data.csv", "a") as filee:

        if os.stat("data.csv").st_size != 0:
            filee.truncate(0)
        filee.close()

    def start_requests(self):
        list = ["https://www.example.com/item1",
                "https://www.example.com/item2",
                "https://www.example.com/item3",
                "https://www.example.com/item4",
                "https://www.example.com/item5"
                ]

        for i in list:
            yield scrapy.Request(i, callback=self.parse)
            sleep(random.randint(0, 5))

    def parse(self, response):

        product_name = response.css('#pd-h1-cartridge::text')[0].extract()
        product_price = response.css(
            '.product-price .is-current, .product-price_total .is-current, .product-price_total ins, .product-price ins').css(
            '::text')[3].extract()

        with open('data.csv', 'a+') as file:

            itemwriter = csv.writer(file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

            itemwriter.writerow([str(product_name).strip(), str(product_price).strip()])

            file.close()
</code>```

CSV Output

```<code>Purple Wine Glass Cooler,1.47
Color Your Own VBS Island Wind Chimes,6.47
Color Your Own Fuzzy Patriotic Wreaths,7.79
Color Your Own Patriotic Keychains,6.19
Patriotic Cool Treats Craft Stick Magnet Craft Kit,6.19
</code>```

答:
Use Scrapy to generate CSV files only.

Write a separate script to compare CSV files.

Body:
I'm new to Python and web scraping. Pls excuse me for my ignorance. In this program, I have crawled some urls and saved product name and price to csv file. When I run the script again, I want to read the existing csv records(product name and price) and  if there's a change of the price for any product/s, I want to print a message. I'm struggling with implementing 2nd part of the program, Which is compare values against saved csv records. Please help. Any help would be highly appreciated.

import scrapy
from time import sleep
import csv, os, json
import random
import os

class spider1(scrapy.Spider):
    name = "spider1"

    with open("data.csv", "a") as filee:

        if os.stat("data.csv").st_size != 0:
            filee.truncate(0)
        filee.close()

    def start_requests(self):
        list = ["https://www.example.com/item1",
                "https://www.example.com/item2",
                "https://www.example.com/item3",
                "https://www.example.com/item4",
                "https://www.example.com/item5"
                ]

        for i in list:
            yield scrapy.Request(i, callback=self.parse)
            sleep(random.randint(0, 5))

    def parse(self, response):

        product_name = response.css('#pd-h1-cartridge::text')[0].extract()
        product_price = response.css(
            '.product-price .is-current, .product-price_total .is-current, .product-price_total ins, .product-price ins').css(
            '::text')[3].extract()

        with open('data.csv', 'a+') as file:

            itemwriter = csv.writer(file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

            itemwriter.writerow([str(product_name).strip(), str(product_price).strip()])

            file.close()

CSV Output

Purple Wine Glass Cooler,1.47
Color Your Own VBS Island Wind Chimes,6.47
Color Your Own Fuzzy Patriotic Wreaths,7.79
Color Your Own Patriotic Keychains,6.19
Patriotic Cool Treats Craft Stick Magnet Craft Kit,6.19


问:
Why is 3 >> 32 equal to 3?

why 3 right shift 32 is equal to 3 and not 0.

I got these results in nodeJs and Java

3 >> 31 = 0

3 >> 32 = 3

3 >> 33 = 1

3 >> 34 = 0

3 >> 35 = 0

答:
This is part of the Java language specification. The right hand operand is wrapped so that it is always in the range 0 - bits, where bits is the number of bits of the left hand operand. Since you are shifting a 32 bit integer, the right hand operand is wrapped within 0 to 31. 32 becomes 0, 33 becomes 1 etc.

See the Java language specification for shift operators:

If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x1f (0b11111). The shift distance actually used is therefore always in the range 0 to 31, inclusive.

Title: Why is 3 >> 32 equal to 3?


问:
Custom File Format to partition data while writing
Hi I want to save my spark dataframe to a file with custom file format,
such that it partitions data to different files while writing to the file.
Also I need single part file for each partition key.

I have tried extending TextBasedFileFormat and change writer to suit my needs.
The data is getting partitioned while writing to file without shuffle.
But I feel each rdd partition will write data to different part file

答:
When you write the dataframe, each partition of underlying RDD will be written by separate tasks. Now each of these RDD partitions might correspond to data which belongs to different partition key. So each task will end up creating multiple part files.

To solve this, you have to repartition your dataframe by the partitionKey. This will involve a shuffle and all the data corresponding to same partitionKey will come into same RDD partition. This can be done by -

```<code>val newDf = df.repartition("partitionKey")
</code>```

Now this RDD can be written to any file format (say parquet, csv etc) and their should be 1 file per partition. If the file size is going big, it might create multiple files. This can be controlled by config "spark.sql.files.maxRecordsPerFile".

```<code>val newDf = df.repartition("partitionKey")
newDf.write.partitionBy("partitionKey").parquet("<directory_path>")
</code>```

Body:
When you write the dataframe, each partition of underlying RDD will be written by separate tasks. Now each of these RDD partitions might correspond to data which belongs to different partition key. So each task will end up creating multiple part files.

To solve this, you have to repartition your dataframe by the partitionKey. This will involve a shuffle and all the data corresponding to same partitionKey will come into same RDD partition. This can be done by -

val newDf = df.repartition("partitionKey")

Now this RDD can be written to any file format (say parquet, csv etc) and their should be 1 file per partition. If the file size is going big, it might create multiple files. This can be controlled by config "spark.sql.files.maxRecordsPerFile".

val newDf = df.repartition("partitionKey")
newDf.write.partitionBy("partitionKey").parquet("<directory_path>")


问:
Bootstrap panel-footer with button pull-right
I have the following HTML element with bootstrap:

```<code> <div class="panel-footer">
                            <button type="button" id="btnSave" class="btn btn-default pull-right">Save</button>
                        </div>
</code>```

If you see there is a gray area (panel-footer):

The button uses pull-right class also that is float:right, but I would like the gray area that is actually the panel-footer div to fit within the button height.

This is the styles for panel-footer:

And this for the pull-right:

Any clue?

UPDATE:

I added after the button:

```<code><div class="clearfix"></div>
</code>```

And seems that fixed the problem. Is that ok?

答:
```<code><div class="panel-footer">
     <div class="form-group text-right">
         <button type="submit" class="btn btn-primary">Submit</button>
     </div>
 </div>
</code>```

This will work properly.

Body:
I have the following HTML element with bootstrap:

                            <button type="button" id="btnSave" class="btn btn-default pull-right">Save</button>

If you see there is a gray area (panel-footer):

The button uses pull-right class also that is float:right, but I would like the gray area that is actually the panel-footer div to fit within the button height.

This is the styles for panel-footer:

And this for the pull-right:

Any clue?

UPDATE:

I added after the button:

And seems that fixed the problem. Is that ok?

Body:
<div class="panel-footer">
     <div class="form-group text-right">
         <button type="submit" class="btn btn-primary">Submit</button>
     </div>
 </div>

This will work properly.


问:
How do i create a drop down list in a vertical navbar
I am trying to make a dropdown list in my vertical navbar. I would really appreciate it if you can help me come up with an idea of how to create a drop-down list.

I tried researching and looking for different codes for my project. Here are some things I tried in my code.

My HTML Code:

```<code>            <div class="menu-overlay"></div>
                <div class="side-menu-wrapper">
                   <a href="#" class="menu-close">×</a>
                   <ul>
                      <li>
                          <form class="example"action="action_page.php">
                              <input type="text" placeholder="Search.."
                              name="search">
                             <button type="submit">
                                   <i class="fa fa-search"></i>
                             </button>
                           </form>
                       </li>
                       <li>
                          <a href="Index.html" target="_blank"
                           rel="nofollow">
                                Home
                           </a>
                       </li>
                       <li >
                          <a href="#" target="_blank" rel="nofollow">
                               About
                          </a>
                         <ul>
                            <li href="#" target="_blank" rel="nofollow">
                                <a >Introduction</a>
                            </li>
                            <li href="#" target="_blank" rel="nofollow">
                                <a >Mission</a>
                            </li>
                            <li href="#" target="_blank" rel="nofollow">
                                 <a >Vision</a>
                            </li>
                         </ul>
                     </li>
                     <li>
                        <a href="#" target="_blank" rel="nofollow">
                            Facebook
                        </a>
                     </li>
                     <li>
                       <a href="#" target="_blank"
                       rel="nofollow">
                            Flickr
                        </a>
                   </li>
                </ul>
           </div>
</code>```

My CSS Code:

```<code>.side-menu-wrapper {
   background: rgba(0,114,187,0.7);
   padding: 40px 0 0 40px;
   position: fixed;
   top: 0;
   right: 0;
   height: 100%;
   z-index: 2;
   transition: 0.5s;
   width: 250px;
   font: 20px "Courier New", Courier, monospace;
   box-sizing: border-box;
 }

.side-menu-wrapper > ul{
   list-style:none;
   padding:0;
   margin:0;
   overflow-y: auto;
   height:95%;
}

.side-menu-wrapper > ul > li > a {
    display: block;
    border-bottom: 1px solid black;
    padding: 6px 4px 6px 4px;
    color: white;
    transition: 0.3s;
    text-decoration: none;
  }

.side-menu-wrapper > a.menu-close {
   padding: 8px 0 4px 23px;
   color: white;
   display: block;
   margin: -30px 0 -10px -20px;
   font-size: 35px;
   text-decoration: none;
 }

.menu-overlay {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: rgba(0,0,0,.7);
  overflow-y: auto;
  overflow-x: hidden;
  text-align: center;
  opacity: 0;
  transition: opacity 1s;
}
</code>```

Result:

Thx Btw

答:
By wrapping your About sub-menu using bootstrap's collapse class (more infos here), this should work :

```<code><a href="#" class="active" data-toggle="collapse" data-target="#sub-menu" target="_blank" rel="nofollow">About<span class="ml-2" style="font-size: 12px;">▼</span></a>
<div class="collapse" id="sub-menu">
    <ul>
        <li href="#" target="_blank" rel="nofollow">
            <a >Introduction</a>
        </li>
        <li href="#" target="_blank" rel="nofollow">
            <a >Mission</a>
        </li>
        <li href="#" target="_blank" rel="nofollow">
            <a >Vision</a>
        </li>
     </ul>
</div>
</code>```

Example below :

.side-menu-wrapper {
   background: rgba(0,114,187,0.7);
   padding: 40px 0 0 40px;
   position: fixed;
   top: 0;
   right: 0;
   height: 100%;
   z-index: 2;
   transition: 0.5s;
   width: 250px;
   font: 20px "Courier New", Courier, monospace;
   box-sizing: border-box;
 }

.side-menu-wrapper > ul{
   list-style:none;
   padding:0;
   margin:0;
   overflow-y: auto;
   height:95%;
}

.side-menu-wrapper > ul > li > a {
    display: block;
    border-bottom: 1px solid black;
    padding: 6px 4px 6px 4px;
    color: white;
    transition: 0.3s;
    text-decoration: none;
  }

.side-menu-wrapper > a.menu-close {
   padding: 8px 0 4px 23px;
   color: white;
   display: block;
   margin: -30px 0 -10px -20px;
   font-size: 35px;
   text-decoration: none;
 }

.menu-overlay {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: rgba(0,0,0,.7);
  overflow-y: auto;
  overflow-x: hidden;
  text-align: center;
  opacity: 0;
  transition: opacity 1s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

 <div class="menu-overlay "></div>
  <div class="side-menu-wrapper">
  ×
    <ul>
    <li>
      <form class="example" action="action_page.php">
        <input type="text" placeholder="Search.."
               name="search">
        <button type="submit">
          <i class="fa fa-search"></i>
        </button>
      </form>
      </li>
      <li>
        Home
      </li>
      <li>
        About<span class="ml-2" style="font-size: 12px;">▼</span>
        <div class="collapse" id="sub-menu">
          <ul>
            <li href="#" target="_blank" rel="nofollow">
              Introduction
            </li>
            <li href="#" target="_blank" rel="nofollow">
              Mission
            </li>
            <li href="#" target="_blank" rel="nofollow">
              Vision
            </li>
          </ul>
        </div>
      </li>
      <li>
        Facebook
      </li>
      <li>
        Flickr
      </li>
    </ul>
  </div></code>```

Body:
I am trying to make a dropdown list in my vertical navbar. I would really appreciate it if you can help me come up with an idea of how to create a drop-down list.

I tried researching and looking for different codes for my project. Here are some things I tried in my code.

My HTML Code:

                   ×

                          <form class="example"action="action_page.php">
                              <input type="text" placeholder="Search.."
                              name="search">
                             <button type="submit">

                             </button>
                           </form>

                                Home

                               About

                                Introduction

                                Mission

                                 Vision

                            Facebook

                            Flickr

My CSS Code:

.side-menu-wrapper {
   background: rgba(0,114,187,0.7);
   padding: 40px 0 0 40px;
   position: fixed;
   top: 0;
   right: 0;
   height: 100%;
   z-index: 2;
   transition: 0.5s;
   width: 250px;
   font: 20px "Courier New", Courier, monospace;
   box-sizing: border-box;
 }

.side-menu-wrapper > ul{
   list-style:none;
   padding:0;
   margin:0;
   overflow-y: auto;
   height:95%;
}

.side-menu-wrapper > ul > li > a {
    display: block;
    border-bottom: 1px solid black;
    padding: 6px 4px 6px 4px;
    color: white;
    transition: 0.3s;
    text-decoration: none;
  }

.side-menu-wrapper > a.menu-close {
   padding: 8px 0 4px 23px;
   color: white;
   display: block;
   margin: -30px 0 -10px -20px;
   font-size: 35px;
   text-decoration: none;
 }

.menu-overlay {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: rgba(0,0,0,.7);
  overflow-y: auto;
  overflow-x: hidden;
  text-align: center;
  opacity: 0;
  transition: opacity 1s;
}

Result:

Thx Btw

Body:
By wrapping your About sub-menu using bootstrap's collapse class (more infos here), this should work :

<a href="#" class="active" data-toggle="collapse" data-target="#sub-menu" target="_blank" rel="nofollow">About<span class="ml-2" style="font-size: 12px;">&#x25BC;</span></a>
<div class="collapse" id="sub-menu">
    <ul>
        <li href="#" target="_blank" rel="nofollow">
            <a >Introduction</a>
        </li>
        <li href="#" target="_blank" rel="nofollow">
            <a >Mission</a>
        </li>
        <li href="#" target="_blank" rel="nofollow">
            <a >Vision</a>
        </li>
     </ul>
</div>

Example below :

.side-menu-wrapper {
   background: rgba(0,114,187,0.7);
   padding: 40px 0 0 40px;
   position: fixed;
   top: 0;
   right: 0;
   height: 100%;
   z-index: 2;
   transition: 0.5s;
   width: 250px;
   font: 20px "Courier New", Courier, monospace;
   box-sizing: border-box;
 }

.side-menu-wrapper > ul{
   list-style:none;
   padding:0;
   margin:0;
   overflow-y: auto;
   height:95%;
}

.side-menu-wrapper > ul > li > a {
    display: block;
    border-bottom: 1px solid black;
    padding: 6px 4px 6px 4px;
    color: white;
    transition: 0.3s;
    text-decoration: none;
  }

.side-menu-wrapper > a.menu-close {
   padding: 8px 0 4px 23px;
   color: white;
   display: block;
   margin: -30px 0 -10px -20px;
   font-size: 35px;
   text-decoration: none;
 }

.menu-overlay {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: rgba(0,0,0,.7);
  overflow-y: auto;
  overflow-x: hidden;
  text-align: center;
  opacity: 0;
  transition: opacity 1s;
}

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

 <div class="menu-overlay "></div>
  <div class="side-menu-wrapper">
  <a href="#" class="menu-close">×</a>
    <ul>
    <li>
      <form class="example" action="action_page.php">
        <input type="text" placeholder="Search.."
               name="search">
        <button type="submit">
          <i class="fa fa-search"></i>
        </button>
      </form>
      </li>
      <li>
        <a href="#" target="_blank" rel="nofollow">Home</a>
      </li>
      <li>
        <a href="#sub-menu" class="active" data-toggle="collapse" data-target="#sub-menu">About<span class="ml-2" style="font-size: 12px;">&#x25BC;</span></a>
        <div class="collapse" id="sub-menu">
          <ul>
            <li href="#" target="_blank" rel="nofollow">
              <a >Introduction</a>
            </li>
            <li href="#" target="_blank" rel="nofollow">
              <a >Mission</a>
            </li>
            <li href="#" target="_blank" rel="nofollow">
              <a >Vision</a>
            </li>
          </ul>
        </div>
      </li>
      <li>
        <a href="#" target="_blank" rel="nofollow">Facebook</a>
      </li>
      <li>
        <a href="#" target="_blank" rel="nofollow">Flickr</a>
      </li>
    </ul>
  </div>


问:
xamarin ios polyline Map.AddOverlay not works
im trying to draw a path on map which user walked. It works fine on android but ios, just draw at start little line. After "OnElementPropertyChanged" triggered not draw anything.

RouteCoordinates are created on CustomMap based Map class as BindableProperties. I think my property changed method can not reach right display layer or thread.

My custom renderer for IOS:

```<code>[assembly: ExportRenderer(typeof(CustomMap), typeof(CustomMapRenderer))]
namespace PawsApp.iOS.Renderers
{
    public class CustomMapRenderer : MapRenderer
    {
        MKPolylineRenderer polylineRenderer;
        CustomMap formsMap;
        MKMapView nativeMap;

    protected override void OnElementChanged(ElementChangedEventArgs<View> e)
    {
        base.OnElementChanged(e);

        if (e.OldElement != null)
        {
            if (nativeMap != null)
            {
                nativeMap.RemoveOverlays(nativeMap.Overlays);
                nativeMap.OverlayRenderer = null;
                polylineRenderer = null;
            }
        }

        if (e.NewElement != null)
        {
            formsMap = (CustomMap)e.NewElement;
            nativeMap = Control as MKMapView;
            UpdatePolyLine();
        }
    }

    protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender, e);
        if (this.Element == null || this.Control == null)
            return;

        //if (e.PropertyName == CustomMap.RouteCoordinatesProperty.PropertyName)
        if ((e.PropertyName == "RouteCoordinates" || e.PropertyName == "VisibleRegion"))
        {
            formsMap = (CustomMap)sender;
            nativeMap = Control as MKMapView;
            UpdatePolyLine();
        }
    }

    private void UpdatePolyLine()
    {

        //var nativeMap = Control as MKMapView;

        nativeMap.OverlayRenderer = GetOverlayRenderer;

        CLLocationCoordinate2D[] coords = new CLLocationCoordinate2D[formsMap.RouteCoordinates.Count];

        int index = 0;
        foreach (var position in formsMap.RouteCoordinates)
        {
            coords[index] = new CLLocationCoordinate2D(position.Latitude, position.Longitude);
            index++;
        }

        var routeOverlay = MKPolyline.FromCoordinates(coords);
        nativeMap.AddOverlay(routeOverlay);
    }

    //[Foundation.Export("mapView:rendererForOverlay:")]
    MKOverlayRenderer GetOverlayRenderer(MKMapView mapView, IMKOverlay overlayWrapper)
    {
        if (polylineRenderer == null)
        {
            var overlay = Runtime.GetNSObject(overlayWrapper.Handle) as IMKOverlay;
            //var overlay = Runtime.GetNSObject(overlayWrapper.Handle) as MKPolyline;
            polylineRenderer = new MKPolylineRenderer(overlay as MKPolyline)
            {
                FillColor = UIColor.Yellow,
                StrokeColor = UIColor.Red,
                LineWidth = 3,
                Alpha = 0.4f
            };
        }
        return polylineRenderer;
    }
}
}
</code>```

答:
After trying it on my side, I find if you want to refresh the polyLine in the Map in iOS, you have to:

remove the old polyline;

use a new nativeMap.OverlayRenderer everytime.

I changed the customer renderer code like this:

```<code>public class CustomMapRenderer : MapRenderer
{
    MKPolylineRenderer polylineRenderer;
    CustomMap formsMap;
    MKMapView nativeMap;

    MKPolyline polyline;

    protected override void OnElementChanged(ElementChangedEventArgs<View> e)
    {
        base.OnElementChanged(e);

        if (e.OldElement != null)
        {
            if (nativeMap != null)
            {
                nativeMap.RemoveOverlays(nativeMap.Overlays);
                nativeMap.OverlayRenderer = null;
                polylineRenderer = null;
            }
        }

        if (e.NewElement != null)
        {
            formsMap = (CustomMap)e.NewElement;
            nativeMap = Control as MKMapView;
            UpdatePolyLine();
        }
    }

    protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender, e);
        if (this.Element == null || this.Control == null)
            return;

        //if (e.PropertyName == CustomMap.RouteCoordinatesProperty.PropertyName)
        if ((e.PropertyName == "RouteCoordinates" || e.PropertyName == "VisibleRegion"))
        {
            formsMap = (CustomMap)sender;
            nativeMap = Control as MKMapView;
            UpdatePolyLine();
        }

    }

    private void UpdatePolyLine()
    {

        //var nativeMap = Control as MKMapView;

        if (polyline != null)
        {
            nativeMap.RemoveOverlay(polyline);
            polyline.Dispose();
        }

        nativeMap.OverlayRenderer = GetOverlayRenderer;

        CLLocationCoordinate2D[] coords = new CLLocationCoordinate2D[formsMap.RouteCoordinates.Count];

        int index = 0;
        foreach (var position in formsMap.RouteCoordinates)
        {
            coords[index] = new CLLocationCoordinate2D(position.Latitude, position.Longitude);
            index++;
        }

        var routeOverlay = MKPolyline.FromCoordinates(coords);
        nativeMap.AddOverlay(routeOverlay);

        polyline = routeOverlay;
    }

    //[Foundation.Export("mapView:rendererForOverlay:")]
    MKOverlayRenderer GetOverlayRenderer(MKMapView mapView, IMKOverlay overlayWrapper)
    {
        if (polylineRenderer != null)
        {
            polylineRenderer = null;
        }

        var overlay = Runtime.GetNSObject(overlayWrapper.Handle) as IMKOverlay;
        //var overlay = Runtime.GetNSObject(overlayWrapper.Handle) as MKPolyline;

        polylineRenderer = new MKPolylineRenderer(overlay as MKPolyline)
        {
            FillColor = UIColor.Yellow,
            StrokeColor = UIColor.Red,
            LineWidth = 3,
            Alpha = 0.4f
        };

        return polylineRenderer;
    }
}
</code>```

And in the xamarin.forms porject, reset the customMap.RouteCoordinates every time:

```<code>  Device.StartTimer(TimeSpan.FromSeconds(3), () =>
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                          a -= 0.000321;
                          b += 0.000222;
                          customMap.RouteCoordinates = new List<Position>
                          {
                              new Position (37.797534, -122.401827),
                              new Position(37.797510, -122.402060),
                              new Position(37.790269, -122.400589),
                              new Position(37.790265, -122.400474),
                              new Position(37.790228, -122.400391),
                              new Position(37.790126, -122.400360),
                              new Position(37.789250, -122.401451),
                              new Position(a, b)
                          };
                });

            return true;
            });
</code>```

I also upload my demo here and you can check it. Let me know if it works.

Body:
im trying to draw a path on map which user walked. It works fine on android but ios, just draw at start little line. After "OnElementPropertyChanged" triggered not draw anything.

RouteCoordinates are created on CustomMap based Map class as BindableProperties. I think my property changed method can not reach right display layer or thread.

My custom renderer for IOS:

[assembly: ExportRenderer(typeof(CustomMap), typeof(CustomMapRenderer))]
namespace PawsApp.iOS.Renderers
{
    public class CustomMapRenderer : MapRenderer
    {
        MKPolylineRenderer polylineRenderer;
        CustomMap formsMap;
        MKMapView nativeMap;

    protected override void OnElementChanged(ElementChangedEventArgs<View> e)
    {
        base.OnElementChanged(e);

        if (e.OldElement != null)
        {
            if (nativeMap != null)
            {
                nativeMap.RemoveOverlays(nativeMap.Overlays);
                nativeMap.OverlayRenderer = null;
                polylineRenderer = null;
            }
        }

        if (e.NewElement != null)
        {
            formsMap = (CustomMap)e.NewElement;
            nativeMap = Control as MKMapView;
            UpdatePolyLine();
        }
    }

    protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender, e);
        if (this.Element == null || this.Control == null)
            return;

        //if (e.PropertyName == CustomMap.RouteCoordinatesProperty.PropertyName)
        if ((e.PropertyName == "RouteCoordinates" || e.PropertyName == "VisibleRegion"))
        {
            formsMap = (CustomMap)sender;
            nativeMap = Control as MKMapView;
            UpdatePolyLine();
        }
    }

    private void UpdatePolyLine()
    {

        //var nativeMap = Control as MKMapView;

        nativeMap.OverlayRenderer = GetOverlayRenderer;

        CLLocationCoordinate2D[] coords = new CLLocationCoordinate2D[formsMap.RouteCoordinates.Count];

        int index = 0;
        foreach (var position in formsMap.RouteCoordinates)
        {
            coords[index] = new CLLocationCoordinate2D(position.Latitude, position.Longitude);
            index++;
        }

        var routeOverlay = MKPolyline.FromCoordinates(coords);
        nativeMap.AddOverlay(routeOverlay);
    }

    //[Foundation.Export("mapView:rendererForOverlay:")]
    MKOverlayRenderer GetOverlayRenderer(MKMapView mapView, IMKOverlay overlayWrapper)
    {
        if (polylineRenderer == null)
        {
            var overlay = Runtime.GetNSObject(overlayWrapper.Handle) as IMKOverlay;
            //var overlay = Runtime.GetNSObject(overlayWrapper.Handle) as MKPolyline;
            polylineRenderer = new MKPolylineRenderer(overlay as MKPolyline)
            {
                FillColor = UIColor.Yellow,
                StrokeColor = UIColor.Red,
                LineWidth = 3,
                Alpha = 0.4f
            };
        }
        return polylineRenderer;
    }
}
}

Body:
After trying it on my side, I find if you want to refresh the polyLine in the Map in iOS, you have to:

remove the old polyline;

use a new nativeMap.OverlayRenderer everytime.

I changed the customer renderer code like this:

public class CustomMapRenderer : MapRenderer
{
    MKPolylineRenderer polylineRenderer;
    CustomMap formsMap;
    MKMapView nativeMap;

    MKPolyline polyline;

    protected override void OnElementChanged(ElementChangedEventArgs<View> e)
    {
        base.OnElementChanged(e);

        if (e.OldElement != null)
        {
            if (nativeMap != null)
            {
                nativeMap.RemoveOverlays(nativeMap.Overlays);
                nativeMap.OverlayRenderer = null;
                polylineRenderer = null;
            }
        }

        if (e.NewElement != null)
        {
            formsMap = (CustomMap)e.NewElement;
            nativeMap = Control as MKMapView;
            UpdatePolyLine();
        }
    }

    protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender, e);
        if (this.Element == null || this.Control == null)
            return;

        //if (e.PropertyName == CustomMap.RouteCoordinatesProperty.PropertyName)
        if ((e.PropertyName == "RouteCoordinates" || e.PropertyName == "VisibleRegion"))
        {
            formsMap = (CustomMap)sender;
            nativeMap = Control as MKMapView;
            UpdatePolyLine();
        }

    }

    private void UpdatePolyLine()
    {

        //var nativeMap = Control as MKMapView;

        if (polyline != null)
        {
            nativeMap.RemoveOverlay(polyline);
            polyline.Dispose();
        }

        nativeMap.OverlayRenderer = GetOverlayRenderer;

        CLLocationCoordinate2D[] coords = new CLLocationCoordinate2D[formsMap.RouteCoordinates.Count];

        int index = 0;
        foreach (var position in formsMap.RouteCoordinates)
        {
            coords[index] = new CLLocationCoordinate2D(position.Latitude, position.Longitude);
            index++;
        }

        var routeOverlay = MKPolyline.FromCoordinates(coords);
        nativeMap.AddOverlay(routeOverlay);

        polyline = routeOverlay;
    }

    //[Foundation.Export("mapView:rendererForOverlay:")]
    MKOverlayRenderer GetOverlayRenderer(MKMapView mapView, IMKOverlay overlayWrapper)
    {
        if (polylineRenderer != null)
        {
            polylineRenderer = null;
        }

        var overlay = Runtime.GetNSObject(overlayWrapper.Handle) as IMKOverlay;
        //var overlay = Runtime.GetNSObject(overlayWrapper.Handle) as MKPolyline;

        polylineRenderer = new MKPolylineRenderer(overlay as MKPolyline)
        {
            FillColor = UIColor.Yellow,
            StrokeColor = UIColor.Red,
            LineWidth = 3,
            Alpha = 0.4f
        };

        return polylineRenderer;
    }
}

And in the xamarin.forms porject, reset the customMap.RouteCoordinates every time:

  Device.StartTimer(TimeSpan.FromSeconds(3), () =>
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                          a -= 0.000321;
                          b += 0.000222;
                          customMap.RouteCoordinates = new List<Position>
                          {
                              new Position (37.797534, -122.401827),
                              new Position(37.797510, -122.402060),
                              new Position(37.790269, -122.400589),
                              new Position(37.790265, -122.400474),
                              new Position(37.790228, -122.400391),
                              new Position(37.790126, -122.400360),
                              new Position(37.789250, -122.401451),
                              new Position(a, b)
                          };
                });

            return true;
            });

I also upload my demo here and you can check it. Let me know if it works.