问:
Get inner JSON content as string without deserializing
I've got a file with JSON content like this:

```<code>{
  "Data": {
    "A": {
      "A1": "S",
      "A2": 0.0
    }
  },
  "NoData": "text"
}
</code>```

What I want to achieve is to get the inner json of "Data" as a string. I do not want it to be deserialized as an object. I already tried to deserialize it with Json.NET JsonConvert.DeserializeObject<TestClass> where Test class is defined as

```<code>class Testclass
{
  public string Data {get; set;}
  public string NoData {get; set;}
}
</code>```

But this results in Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: {. Path 'Data', line 2, position 11.

The data in "Data" is cryptographically signed by a remote server and the signature needs to be checked. But I do not necessarily have the same classes the data was serialized with at the clients side. That's why I want to do as few conversions as possible. So deserializing and serializing again may change the original string in "data". All spaces and linebreaks have to stay intact.

答:
I had implemented a naive JSON parser just for solving this specific problem, here's the code:

Method:

```<code>static string ExtractInnerJsonObject(ReadOnlySpan<byte> jsonPayload, ReadOnlySpan<char> targetField, bool preserveWhiteSpaces = false)
{
    const int TYPE_OTHER = 0;
    const int TYPE_OBJECT = 1;
    const int TYPE_STRING = 2;
    const int TYPE_ARRAY = 3;

    ReadOnlySpan<char> jsonPayloadString = Encoding.UTF8.GetString(jsonPayload).AsSpan();

    int objectDepth = 0;
    int lastWhiteSpacePosition = 0;
    int fieldNameStartPosition = 0;
    int fieldNameEndPosition = 0;
    int valueStartPosition = 0;
    int valueEndPosition = 0;
    int detectedValueType = TYPE_OTHER;

    bool isValueTypeDetected = false;

    bool isValueScanStarted = false;
    bool isValueScanCompleted = false;

    bool isTargetField = false;
    bool isFieldNameScanStarted = false;
    bool isFieldNameScanCompleted = false;

    for (int i = 0; i < jsonPayloadString.Length; i++)
    {
        char c = jsonPayloadString[i];

        if (c == '{')
        {
            objectDepth++;

            if (isValueScanStarted && !isValueScanCompleted && !isValueTypeDetected)
            {
                detectedValueType = TYPE_OBJECT;
                isValueTypeDetected = true;
            }
        }
        else if (c == '}')
        {
            objectDepth--;

            if (isValueScanStarted && !isValueScanCompleted && detectedValueType == TYPE_OBJECT && objectDepth == 1)
            {
                valueEndPosition = i;
                isValueScanCompleted = true;
            }

            if (isValueScanStarted && !isValueScanCompleted && detectedValueType == TYPE_OTHER)
            {
                valueEndPosition = i - 1;
                isValueScanCompleted = true;
            }
        }
        else if (c == '"')
        {
            if (!isValueScanStarted)
            {
                if (!isFieldNameScanStarted)
                {
                    fieldNameStartPosition = i + 1;
                    isFieldNameScanStarted = true;
                }
                else
                {
                    fieldNameEndPosition = i - 1;
                    isFieldNameScanCompleted = true;
                }
            }
            else
            {
                if (!isValueTypeDetected)
                {
                    detectedValueType = TYPE_STRING;
                    isValueTypeDetected = true;
                }
                else
                {
                    if (!isValueScanCompleted && detectedValueType == TYPE_STRING)
                    {
                        valueEndPosition = i;
                        isValueScanCompleted = true;
                    }
                }
            }
        }
        else if (c == ':')
        {
            if (!isValueScanStarted)
            {
                valueStartPosition = i + 1;
                isValueScanStarted = true;
            }
        }
        else if (c == ',')
        {
            if (isValueScanStarted && !isValueScanCompleted && detectedValueType == TYPE_OTHER)
            {
                valueEndPosition = i - 1;
                isValueScanCompleted = true;
            }
        }
        else if (c == '[')
        {
            if (isValueScanStarted && !isValueScanCompleted && !isValueTypeDetected)
            {
                detectedValueType = TYPE_ARRAY;
                isValueTypeDetected = true;
            }
        }
        else if (c == ']')
        {
            if (isValueScanStarted && !isValueScanCompleted && detectedValueType == TYPE_ARRAY)
            {
                valueEndPosition = i;
                isValueScanCompleted = true;
            }
        }
        else if (char.IsWhiteSpace(c))
        {
            lastWhiteSpacePosition = i;
        }

        if (isFieldNameScanStarted && isFieldNameScanCompleted)
        {
            ReadOnlySpan<char> fieldName = jsonPayloadString[fieldNameStartPosition..(fieldNameEndPosition + 1)];

            if (fieldName.Equals(targetField, StringComparison.Ordinal))
            {
                isTargetField = true;
            }

            isFieldNameScanStarted = false;
            isFieldNameScanCompleted = false;
        }

        if (isValueScanStarted && isValueScanCompleted)
        {
            if (isTargetField)
            {
                ReadOnlySpan<char> value = jsonPayloadString[valueStartPosition..(valueEndPosition + 1)];

                if (preserveWhiteSpaces)
                {
                    return value.ToString();
                }
                else
                {
                    return value.ToString().Trim();
                }
            }

            isValueScanStarted = false;
            isValueScanCompleted = false;
            isValueTypeDetected = false;
            detectedValueType = TYPE_OTHER;
        }

    }

    return null;
}
</code>```

Usage:

```<code>byte[] jsonPayloadReceivedFromSomewhere = Encoding.UTF8.GetBytes(
@"{
  ""Data"": {
    ""A"": {
      ""A1"": ""S"",
      ""A2"": 0.0
    }
  },
  ""NoData"":             ""hello
world!!@#$%^&*()_+-=[]{}|\/?><,.`01234     56789
""
, ""TestArray"":            [1, 2, 3 , 4, 5], ""TestBoolean"" :       true
,        ""TestDouble""       :  123.45678
, ""TestInteger"" :-9999

}");

string a = ExtractInnerJsonObject(jsonPayloadReceivedFromSomewhere, "Data");
string b = ExtractInnerJsonObject(jsonPayloadReceivedFromSomewhere, "NoData");
string c = ExtractInnerJsonObject(jsonPayloadReceivedFromSomewhere, "InvalidField");
string d = ExtractInnerJsonObject(jsonPayloadReceivedFromSomewhere, "TestArray");
string e = ExtractInnerJsonObject(jsonPayloadReceivedFromSomewhere, "TestBoolean");
string f = ExtractInnerJsonObject(jsonPayloadReceivedFromSomewhere, "TestDouble");
string g = ExtractInnerJsonObject(jsonPayloadReceivedFromSomewhere, "TestInteger");
</code>```

Result:

Body:
I've got a file with JSON content like this:

{
  "Data": {
    "A": {
      "A1": "S",
      "A2": 0.0
    }
  },
  "NoData": "text"
}

What I want to achieve is to get the inner json of "Data" as a string. I do not want it to be deserialized as an object. I already tried to deserialize it with Json.NET JsonConvert.DeserializeObject<TestClass> where Test class is defined as

class Testclass
{
  public string Data {get; set;}
  public string NoData {get; set;}
}

But this results in Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: {. Path 'Data', line 2, position 11.

The data in "Data" is cryptographically signed by a remote server and the signature needs to be checked. But I do not necessarily have the same classes the data was serialized with at the clients side. That's why I want to do as few conversions as possible. So deserializing and serializing again may change the original string in "data". All spaces and linebreaks have to stay intact.

Body:
I had implemented a naive JSON parser just for solving this specific problem, here's the code:

Method:

static string ExtractInnerJsonObject(ReadOnlySpan<byte> jsonPayload, ReadOnlySpan<char> targetField, bool preserveWhiteSpaces = false)
{
    const int TYPE_OTHER = 0;
    const int TYPE_OBJECT = 1;
    const int TYPE_STRING = 2;
    const int TYPE_ARRAY = 3;

    ReadOnlySpan<char> jsonPayloadString = Encoding.UTF8.GetString(jsonPayload).AsSpan();

    int objectDepth = 0;
    int lastWhiteSpacePosition = 0;
    int fieldNameStartPosition = 0;
    int fieldNameEndPosition = 0;
    int valueStartPosition = 0;
    int valueEndPosition = 0;
    int detectedValueType = TYPE_OTHER;

    bool isValueTypeDetected = false;

    bool isValueScanStarted = false;
    bool isValueScanCompleted = false;

    bool isTargetField = false;
    bool isFieldNameScanStarted = false;
    bool isFieldNameScanCompleted = false;

    for (int i = 0; i < jsonPayloadString.Length; i++)
    {
        char c = jsonPayloadString[i];

        if (c == '{')
        {
            objectDepth++;

            if (isValueScanStarted && !isValueScanCompleted && !isValueTypeDetected)
            {
                detectedValueType = TYPE_OBJECT;
                isValueTypeDetected = true;
            }
        }
        else if (c == '}')
        {
            objectDepth--;

            if (isValueScanStarted && !isValueScanCompleted && detectedValueType == TYPE_OBJECT && objectDepth == 1)
            {
                valueEndPosition = i;
                isValueScanCompleted = true;
            }

            if (isValueScanStarted && !isValueScanCompleted && detectedValueType == TYPE_OTHER)
            {
                valueEndPosition = i - 1;
                isValueScanCompleted = true;
            }
        }
        else if (c == '"')
        {
            if (!isValueScanStarted)
            {
                if (!isFieldNameScanStarted)
                {
                    fieldNameStartPosition = i + 1;
                    isFieldNameScanStarted = true;
                }
                else
                {
                    fieldNameEndPosition = i - 1;
                    isFieldNameScanCompleted = true;
                }
            }
            else
            {
                if (!isValueTypeDetected)
                {
                    detectedValueType = TYPE_STRING;
                    isValueTypeDetected = true;
                }
                else
                {
                    if (!isValueScanCompleted && detectedValueType == TYPE_STRING)
                    {
                        valueEndPosition = i;
                        isValueScanCompleted = true;
                    }
                }
            }
        }
        else if (c == ':')
        {
            if (!isValueScanStarted)
            {
                valueStartPosition = i + 1;
                isValueScanStarted = true;
            }
        }
        else if (c == ',')
        {
            if (isValueScanStarted && !isValueScanCompleted && detectedValueType == TYPE_OTHER)
            {
                valueEndPosition = i - 1;
                isValueScanCompleted = true;
            }
        }
        else if (c == '[')
        {
            if (isValueScanStarted && !isValueScanCompleted && !isValueTypeDetected)
            {
                detectedValueType = TYPE_ARRAY;
                isValueTypeDetected = true;
            }
        }
        else if (c == ']')
        {
            if (isValueScanStarted && !isValueScanCompleted && detectedValueType == TYPE_ARRAY)
            {
                valueEndPosition = i;
                isValueScanCompleted = true;
            }
        }
        else if (char.IsWhiteSpace(c))
        {
            lastWhiteSpacePosition = i;
        }

        if (isFieldNameScanStarted && isFieldNameScanCompleted)
        {
            ReadOnlySpan<char> fieldName = jsonPayloadString[fieldNameStartPosition..(fieldNameEndPosition + 1)];

            if (fieldName.Equals(targetField, StringComparison.Ordinal))
            {
                isTargetField = true;
            }

            isFieldNameScanStarted = false;
            isFieldNameScanCompleted = false;
        }

        if (isValueScanStarted && isValueScanCompleted)
        {
            if (isTargetField)
            {
                ReadOnlySpan<char> value = jsonPayloadString[valueStartPosition..(valueEndPosition + 1)];

                if (preserveWhiteSpaces)
                {
                    return value.ToString();
                }
                else
                {
                    return value.ToString().Trim();
                }
            }

            isValueScanStarted = false;
            isValueScanCompleted = false;
            isValueTypeDetected = false;
            detectedValueType = TYPE_OTHER;
        }

    }

    return null;
}

Usage:

byte[] jsonPayloadReceivedFromSomewhere = Encoding.UTF8.GetBytes(
@"{
  ""Data"": {
    ""A"": {
      ""A1"": ""S"",
      ""A2"": 0.0
    }
  },
  ""NoData"":             ""hello
world!!@#$%^&*()_+-=[]{}|\/?><,.`01234     56789
""
, ""TestArray"":            [1, 2, 3 , 4, 5], ""TestBoolean"" :       true
,        ""TestDouble""       :  123.45678
, ""TestInteger"" :-9999

}");

string a = ExtractInnerJsonObject(jsonPayloadReceivedFromSomewhere, "Data");
string b = ExtractInnerJsonObject(jsonPayloadReceivedFromSomewhere, "NoData");
string c = ExtractInnerJsonObject(jsonPayloadReceivedFromSomewhere, "InvalidField");
string d = ExtractInnerJsonObject(jsonPayloadReceivedFromSomewhere, "TestArray");
string e = ExtractInnerJsonObject(jsonPayloadReceivedFromSomewhere, "TestBoolean");
string f = ExtractInnerJsonObject(jsonPayloadReceivedFromSomewhere, "TestDouble");
string g = ExtractInnerJsonObject(jsonPayloadReceivedFromSomewhere, "TestInteger");

Result:


来源: stackexchange

问:
list indiced must be integers or slices not tuples
What I want to do is to import only 6 rows into 2D list here is part my code :

```<code>cur = connection.cursor()
sql_select_query = """select * from image"""
cur.execute(sql_select_query)
record = cur.fetchall()

imgs_recently = [["","",""],["","",""],["","",""],["","",""],["","",""],["","",""]]

for row in record:
    imgs_recently[row][0] = row[0] # img id
    imgs_recently[row][1] = row[2] # location
    imgs_recently[row][2] = row[5] # img path
</code>```

I'm guising that my mistake is that i used row as array and as index ? If so how can i resolve this error ?

答:
```<code>imgs_recently = [ [ row[0], row[2], row[5] ] for row in record[:6] ]
</code>```

That's it.

ContentLicense: CC BY-SA 4.0

Body:
What I want to do is to import only 6 rows into 2D list here is part my code :

cur = connection.cursor()
sql_select_query = """select * from image"""
cur.execute(sql_select_query)
record = cur.fetchall()

imgs_recently = [["","",""],["","",""],["","",""],["","",""],["","",""],["","",""]]

for row in record:
    imgs_recently[row][0] = row[0] # img id
    imgs_recently[row][1] = row[2] # location
    imgs_recently[row][2] = row[5] # img path

I'm guising that my mistake is that i used row as array and as index ? If so how can i resolve this error ?

Body:
imgs_recently = [ [ row[0], row[2], row[5] ] for row in record[:6] ]

That's it.


问:
Command line tool to dump Windows DLL version?
I need a command line tool to dump standard Windows DLL version info so I can process it by means of a bash script (Cygwin).

As a Java developer I am not very used to Microsoft development tools (though I have a little bit of experience with Microsoft Visual Embedded C++ 4.0 and Microsoft Visual Basic 6.0).

The appropriate tool seems to be mt.exe, as stated on SO. However the only chance I have found to get this little application is to download a 1.29 GB ISO of the Windows SDK for Windows Server 2008 and .NET Framework. I can not believe this is the only way to do it.

I have also found a little application on the Internet called PEView, but it displays too much (and useless in my case) information and it is not a command line application.

Standard objdump bundled inside Cygwin can also dump some information about the DLL files, but I can not see the option to dump DLL version. Note that MajorImageVersion, MinorImageVersion and other fields dumped by this tool (with -p option) are not related to own DLL version.

Any alternatives about what to do? Maybe I missed some important objdump option? Is mt.exe my only choice? If this is the case, is it possible to get it separately from Windows SDK?

答: You can also look at filever.exe, which can be downloaded as part of the Windows XP SP2 Support Tools package - only 4.7MB of download.</p>

OwnerDisplayName: Fernando Miguélez

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Franci Penov


问:
Entity Framework Code First Many to Many Setup For Existing Tables
I have the following tables Essence, EssenseSet, and Essense2EssenceSet

Essense2EssenceSet is the linking table that creates the M:M relationship.

I've been unable to get the M:M relationship working though in EF code first though.

Here's my code:

```<code>[Table("Essence", Schema = "Com")]
    public class Essence
    {
        public int EssenceID { get; set; }
        public string Name { get; set; }
        public int EssenceTypeID { get; set; }
        public string DescLong { get; set; }
        public string DescShort { get; set; }
        public virtual ICollection<EssenceSet> EssenceSets { get; set; }
        public virtual EssenceType EssenceType { get; set; }
    }

    [Table("EssenceSet", Schema = "Com")]
    public class EssenceSet
    {
        public int EssenceSetID { get; set; }
        public int EssenceMakerID { get; set; }
        public string Name { get; set; }
        public string DescLong { get; set; }
        public string DescShort { get; set; }

        public virtual ICollection<Essence> Essences { get; set; }
    }

[Table("Essence2EssenceSet", Schema = "Com")]
    public class Essence2EssenceSet
    {
        //(PK / FK)
        [Key] [Column(Order = 0)] [ForeignKey("Essence")] public int EssenceID { get; set; }
        [Key] [Column(Order = 1)] [ForeignKey("EssenceSet")] public int EssenceSetID { get; set; }

        //Navigation
        public virtual Essence Essence { get; set; }
        public virtual EssenceSet EssenceSet { get; set; }
    }
            public class EssenceContext : DbContext
            {
                public DbSet<Essence> Essences { get; set; }
                public DbSet<EssenceSet> EssenceSets { get; set; }
                public DbSet<Essence2EssenceSet> Essence2EssenceSets { get; set; }

                protected override void OnModelCreating(DbModelBuilder mb)
                {
                    mb.Entity<Essence>()
                        .HasMany(e => e.EssenceSets)
                        .WithMany(set => set.Essences)
                        .Map(mc =>
                            {
                                mc.ToTable("Essence2EssenceSet");
                                mc.MapLeftKey("EssenceID");
                                mc.MapRightKey("EssenceSetID");
                            });
                }
        }
</code>```

This is the code I'm trying to run:

```<code>    Essence e = new Essence();
                            e.EssenceTypeID = (int)(double)dr[1];
                            e.Name          = dr[2].ToString();
                            e.DescLong      = dr[3].ToString();

                            //Get Essence Set
                            int setID = (int)(double)dr[0];
                            var set = ctx.EssenceSets.Find(setID);
                            e.EssenceSets = new HashSet<EssenceSet>();
                            e.EssenceSets.Add(set);
                            ctx.Essences.Add(e);
ctx.SaveChanges();
</code>```

And here's the error:

An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception.

I'm not able to find the problem. I'd greatly appreciate help setting this up right.
Thanks!

答:
Remove your Essence2EssenceSet model class. If junction table contains only keys of related entities participating in many-to-many relations it is not needed to map it as entity. Also make sure that your fluent mapping of many-to-many relations specifies schema for table:

```<code>mb.Entity<Essence>()
  .HasMany(e => e.EssenceSets)
  .WithMany(set => set.Essences)
  .Map(mc =>
      {
          mc.ToTable("Essence2EssenceSet", "Com");
          mc.MapLeftKey("EssenceID");
          mc.MapRightKey("EssenceSetID");
      });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following tables Essence, EssenseSet, and Essense2EssenceSet

Essense2EssenceSet is the linking table that creates the M:M relationship.

I've been unable to get the M:M relationship working though in EF code first though.

Here's my code:

[Table("Essence", Schema = "Com")]
    public class Essence
    {
        public int EssenceID { get; set; }
        public string Name { get; set; }
        public int EssenceTypeID { get; set; }
        public string DescLong { get; set; }
        public string DescShort { get; set; }
        public virtual ICollection<EssenceSet> EssenceSets { get; set; }
        public virtual EssenceType EssenceType { get; set; }
    }

    [Table("EssenceSet", Schema = "Com")]
    public class EssenceSet
    {
        public int EssenceSetID { get; set; }
        public int EssenceMakerID { get; set; }
        public string Name { get; set; }
        public string DescLong { get; set; }
        public string DescShort { get; set; }

        public virtual ICollection<Essence> Essences { get; set; }
    }

[Table("Essence2EssenceSet", Schema = "Com")]
    public class Essence2EssenceSet
    {
        //(PK / FK)
        [Key] [Column(Order = 0)] [ForeignKey("Essence")] public int EssenceID { get; set; }
        [Key] [Column(Order = 1)] [ForeignKey("EssenceSet")] public int EssenceSetID { get; set; }

        //Navigation
        public virtual Essence Essence { get; set; }
        public virtual EssenceSet EssenceSet { get; set; }
    }
            public class EssenceContext : DbContext
            {
                public DbSet<Essence> Essences { get; set; }
                public DbSet<EssenceSet> EssenceSets { get; set; }
                public DbSet<Essence2EssenceSet> Essence2EssenceSets { get; set; }

                protected override void OnModelCreating(DbModelBuilder mb)
                {
                    mb.Entity<Essence>()
                        .HasMany(e => e.EssenceSets)
                        .WithMany(set => set.Essences)
                        .Map(mc =>
                            {
                                mc.ToTable("Essence2EssenceSet");
                                mc.MapLeftKey("EssenceID");
                                mc.MapRightKey("EssenceSetID");
                            });
                }
        }

This is the code I'm trying to run:

    Essence e = new Essence();
                            e.EssenceTypeID = (int)(double)dr[1];
                            e.Name          = dr[2].ToString();
                            e.DescLong      = dr[3].ToString();

                            //Get Essence Set
                            int setID = (int)(double)dr[0];
                            var set = ctx.EssenceSets.Find(setID);
                            e.EssenceSets = new HashSet<EssenceSet>();
                            e.EssenceSets.Add(set);
                            ctx.Essences.Add(e);
ctx.SaveChanges();

And here's the error:

An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception.

I'm not able to find the problem. I'd greatly appreciate help setting this up right.
Thanks!

Body:
Remove your Essence2EssenceSet model class. If junction table contains only keys of related entities participating in many-to-many relations it is not needed to map it as entity. Also make sure that your fluent mapping of many-to-many relations specifies schema for table:

mb.Entity<Essence>()
  .HasMany(e => e.EssenceSets)
  .WithMany(set => set.Essences)
  .Map(mc =>
      {
          mc.ToTable("Essence2EssenceSet", "Com");
          mc.MapLeftKey("EssenceID");
          mc.MapRightKey("EssenceSetID");
      });


问:
How can I get parameters from a URL string?
I have an HTML form field $_POST["url"], having some URL strings as the value.

Example values are:

```
https://example.com/test/1234?email=xyz@test.com
https://example.com/test/1234?basic=2&email=xyz2@test.com
https://example.com/test/1234?email=xyz3@test.com
https://example.com/test/1234?email=xyz4@test.com&testin=123
https://example.com/test/the-page-here/1234?someurl=key&email=xyz5@test.com
```

etc.

How can I get only the email parameter from these URLs/values?

Please note that I am not getting these strings from the browser address bar.

答:
A much more secure answer that I'm surprised is not mentioned here yet:

filter_input

So in the case of the question you can use this to get an email value from the URL get parameters:

$email = filter_input( INPUT_GET, 'email', FILTER_SANITIZE_EMAIL );

For other types of variables, you would want to choose a different/appropriate filter such as FILTER_SANITIZE_STRING.

I suppose this answer does more than exactly what the question asks for - getting the raw data from the URL parameter. But this is a one-line shortcut that is the same result as this:

```<code>$email = $_GET['email'];
$email = filter_var( $email, FILTER_SANITIZE_EMAIL );
</code>```

Might as well get into the habit of grabbing variables this way.

Body:
I have an HTML form field $_POST["url"], having some URL strings as the value.

Example values are:

https://example.com/test/1234?email=xyz@test.com
https://example.com/test/1234?basic=2&email=xyz2@test.com
https://example.com/test/1234?email=xyz3@test.com
https://example.com/test/1234?email=xyz4@test.com&testin=123
https://example.com/test/the-page-here/1234?someurl=key&email=xyz5@test.com

etc.

How can I get only the email parameter from these URLs/values?

Please note that I am not getting these strings from the browser address bar.

Body:
A much more secure answer that I'm surprised is not mentioned here yet:

filter_input

So in the case of the question you can use this to get an email value from the URL get parameters:

$email = filter_input( INPUT_GET, 'email', FILTER_SANITIZE_EMAIL );

For other types of variables, you would want to choose a different/appropriate filter such as FILTER_SANITIZE_STRING.

I suppose this answer does more than exactly what the question asks for - getting the raw data from the URL parameter. But this is a one-line shortcut that is the same result as this:

$email = $_GET['email'];
$email = filter_var( $email, FILTER_SANITIZE_EMAIL );

Might as well get into the habit of grabbing variables this way.


问:
Copy Elision in visual 2019
I was trying to test a small code to check if my compiler (under Visual Studio 2019) does copy elision, as it is no more optional for some cases under C++17.

So I tried the code below :

```<code>#include <iostream>
#include <vector>
using namespace std;

struct myStruct
{
    myStruct() { cout << "default ctor" << endl; }
    myStruct(const myStruct& str) { cout << "copy ctor" << endl; }
    myStruct& operator=(myStruct other) { cout << "Copy assignement" << endl; return *this; }
    myStruct(myStruct&& str) noexcept { cout << "move ctor" << endl; }
    myStruct& operator=(myStruct&& other) { cout << "move assignement" << endl; return *this; }
    ~myStruct() { cout << "deleted" << endl; }
};

myStruct get()
{
    myStruct s;
    return s;
}

int main()
{
    vector<myStruct> vect;
    vect.reserve(10);
    cout << "Creating The Vector" << endl;
    vect.push_back(get());
    vect.push_back(get());
    cout << "Cretion End" << endl;
    return 0;
}
</code>```

So as far as I read, calling the function get() will trigger the RVO so I will get only ctor calls. But when I run the program I get (I added <<<<  in front of lines that are related to copy after calling get() function):

```<code>Creating The Vector
default ctor
move ctor
deleted
move ctor  <<<<
deleted    <<<<
default ctor
move ctor
deleted
move ctor  <<<<
deleted    <<<<
Cretion End
deleted
deleted
</code>```

When tried with gcc I get :

```<code>Creating The Vector
default ctor
move ctor
deleted
default ctor
move ctor
deleted
Cretion End
deleted
deleted
</code>```

So seems that Microsoft still didn't implement the Copy elision, or is there wrong in my code so I missed the real charm of Copy elision?

Thank you in advance

答:
None of the copies in this case are required to be elided by any (currently existing) version of C++. The standard lays down several copies: the copy from s to the return value object of get, and the copy from the reference parameter to push_back into the vector's internal object. The latter copy cannot be elided, and the former copy's elision is not guaranteed to happen at all.

If you're talking about C++17's guaranteed elision, this only applies to the use of a prvalue to initialize an object (of that type). That never happens here (outside of the temporary parameter passed to call push_back, but that's normal for any version of C++), so it doesn't apply.

Here's a simple test: if the source object of the hypothetical copy has a variable name, then elision if applicable is not mandatory.

Title: Copy Elision in visual 2019

Body:
I was trying to test a small code to check if my compiler (under Visual Studio 2019) does copy elision, as it is no more optional for some cases under C++17.

So I tried the code below :

#include <iostream>
#include <vector>
using namespace std;

struct myStruct
{
    myStruct() { cout << "default ctor" << endl; }
    myStruct(const myStruct& str) { cout << "copy ctor" << endl; }
    myStruct& operator=(myStruct other) { cout << "Copy assignement" << endl; return *this; }
    myStruct(myStruct&& str) noexcept { cout << "move ctor" << endl; }
    myStruct& operator=(myStruct&& other) { cout << "move assignement" << endl; return *this; }
    ~myStruct() { cout << "deleted" << endl; }
};

myStruct get()
{
    myStruct s;
    return s;
}

int main()
{
    vector<myStruct> vect;
    vect.reserve(10);
    cout << "Creating The Vector" << endl;
    vect.push_back(get());
    vect.push_back(get());
    cout << "Cretion End" << endl;
    return 0;
}

So as far as I read, calling the function get() will trigger the RVO so I will get only ctor calls. But when I run the program I get (I added <<<<  in front of lines that are related to copy after calling get() function):

Creating The Vector
default ctor
move ctor
deleted
move ctor  <<<<
deleted    <<<<
default ctor
move ctor
deleted
move ctor  <<<<
deleted    <<<<
Cretion End
deleted
deleted

When tried with gcc I get :

Creating The Vector
default ctor
move ctor
deleted
default ctor
move ctor
deleted
Cretion End
deleted
deleted

So seems that Microsoft still didn't implement the Copy elision, or is there wrong in my code so I missed the real charm of Copy elision?

Thank you in advance


问:
Python: Create new column and row in csv file based on data on another column
i have an  output.csv file, a large dataset, with a similar output below:

```<code>index, url
0, www.example1.com
1,
2,
3, www.example2.com
4, www.example3.com
</code>```

I want to add a new column, mail to the csv. I am basically scraping the urls (in the example above row 1 and 2 are empty, no url present) in column2 in output.csv to extract the mails present in the urls.
So the final output I need should be like

```<code> index, url, mail
    0, www.example1.com, example1@gmail.com
    1,
    2,
    3, www.example2.com, example2@yahoo.com
    4, www.example3.com, example3@hotmail.com
</code>```

Is there a way I can achieve this?

答:
I know its not the best way but you can help yourself by using pandas library and create something like this:</p>

```<code>import pandas as pd

df = pd.read_excel('output.xlsx')

def split_value(i):
    if type(i) == str:
        url = i.split('.')[1]+"@some_domaine"
    else:
        url = np.nan
    return url

df['mail'] = [split_value(i) for i in df.url.values]

df
**Out[1]:**
index           url                   mail
0  www.example1.com  example1@some_domaine
1               NaN                    NaN
2               NaN                    NaN
3  www.example2.com  example2@some_domaine
4  www.example3.com  example3@some_domaine

df.to_excel(onemoreoutput.xlsx)
</code>```

Body:
i have an  output.csv file, a large dataset, with a similar output below:

index, url
0, www.example1.com
1,
2,
3, www.example2.com
4, www.example3.com

I want to add a new column, mail to the csv. I am basically scraping the urls (in the example above row 1 and 2 are empty, no url present) in column2 in output.csv to extract the mails present in the urls.
So the final output I need should be like

 index, url, mail
    0, www.example1.com, example1@gmail.com
    1,
    2,
    3, www.example2.com, example2@yahoo.com
    4, www.example3.com, example3@hotmail.com

Is there a way I can achieve this?

Body:
I know its not the best way but you can help yourself by using pandas library and create something like this:

import pandas as pd

df = pd.read_excel('output.xlsx')

def split_value(i):
    if type(i) == str:
        url = i.split('.')[1]+"@some_domaine"
    else:
        url = np.nan
    return url

df['mail'] = [split_value(i) for i in df.url.values]

df
**Out[1]:**
index           url                   mail
0  www.example1.com  example1@some_domaine
1               NaN                    NaN
2               NaN                    NaN
3  www.example2.com  example2@some_domaine
4  www.example3.com  example3@some_domaine

df.to_excel(onemoreoutput.xlsx)


问:
Get IFTA (State Miles)
I used postman to get a route and it returned the instructions, the polygon, traffic information, but I didn't see where you can request state miles breakdown.

Can the azure maps return miles per state breakdown?
I need this to calculate IFTA per trip.

答: Azure Maps currently does not have an option to return the distances travelled within states that a route crosses. This is however something that is being investigated as a future feature.</p>

Title: Get IFTA (State Miles)


问:
ActionScript 3 - objects?
I'm new to Flash AS3. I started making a game and I am a bit confused. Let's assume that I want to create a game that has multiple levels/modes, how can I do this in an object orientated way?

When i create games in other languages e.g. XNA C#, i create a separate class then create an object of that class within the main class and run the game based on a simple statement.

```<code>if(player picks second option)
object2.start_level
else
object1.start_level
</code>```

How can this be done is AS3? Are there any Tutorials I could read on, please? Thanks.

答:
Hm, if I understood correctly your question, you should behave just as you used to in XNA C#: two instances(object1 and object2) of class Level and

```<code>if(player picks second option) object2.start_level else object1.start_level
</code>```

If I understood you incorrectly feel free to reask and specify your question.

P.S.: you can read about how to create classes in AS3 here

Title: ActionScript 3 - objects?

Body:
I'm new to Flash AS3. I started making a game and I am a bit confused. Let's assume that I want to create a game that has multiple levels/modes, how can I do this in an object orientated way?

When i create games in other languages e.g. XNA C#, i create a separate class then create an object of that class within the main class and run the game based on a simple statement.

if(player picks second option)
object2.start_level
else
object1.start_level

How can this be done is AS3? Are there any Tutorials I could read on, please? Thanks.

Body:
Hm, if I understood correctly your question, you should behave just as you used to in XNA C#: two instances(object1 and object2) of class Level and

if(player picks second option) object2.start_level else object1.start_level

If I understood you incorrectly feel free to reask and specify your question.

P.S.: you can read about how to create classes in AS3 here


问:
Insert text from a Text Area in a MySQL DB (Python/Flask)
I want to code a small message feed for my homepage. I want to send a text from a textarea to my Database
this is my html template:

```<code> {% extends 'layout.html'%}

 {% block body%}

   <form action="/feed" method="post">
   <table>
     <tr>
       <td><textarea name="feedtext" id="feedtext" placeholder="Type message here!" rows="4" cols="53"></textarea></td>
     </tr>
     <tr>
       <td><button style="width: 65%;" "submit"\>Send</button></td>
     </tr>
   </table>
   </form>

{% endblock %}
</code>```

now my problem is the python part. I try anything but I don't get the right code.

this is my python code now:

```<code> @app.route('/feed', methods=['POST'])
 def feed():
     try:
         conn = mysql.connect()
         cursor = conn.cursor()
         feedtxt = request.form['feedtext']

         cursor.execute('INSERT INTO nachrichten (Vorname, Nachname, Nachricht) VALUES(%);', (feedtxt))

     finally:
         cursor.close()
         conn.close()
</code>```

答:
Welcome.

Can not make out "I try anything but I don't get the right code".

Anyway, out of the columns

(Vorname, Nachname, Nachricht)

it seems only the Nachricht gets the value of (feedtxt).

Try giving 3 items within VALUES

Body:
I want to code a small message feed for my homepage. I want to send a text from a textarea to my Database
this is my html template:

 {% extends 'layout.html'%}

 {% block body%}

   <form action="/feed" method="post">

       <textarea name="feedtext" id="feedtext" placeholder="Type message here!" rows="4" cols="53"></textarea>

       <button style="width: 65%;" "submit"\>Send</button>

   </form>

{% endblock %}

now my problem is the python part. I try anything but I don't get the right code.

this is my python code now:

 @app.route('/feed', methods=['POST'])
 def feed():
     try:
         conn = mysql.connect()
         cursor = conn.cursor()
         feedtxt = request.form['feedtext']

         cursor.execute('INSERT INTO nachrichten (Vorname, Nachname, Nachricht) VALUES(%);', (feedtxt))

     finally:
         cursor.close()
         conn.close()


问:
Is Spring Boot just for Microservices ? can i use Spring Boot for Monolithic architecture?
Is Spring Boot just for Microservices or can I use Spring Boot for Monolithic architecture?</p>

答:
Spring Boot in itself has nothing to do with microservices. It's a Spring module which simply makes the configuration of your app easier. As such, it absolutely can be used in a monolithic app.

From the official docs:

Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run".

We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration.

Features

Create stand-alone Spring applications

Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)

Provide opinionated 'starter' dependencies to simplify your build configuration

Automatically configure Spring and 3rd party libraries whenever possible

Provide production-ready features such as metrics, health checks and externalized configuration

Absolutely no code generation and no requirement for XML configuration


答:
you are using row as list indices that's why its throwing this kind of error.

so in you case row is a tuple, you have to use integers or slices. so you can try with row[n]

Title: list indiced must be integers or slices not tuples


问:
Checking some columns for specific values before insert/update using a trigger
I have a database FOO with several columns, among those I have one column "Url". I need to write a trigger before insert/update that will check the Url columns whether the newer value matches any existing values, i.e. "hello" except some predefined value. That means if "hello" is inserted or updated multiple times no error will happen otherwise it will check for duplicity. And if it finds some aborts the insertion update. This will also return some code so that my script calling for the insertion/update will know a failure has occurred. I know there might be other workarounds but I will need to have it this way. I am pretty new to SQL.

```<code>Foo {
    Url
}
</code>```

Here is the algorithm

```<code>Before update insert
if new value of Url is not "hello1" o "hello 2"
    check if new value of Url already exists in Foo.Url if so abort otherwise allow update/insert
     return something if aborted/success
</code>```

答:
I suppose you're looking for a UNIQUE constraint & a CHECK constraint as

```<code>CREATE TABLE Foo(
  Url VARCHAR(250) NOT NULL,
  CONSTRAINT UQ_Url UNIQUE(Url),
  CONSTRAINT CHK_Url CHECK (Url NOT IN ('hello1', 'hello2'))
);
</code>```

See how it's working online.

Body:
I have a database FOO with several columns, among those I have one column "Url". I need to write a trigger before insert/update that will check the Url columns whether the newer value matches any existing values, i.e. "hello" except some predefined value. That means if "hello" is inserted or updated multiple times no error will happen otherwise it will check for duplicity. And if it finds some aborts the insertion update. This will also return some code so that my script calling for the insertion/update will know a failure has occurred. I know there might be other workarounds but I will need to have it this way. I am pretty new to SQL.

Foo {
    Url
}

Here is the algorithm

Before update insert
if new value of Url is not "hello1" o "hello 2"
    check if new value of Url already exists in Foo.Url if so abort otherwise allow update/insert
     return something if aborted/success

Body:
I suppose you're looking for a UNIQUE constraint & a CHECK constraint as

CREATE TABLE Foo(
  Url VARCHAR(250) NOT NULL,
  CONSTRAINT UQ_Url UNIQUE(Url),
  CONSTRAINT CHK_Url CHECK (Url NOT IN ('hello1', 'hello2'))
);

See how it's working online.


问:
Visual Studio 2008 debugging: when I click on the play button, it flashes real quick
I am having a weird issue with VS 2008 when I go to debug my program. When I click on the play button to run the program it flashes real quick and goes back to the VB IDE. No matter how many times I click on the play button it continually flashes and then goes back without displaying my form window or anything.

What type of setting would I need to change in order to correct this issue? I've been through most settings in the "my project" section and i do not see anything that could be causing it to do something like this.

My older vb apps I've made seem to work just fine when I click the play button on them. Only noticed this problem whenever I go and make a new vb app.

update video of what's going on
http://tinypic.com/r/2eycaas/7

答: Is the startup form correct? You can see that in project properties.</p>


问:
Says it cannot be used as constant
Visual studio 2019

```<code>const int inputs = 1, layers = 2, layerN = 3, output = 1;
const int how = inputs * layerN + pow(layerN,layers) + output * layerN;
float w[how];
</code>```

it says on w[how] that it must be "const" expression(but is is??)

I cannot run the program with this error.

hielp.

答:
how is not a constant expression. Its value is not known to the compiler at compile-time, it is calculated dynamically at runtime because of the function call to pow(). As such, it cannot be used to declare a fixed length array. You will have to use new[] or a std::vector instead:

```<code>float *w = new float[how];
...
delete[] w;
</code>```

```<code>#include <vector>
std::vector<float> w(how);
</code>```

Title: Says it cannot be used as constant

Body:
Visual studio 2019

const int inputs = 1, layers = 2, layerN = 3, output = 1;
const int how = inputs * layerN + pow(layerN,layers) + output * layerN;
float w[how];

it says on w[how] that it must be "const" expression(but is is??)

I cannot run the program with this error.

hielp.

Body:
how is not a constant expression. Its value is not known to the compiler at compile-time, it is calculated dynamically at runtime because of the function call to pow(). As such, it cannot be used to declare a fixed length array. You will have to use new[] or a std::vector instead:

float *w = new float[how];
...
delete[] w;

#include <vector>
std::vector<float> w(how);


问:
what is the diff b/w pset and psetx in php redis?Is it possible set a array as value with it?
```<code>$redisClient -> setex('key', 3600, 'value' );
</code>```

and

```<code>$redisClient -> psetex('key', 3600, 'value' );
</code>```

答:
https://redis.io/commands/set vs https://redis.io/commands/setex

and yes, serialize the data with serialize or jasn_encode.

Body:
$redisClient -> setex('key', 3600, 'value' );

and

$redisClient -> psetex('key', 3600, 'value' );


答:
Perhaps it is more clear if you consider this example:

```<code>int x;
std::cin >> x;
const int y = x;
float w[y];   // error
</code>```

y is const, ie during runtime its value cannot possibly change. However to allocate memory for an array the compiler needs to know the size. Making y a constant alone is not sufficient to achieve that. In your case it is not reading user input, but the call to pow that prevents the compiler from knowing the value.

PS: You might want to read about constexpr which is a much stronger guarantee than const. Unfortunately there is no constexpr version of pow.

Title: Says it cannot be used as constant

Body:
Perhaps it is more clear if you consider this example:

int x;
std::cin >> x;
const int y = x;
float w[y];   // error

y is const, ie during runtime its value cannot possibly change. However to allocate memory for an array the compiler needs to know the size. Making y a constant alone is not sufficient to achieve that. In your case it is not reading user input, but the call to pow that prevents the compiler from knowing the value.

PS: You might want to read about constexpr which is a much stronger guarantee than const. Unfortunately there is no constexpr version of pow.


问:
while inserting data to database using postman showing error in controller file
while using node.js i am not able to insert a data to database ,i am using express.js ,mongoose but getting error which i mentioned in code as comment

Blockquote
  error is
  Blockquote
  TypeError: Cannot read property 'name' of undefined
      at insert (E:\node\website\controller\signup.js:5:25)
      at Layer.handle [as handle_request] (E:\node\website\node_modules\express\lib\router\layer.js:95:5)
      at next (E:\node\website\node_modules\express\lib\router\route.js:137:13)
      at Route.dispatch (E:\node\website\node_modules\express\lib\router\route.js:112:3)
      at Layer.handle [as handle_request] (E:\node\website\node_modules\express\lib\router\layer.js:95:5)
      at E:\node\website\node_modules\express\lib\router\index.js:281:22
      at Function.process_params (E:\node\website\node_modules\express\lib\router\index.js:335:12)
      at next (E:\node\website\node_modules\express\lib\router\index.js:275:10)
      at Function.handle (E:\node\website\node_modules\express\lib\router\index.js:174:3)
      at router (E:\node\website\node_modules\express\lib\router\index.js:47:12)
      at Layer.handle [as handle_request] (E:\node\website\node_modules\express\lib\router\layer.js:95:5)
      at trim_prefix (E:\node\website\node_modules\express\lib\router\index.js:317:13)
      at E:\node\website\node_modules\express\lib\router\index.js:284:7
      at Function.process_params (E:\node\website\node_modules\express\lib\router\index.js:335:12)
      at next (E:\node\website\node_modules\express\lib\router\index.js:275:10)
      at expressInit (E:\node\website\node_modules\express\lib\middleware\init.js:40:5)
      at Layer.handle [as handle_request] (E:\node\website\node_modules\express\lib\router\layer.js:95:5)
      at trim_prefix (E:\node\website\node_modules\express\lib\router\index.js:317:13)
      at E:\node\website\node_modules\express\lib\router\index.js:284:7
      at Function.process_params (E:\node\website\node_modules\express\lib\router\index.js:335:12)
      at next (E:\node\website\node_modules\express\lib\router\index.js:275:10)
      at query (E:\node\website\node_modules\express\lib\middleware\query.js:45:5)
  Blockquote
      //controller file named as signup.js

```<code>var express=require('express');
var post1=require('../model/singup')
var router=express.Router();
var insert=(req,res)=>{
    var name1= req.body.name;// error:name is not defined
    var email1= req.body.email;//error:email is not defined
    var password1= req.body.password;//error:password is not defined
    post1.create({
        name: name1,email:email1,password:password1
    },(err,result)=>{
        if(err){res.json({message:'error'
           })
        }
        else{res.json({message:'sucessful',result:result
        })
     }
})
}
router.post('/signup',insert);
router.get('/h',(req,res)=>{
    res.json({
        message:'insert'
    })
    console.log("insert");
    })
module.exports=router;
</code>```

Blockquote
      //model file named as signup.js

```<code>require('../db');
var mongoose=require('mongoose');
mongoose.Promise=require('bluebird');
var schema= new mongoose.Schema({
    name:{type:String,required:true},
    email:{type:String,required:true},
    password:{type:String,required:true},
},
{timestamp:true});
module.exports=mongoose.model('post1',schema);
</code>```

Blockquote
      //db.js file for database connection

```<code>var mongose=require('mongoose');
mongose.set('useNewUrlParser', 'true');
mongose.set('useCreateIndex', 'true');
mongose.set('useFindAndModify', 'true');
mongose.connect("mongodb://127.0.0.1:27017/website");
var db=mongose.connection;
db.on('error',console.error.bind(console,'connection error'));
db.once('open',(req,res)=>{
    console.log("connected with db!!!");
})
</code>```

Blockquote
  //index.js

```<code>var app=require('./server')
var signup=require('./controller/signup')

 var session=require('express-session')
app.set('viewengin','ejs')
app.set('useNewUrlParser', 'true')
app.set('useUnifiedTopology', 'true')
app.use('/user',signup)
app.use(session({
    secret:'keyboard cat ',
    resave:false,
    cookies:{
        secrue:true
    },
}))
app.all('*',(req,res)=>{
    return res.json({status: 205,message: 'not found'});
})
var server=app.get('/',(req,res)=>{
req.end()
});
</code>```

答:
Seems you are missing the body-parser middleware.

$ npm i body-parser
```

<pre class="lang-js prettyprint-override"><code>var express=require('express');
var bodyParser = require('body-parser');

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())
</code>```

Body:
while using node.js i am not able to insert a data to database ,i am using express.js ,mongoose but getting error which i mentioned in code as comment

Blockquote
  error is
  Blockquote
  TypeError: Cannot read property 'name' of undefined
      at insert (E:\node\website\controller\signup.js:5:25)
      at Layer.handle [as handle_request] (E:\node\website\node_modules\express\lib\router\layer.js:95:5)
      at next (E:\node\website\node_modules\express\lib\router\route.js:137:13)
      at Route.dispatch (E:\node\website\node_modules\express\lib\router\route.js:112:3)
      at Layer.handle [as handle_request] (E:\node\website\node_modules\express\lib\router\layer.js:95:5)
      at E:\node\website\node_modules\express\lib\router\index.js:281:22
      at Function.process_params (E:\node\website\node_modules\express\lib\router\index.js:335:12)
      at next (E:\node\website\node_modules\express\lib\router\index.js:275:10)
      at Function.handle (E:\node\website\node_modules\express\lib\router\index.js:174:3)
      at router (E:\node\website\node_modules\express\lib\router\index.js:47:12)
      at Layer.handle [as handle_request] (E:\node\website\node_modules\express\lib\router\layer.js:95:5)
      at trim_prefix (E:\node\website\node_modules\express\lib\router\index.js:317:13)
      at E:\node\website\node_modules\express\lib\router\index.js:284:7
      at Function.process_params (E:\node\website\node_modules\express\lib\router\index.js:335:12)
      at next (E:\node\website\node_modules\express\lib\router\index.js:275:10)
      at expressInit (E:\node\website\node_modules\express\lib\middleware\init.js:40:5)
      at Layer.handle [as handle_request] (E:\node\website\node_modules\express\lib\router\layer.js:95:5)
      at trim_prefix (E:\node\website\node_modules\express\lib\router\index.js:317:13)
      at E:\node\website\node_modules\express\lib\router\index.js:284:7
      at Function.process_params (E:\node\website\node_modules\express\lib\router\index.js:335:12)
      at next (E:\node\website\node_modules\express\lib\router\index.js:275:10)
      at query (E:\node\website\node_modules\express\lib\middleware\query.js:45:5)
  Blockquote
      //controller file named as signup.js

var express=require('express');
var post1=require('../model/singup')
var router=express.Router();
var insert=(req,res)=>{
    var name1= req.body.name;// error:name is not defined
    var email1= req.body.email;//error:email is not defined
    var password1= req.body.password;//error:password is not defined
    post1.create({
        name: name1,email:email1,password:password1
    },(err,result)=>{
        if(err){res.json({message:'error'
           })
        }
        else{res.json({message:'sucessful',result:result
        })
     }
})
}
router.post('/signup',insert);
router.get('/h',(req,res)=>{
    res.json({
        message:'insert'
    })
    console.log("insert");
    })
module.exports=router;

Blockquote
      //model file named as signup.js

require('../db');
var mongoose=require('mongoose');
mongoose.Promise=require('bluebird');
var schema= new mongoose.Schema({
    name:{type:String,required:true},
    email:{type:String,required:true},
    password:{type:String,required:true},
},
{timestamp:true});
module.exports=mongoose.model('post1',schema);

Blockquote
      //db.js file for database connection

var mongose=require('mongoose');
mongose.set('useNewUrlParser', 'true');
mongose.set('useCreateIndex', 'true');
mongose.set('useFindAndModify', 'true');
mongose.connect("mongodb://127.0.0.1:27017/website");
var db=mongose.connection;
db.on('error',console.error.bind(console,'connection error'));
db.once('open',(req,res)=>{
    console.log("connected with db!!!");
})

Blockquote
  //index.js

var app=require('./server')
var signup=require('./controller/signup')

 var session=require('express-session')
app.set('viewengin','ejs')
app.set('useNewUrlParser', 'true')
app.set('useUnifiedTopology', 'true')
app.use('/user',signup)
app.use(session({
    secret:'keyboard cat ',
    resave:false,
    cookies:{
        secrue:true
    },
}))
app.all('*',(req,res)=>{
    return res.json({status: 205,message: 'not found'});
})
var server=app.get('/',(req,res)=>{
req.end()
});

Body:
Seems you are missing the body-parser middleware.

$ npm i body-parser

var express=require('express');
var bodyParser = require('body-parser');

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())


问:
Cursor weird behavior: resets to default
On a mouse move on an NSView, I change the cursor to a hand [[NSCursor pointingHandCursor] set]. I do NOT reset anywhere in the code the cursor to arrow.

This works pretty well, however if I move the mouse slowly I can see at times it reverts to the arrow. This is unwanted. Is that a bug in Cocoa or is there a work around?

```<code>-(void) mouseMoved:(NSEvent*) event {
  [[NSCursor pointingHandCursor] set];
}
</code>```

Again, I do not play with the cursor anywhere else in the code. I do not have other views overlaying on my NSView. Thanks in advance!

答:
If you can make use of purely rectangular areas, using addCursorRect:cursor: etc within resetCursorRects is an easy way to do this.

Otherwise, you can make use of NSTrackingAreas with NSTrackingCursorUpdate set as the option, and in cursorUpdate: use the set method on a cursor like you are.

Using set/push/pop etc on their own isn't stable because it's not cooperative with other views which set the cursor.

Body:
On a mouse move on an NSView, I change the cursor to a hand [[NSCursor pointingHandCursor] set]. I do NOT reset anywhere in the code the cursor to arrow.

This works pretty well, however if I move the mouse slowly I can see at times it reverts to the arrow. This is unwanted. Is that a bug in Cocoa or is there a work around?

-(void) mouseMoved:(NSEvent*) event {
  [[NSCursor pointingHandCursor] set];
}

Again, I do not play with the cursor anywhere else in the code. I do not have other views overlaying on my NSView. Thanks in advance!


问:
How to validate each form step in material ui stepper?
Typical material-ui stepper below.

```<code>  export default function HorizontalLinearStepper() {
    const classes = useStyles();
    const [activeStep, setActiveStep] = React.useState(0);
    const [skipped, setSkipped] = React.useState(new Set());
    const steps = getSteps();

    const isStepOptional = step => {
        return step === 1;
    };

    const isStepSkipped = step => {
        return skipped.has(step);
    };

    const handleNext = () => {
    let newSkipped = skipped;
    if (isStepSkipped(activeStep)) {
        newSkipped = new Set(newSkipped.values());
        newSkipped.delete(activeStep);
    }

    setActiveStep(prevActiveStep => prevActiveStep + 1);
    setSkipped(newSkipped);
};

const handleBack = () => {
    setActiveStep(prevActiveStep => prevActiveStep - 1);
};

const handleSkip = () => {
    if (!isStepOptional(activeStep)) {
        // You probably want to guard against something like this,
        // it should never occur unless someone's actively trying to break something.
        throw new Error("You can't skip a step that isn't optional.");
    }

    setActiveStep(prevActiveStep => prevActiveStep + 1);
    setSkipped(prevSkipped => {
        const newSkipped = new Set(prevSkipped.values());
        newSkipped.add(activeStep);
        return newSkipped;
    });
};

const handleReset = () => {
    setActiveStep(0);
};

return (
    <div className={classes.root}>
        <Stepper activeStep={activeStep}>
            {steps.map((label, index) => {
                const stepProps = {};
                const labelProps = {};
                if (isStepOptional(index)) {
                    labelProps.optional = <Typography variant="caption">Optional</Typography>;
                }
                if (isStepSkipped(index)) {
                    stepProps.completed = false;
                }
                return (
                    <Step key={label} {...stepProps}>
                        <StepLabel {...labelProps}>{label}</StepLabel>
                    </Step>
                );
            })}
        </Stepper>
        <div>
            {activeStep === steps.length ? (
                <div>
                    <Typography className={classes.instructions}>
                        All steps completed - you're finished
                    </Typography>
                    <Button onClick={handleReset} className={classes.button}>
                        Reset
                    </Button>
                </div>
            ) : (
                <div>
                    <div className={classes.instructions}>{getStepContent(activeStep)}</div>
                    <div>
                        <Button disabled={activeStep === 0} onClick={handleBack} className={classes.button}>
                            Back
                        </Button>
                        {isStepOptional(activeStep) && (
                            <Button
                                variant="contained"
                                color="primary"
                                onClick={handleSkip}
                                className={classes.button}
                            >
                                Skip
                            </Button>
                        )}

                        <Button
                            variant="contained"
                            color="primary"
                            onClick={handleNext}
                            type="submit"
                            className={classes.button}
                        >
                            {activeStep === steps.length - 1 ? 'Finish' : 'Next'}
                        </Button>
                    </div>
                </div>
            )}
        </div>
    </div>
    );
}
</code>```

Here is function i create to choice step

```<code>function getStepContent(step) {
    switch (step) {
        case 0:
            return <Step1/>;
        case 1:
            return <Step2/>;
        case 2:
            return 'This is the bit I really care about!';
        default:
            return 'Unknown step';
    }
}
</code>```

Step1 and Step2 are components that has 2 forms inside build with react-final-form

```<code>import React, { Component } from 'react';
import { Form } from 'react-final-form';
import initialValuesCreator from './creationMethods/initialValuesCreator';
import { validationCreator } from './creationMethods/validationSchemaCreator';

class CustomValidationForm extends Component {

    render() {
        const {
            config ,children, submit = () => {}
        } = this.props;

        return (
            <Form
                onSubmit={(event) => {
                    submit(event);
                }}
                initialValues={initialValuesCreator(config)}
                validate={values => validationCreator(values, config)}
                render={({handleSubmit}) => (
                    <form noValidate autoComplete={'off'} onSubmit={handleSubmit}>
                        {children}
                    </form>
                )}
            />
        )
    }
}
</code>```

And here comes the question. Material ui stepper has handleNext function. Its my submit for each step. Each step will be some kind of form with validation. When user is on step1 and he press submit i want to show him input errors (something is required etc) and prevent jumping to next step. Step1 can have multiple small forms so all the form should be validated when handleNext is pressed.

答: The best way I've come up with to do step-wise validation is by breaking the form up into little forms and have a controller component combine all the form values together like in the Wizard Form Example.</p>

Body:
Typical material-ui stepper below.

  export default function HorizontalLinearStepper() {
    const classes = useStyles();
    const [activeStep, setActiveStep] = React.useState(0);
    const [skipped, setSkipped] = React.useState(new Set());
    const steps = getSteps();

    const isStepOptional = step => {
        return step === 1;
    };

    const isStepSkipped = step => {
        return skipped.has(step);
    };

    const handleNext = () => {
    let newSkipped = skipped;
    if (isStepSkipped(activeStep)) {
        newSkipped = new Set(newSkipped.values());
        newSkipped.delete(activeStep);
    }

    setActiveStep(prevActiveStep => prevActiveStep + 1);
    setSkipped(newSkipped);
};

const handleBack = () => {
    setActiveStep(prevActiveStep => prevActiveStep - 1);
};

const handleSkip = () => {
    if (!isStepOptional(activeStep)) {
        // You probably want to guard against something like this,
        // it should never occur unless someone's actively trying to break something.
        throw new Error("You can't skip a step that isn't optional.");
    }

    setActiveStep(prevActiveStep => prevActiveStep + 1);
    setSkipped(prevSkipped => {
        const newSkipped = new Set(prevSkipped.values());
        newSkipped.add(activeStep);
        return newSkipped;
    });
};

const handleReset = () => {
    setActiveStep(0);
};

return (

        <Stepper activeStep={activeStep}>
            {steps.map((label, index) => {
                const stepProps = {};
                const labelProps = {};
                if (isStepOptional(index)) {
                    labelProps.optional = <Typography variant="caption">Optional</Typography>;
                }
                if (isStepSkipped(index)) {
                    stepProps.completed = false;
                }
                return (
                    <Step key={label} {...stepProps}>
                        <StepLabel {...labelProps}>{label}</StepLabel>
                    </Step>
                );
            })}
        </Stepper>

            {activeStep === steps.length ? (

                    <Typography className={classes.instructions}>
                        All steps completed - you're finished
                    </Typography>
                    <Button onClick={handleReset} className={classes.button}>
                        Reset
                    </Button>

            ) : (

{getStepContent(activeStep)}

                        <Button disabled={activeStep === 0} onClick={handleBack} className={classes.button}>
                            Back
                        </Button>
                        {isStepOptional(activeStep) && (
                            <Button
                                variant="contained"
                                color="primary"
                                onClick={handleSkip}
                                className={classes.button}
                            >
                                Skip
                            </Button>
                        )}

                        <Button
                            variant="contained"
                            color="primary"
                            onClick={handleNext}
                            type="submit"
                            className={classes.button}
                        >
                            {activeStep === steps.length - 1 ? 'Finish' : 'Next'}
                        </Button>

            )}

    );
}

Here is function i create to choice step

function getStepContent(step) {
    switch (step) {
        case 0:
            return <Step1/>;
        case 1:
            return <Step2/>;
        case 2:
            return 'This is the bit I really care about!';
        default:
            return 'Unknown step';
    }
}

Step1 and Step2 are components that has 2 forms inside build with react-final-form

import React, { Component } from 'react';
import { Form } from 'react-final-form';
import initialValuesCreator from './creationMethods/initialValuesCreator';
import { validationCreator } from './creationMethods/validationSchemaCreator';

class CustomValidationForm extends Component {

    render() {
        const {
            config ,children, submit = () => {}
        } = this.props;

        return (
            <Form
                onSubmit={(event) => {
                    submit(event);
                }}
                initialValues={initialValuesCreator(config)}
                validate={values => validationCreator(values, config)}
                render={({handleSubmit}) => (
                    <form noValidate autoComplete={'off'} onSubmit={handleSubmit}>
                        {children}
                    </form>
                )}
            />
        )
    }
}

And here comes the question. Material ui stepper has handleNext function. Its my submit for each step. Each step will be some kind of form with validation. When user is on step1 and he press submit i want to show him input errors (something is required etc) and prevent jumping to next step. Step1 can have multiple small forms so all the form should be validated when handleNext is pressed.


问:
Reading Little Endian – LS Byte first for integer how to ignore the extra 0
I have been reading these byte by bytes from streams. Example I read this line like this.

```<code>int payloadLength = r.readUnsignedShort();
</code>```

The problem I have is that 2 bytes value is x3100 so it turns out to be 12544 but I suppose to only read as x31 which makes it to be only 49. How to ignore the extra 00.

答:
Right shift the value by 8 bits and then and it with 0xFF. Right shifting moves the bits 8 bits to the right. Any other bits would also be moved to the right so you need to mask those of by do an ANDing (&) with 0xFF to get rid of them.

```<code>
    int payloadLength = r.readUnsignedShort();

    payloadLength = (payloadLength >>> 8)& 0xFF;
    System.out.println(payLoadLength);

</code>```

You may also want to swap the two bytes.

```<code>    v = 0xa0b;
    v = swapBytes(v);
    System.out.println(Integer.toHexString(v)); // 0xb0a

    public static int swapBytes(int v) {
        return ((v << 8)&0xFF00) | ((v >> 8) & 0xFF);
    }

</code>```

Normally, for reading in just 16 bits you would not have to and it with 0xFF since the high order bits are 0's.  But I think it is a good practice and will prevent possible problems in the future.

Body:
I have been reading these byte by bytes from streams. Example I read this line like this.

int payloadLength = r.readUnsignedShort();

The problem I have is that 2 bytes value is x3100 so it turns out to be 12544 but I suppose to only read as x31 which makes it to be only 49. How to ignore the extra 00.

Body:
Right shift the value by 8 bits and then and it with 0xFF. Right shifting moves the bits 8 bits to the right. Any other bits would also be moved to the right so you need to mask those of by do an ANDing (&) with 0xFF to get rid of them.

    int payloadLength = r.readUnsignedShort();

    payloadLength = (payloadLength >>> 8)& 0xFF;
    System.out.println(payLoadLength);

You may also want to swap the two bytes.

    v = 0xa0b;
    v = swapBytes(v);
    System.out.println(Integer.toHexString(v)); // 0xb0a

    public static int swapBytes(int v) {
        return ((v << 8)&0xFF00) | ((v >> 8) & 0xFF);
    }

Normally, for reading in just 16 bits you would not have to and it with 0xFF since the high order bits are 0's.  But I think it is a good practice and will prevent possible problems in the future.


问:
Application is no longer saving and kCGErrorFailure errors in Console
I've had two users of my application write in with a very strange saving issue. After some time working with the application (it's a document based Cocoa application), the application stops allowing to save the document and the "Save" and "Save as…" main menu items are grayed out. Opening new documents apparently still works, however they come up with a blank canvas.
I asked both users to check Console.app and those are the lines they found:

First user:

```<code><Error>: kCGErrorFailure: _CGSBindWindowBacking: cannot map backing data shmem
<Error>: kCGErrorFailure: _CGSLockWindow: Unable to lock window
</code>```

Second user:

```<code>kCGErrorIllegalArgument: CGSShapeWindow
kCGErrorFailure: Set a breakpoint @ CGErrorBreakpoint() to catch errors as they are logged.
<Error>: kCGErrorIllegalArgument: CGSShapeWindow
<Error>: kCGErrorFailure: Set a breakpoint @ CGErrorBreakpoint() to catch errors as they are logged.
<Error>: kCGErrorIllegalArgument: CGSShapeWindow
kCGErrorIllegalArgument: CGSShapeWindow
</code>```

I tried my best to reproduce this issue, but without luck. I'm slowly running out of ideas what might cause this issue. Does anyone have any idea what is going on? Memory issue?

答: I sadly never really found a solution for this problem. Even had an Apple engineer look into this issue via a DTS. The work around that made this issue disappear was keeping images in a temp folder and only loading them into memory when needed. This greatly reduced my memory food print and made the issue go away.</p>

Body:
I've had two users of my application write in with a very strange saving issue. After some time working with the application (it's a document based Cocoa application), the application stops allowing to save the document and the "Save" and "Save as…" main menu items are grayed out. Opening new documents apparently still works, however they come up with a blank canvas.
I asked both users to check Console.app and those are the lines they found:

First user:

<Error>: kCGErrorFailure: _CGSBindWindowBacking: cannot map backing data shmem
<Error>: kCGErrorFailure: _CGSLockWindow: Unable to lock window

Second user:

kCGErrorIllegalArgument: CGSShapeWindow
kCGErrorFailure: Set a breakpoint @ CGErrorBreakpoint() to catch errors as they are logged.
<Error>: kCGErrorIllegalArgument: CGSShapeWindow
<Error>: kCGErrorFailure: Set a breakpoint @ CGErrorBreakpoint() to catch errors as they are logged.
<Error>: kCGErrorIllegalArgument: CGSShapeWindow
kCGErrorIllegalArgument: CGSShapeWindow

I tried my best to reproduce this issue, but without luck. I'm slowly running out of ideas what might cause this issue. Does anyone have any idea what is going on? Memory issue?


问:
Firebase realtime database cannot query with integer
I have sample of data like below

```<code>{
  "random_key 1" : {
    "id": 0,
    "text": "This is text"
  },
  "random_key 2" : {
    "id": 1,
    "text": "This is text"
  }
}
</code>```

I want to Query to get the node with 'id' equal to 1.

```<code>val database = FirebaseDatabase.getInstance().getReference()
database.orderByChild("id").equalTo(1)
</code>```

But this code return error because follow google document by this link: https://firebase.google.com/docs/reference/android/com/google/firebase/database/Query

The library is only support for Double, Boolean and String. I am really confuse now. How it possible?

答:
Yes, You are right.

The library is only support for Double, Boolean and String.

Also your query is right. As firebase consider 1 as double. So, your query should work. Check below:

```<code>DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
Query query = databaseReference.orderByChild("id").equalTo(1);
query.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        for(DataSnapshot childSnapshot: dataSnapshot.getChildren()) {

            String textValue = childSnapshot.child("text").getValue(String.class);

        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});
</code>```

Update for Kotlin: In Jave, int to double is automatically convert using assignment operator as lower type can be converted to higher type implicitly. This is also known as implicit type casting or type promotion.

But in Kotlin, there is nothing about implicit type casting. You have to do it yourself using toDouble(). Check below:

```<code>val databaseReference = FirebaseDatabase.getInstance().reference
val query = databaseReference.orderByChild("id").equalTo(1.toDouble())
query.addListenerForSingleValueEvent(object: ValueEventListener {
    override fun onCancelled(dataSnapshot: DatabaseError) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onDataChange(dataSnapshot: DataSnapshot) {
        dataSnapshot.children.forEach { childSnapshot->

            val textValue = childSnapshot.child("text").getValue(String::class.java)
        }
    }
})
</code>```

Body:
I have sample of data like below

{
  "random_key 1" : {
    "id": 0,
    "text": "This is text"
  },
  "random_key 2" : {
    "id": 1,
    "text": "This is text"
  }
}

I want to Query to get the node with 'id' equal to 1.

val database = FirebaseDatabase.getInstance().getReference()
database.orderByChild("id").equalTo(1)

But this code return error because follow google document by this link: https://firebase.google.com/docs/reference/android/com/google/firebase/database/Query

The library is only support for Double, Boolean and String. I am really confuse now. How it possible?

Body:
Yes, You are right.

The library is only support for Double, Boolean and String.

Also your query is right. As firebase consider 1 as double. So, your query should work. Check below:

DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
Query query = databaseReference.orderByChild("id").equalTo(1);
query.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        for(DataSnapshot childSnapshot: dataSnapshot.getChildren()) {

            String textValue = childSnapshot.child("text").getValue(String.class);

        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});

Update for Kotlin: In Jave, int to double is automatically convert using assignment operator as lower type can be converted to higher type implicitly. This is also known as implicit type casting or type promotion.

But in Kotlin, there is nothing about implicit type casting. You have to do it yourself using toDouble(). Check below:

val databaseReference = FirebaseDatabase.getInstance().reference
val query = databaseReference.orderByChild("id").equalTo(1.toDouble())
query.addListenerForSingleValueEvent(object: ValueEventListener {
    override fun onCancelled(dataSnapshot: DatabaseError) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onDataChange(dataSnapshot: DataSnapshot) {
        dataSnapshot.children.forEach { childSnapshot->

            val textValue = childSnapshot.child("text").getValue(String::class.java)
        }
    }
})


问:
How to remove all event handlers from an event
To create a new event handler on a control you can do this

```<code>c.Click += new EventHandler(mainFormButton_Click);
</code>```

or this

```<code>c.Click += mainFormButton_Click;
</code>```

and to remove an event handler you can do this

```<code>c.Click -= mainFormButton_Click;
</code>```

But how do you remove all event handlers from an event?

答:
removes all handlers for button:
  save.RemoveEvents();                </p>

```<code>public static class EventExtension
{
    public static void RemoveEvents<T>(this T target) where T : Control
    {
       var propInfo = typeof(T).GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance);
        var list = (EventHandlerList)propInfo.GetValue(target, null);
        list.Dispose();
    }
}
</code>```

OwnerDisplayName: Carrick

Body:
To create a new event handler on a control you can do this

c.Click += new EventHandler(mainFormButton_Click);

or this

c.Click += mainFormButton_Click;

and to remove an event handler you can do this

c.Click -= mainFormButton_Click;

But how do you remove all event handlers from an event?

Body:
removes all handlers for button:
  save.RemoveEvents();

public static class EventExtension
{
    public static void RemoveEvents<T>(this T target) where T : Control
    {
       var propInfo = typeof(T).GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance);
        var list = (EventHandlerList)propInfo.GetValue(target, null);
        list.Dispose();
    }
}


问:
Is it possible for the Scala compiler to understand overridden Abstract Types
Context:

I am attempting to make use of polymorphic sub-typing provided by Jackson, JsonSubTypes, in RESTful endpoint. There is some commonality between the various request bodies so I have:

```<code>abstract class A extends Translatable {
  val infoA: String
  val infoB: String
}

case class B(
  infoA: String,
  infoB: String,
  infoC: String,
  infoD: Int
) extends A {
  override type T = B
  def translate(
    requestInfo: String,
    request: B
  ): String = s"<$infoA,$infoB>:$infoC-${infoD.toString}"
}

case class C(
  infoA: String,
  infoB: String,
  infoC: Array[String]
) extends A {
  override type T = C
  def translate(
    requestInfo: String,
    request: C
  ): String = s"<$infoA,$infoB>:${infoC.mkString}"
}
</code>```

with the following trait so that without having to pattern match the incoming A request to either B or C:

```<code>trait Translatable {
  type T <: A
  def translate(
    requestInfo: String,
    request: T
  ): String
}
</code>```

the problem is when I compile it complains about type mismatch:

```<code>found: request.type (with underlying type com.program.A)
required: request.T
</code>```

I've tried a few things, to no avail, with only this seeming to get close:

implicit generalized type constraints

```<code>e.g.,
def translate[X](
  requestInfo: String,
  request: X
)(implicit ev: X <:< A) = ...
(modifying the case class impl. of ^ accordingly)
</code>```

but this leads to

Cannot prove that com.program.A <:< request.T

Any thoughts on how to do this? Or must I just suffer the pattern match? I say because the first code block works iff I pattern match and call the concrete impl. of translate for either B or C, but I'd prefer to just have an A type param and call translate on it. Is that possible?

EDIT: Adding instances where the above produces compilation errors:

```<code>class Program {
  def doWork(
    info: String,
    request: A
  ): String = {
    request.translate(
      info,
      request // compilation fails/complains about this param in both cases
    )
  }
}
</code>```

EDIT2: Adding qualification: I need the types to be overridden in the sub-types, B & C, so that in the translate func. I can call fields specific to B or C

答:
Try to add type parameter with refined upper bound</p>

```<code>def doWork[T0 <: A { type T = T0 }](
            info: String,
            request: T0
          ): String = {
  request.translate(
    info,
    request
  )
}

doWork("info1", B("infoA1", "infoB1", "infoC1", 1))//<infoA1,infoB1>:infoC1-1
doWork("info2", C("infoA2", "infoB2", Array("infoC21", "infoC22")))//<infoA2,infoB2>:infoC21infoC22
</code>```

Body:
Context:

I am attempting to make use of polymorphic sub-typing provided by Jackson, JsonSubTypes, in RESTful endpoint. There is some commonality between the various request bodies so I have:

abstract class A extends Translatable {
  val infoA: String
  val infoB: String
}

case class B(
  infoA: String,
  infoB: String,
  infoC: String,
  infoD: Int
) extends A {
  override type T = B
  def translate(
    requestInfo: String,
    request: B
  ): String = s"<$infoA,$infoB>:$infoC-${infoD.toString}"
}

case class C(
  infoA: String,
  infoB: String,
  infoC: Array[String]
) extends A {
  override type T = C
  def translate(
    requestInfo: String,
    request: C
  ): String = s"<$infoA,$infoB>:${infoC.mkString}"
}

with the following trait so that without having to pattern match the incoming A request to either B or C:

trait Translatable {
  type T <: A
  def translate(
    requestInfo: String,
    request: T
  ): String
}

the problem is when I compile it complains about type mismatch:

found: request.type (with underlying type com.program.A)
required: request.T

I've tried a few things, to no avail, with only this seeming to get close:

implicit generalized type constraints

e.g.,
def translate[X](
  requestInfo: String,
  request: X
)(implicit ev: X <:< A) = ...
(modifying the case class impl. of ^ accordingly)

but this leads to

Cannot prove that com.program.A <:< request.T

Any thoughts on how to do this? Or must I just suffer the pattern match? I say because the first code block works iff I pattern match and call the concrete impl. of translate for either B or C, but I'd prefer to just have an A type param and call translate on it. Is that possible?

EDIT: Adding instances where the above produces compilation errors:

class Program {
  def doWork(
    info: String,
    request: A
  ): String = {
    request.translate(
      info,
      request // compilation fails/complains about this param in both cases
    )
  }
}

EDIT2: Adding qualification: I need the types to be overridden in the sub-types, B & C, so that in the translate func. I can call fields specific to B or C

Body:
Try to add type parameter with refined upper bound

def doWork[T0 <: A { type T = T0 }](
            info: String,
            request: T0
          ): String = {
  request.translate(
    info,
    request
  )
}

doWork("info1", B("infoA1", "infoB1", "infoC1", 1))//<infoA1,infoB1>:infoC1-1
doWork("info2", C("infoA2", "infoB2", Array("infoC21", "infoC22")))//<infoA2,infoB2>:infoC21infoC22


问:
How to add a character to the beginning of every word in a string in javascript?
I have a string for example

```<code>some_string = "Hello there! How are you?"
</code>```

I want to add a character to the beginning of every word such that the final string looks like

```<code>some_string = "#0Hello #0there! #0How #0are #0you?"
</code>```

So I did something like this

```<code>temp_array = []

some_string.split(" ").forEach(function(item, index) {
    temp_array.push("#0" + item)

})

console.log(temp_array.join(" "))
</code>```

Is there any one liner to do this operation without creating an intermediary temp_array?

答:
The simplest solution is regex. There is already regex soln give. However can be simplified.

var some_string = "Hello there! How are you?"

console.log(some_string.replace(/[^\s]+/g, m => `#0${m}`))```

Body:
I have a string for example

some_string = "Hello there! How are you?"

I want to add a character to the beginning of every word such that the final string looks like

some_string = "#0Hello #0there! #0How #0are #0you?"

So I did something like this

temp_array = []

some_string.split(" ").forEach(function(item, index) {
    temp_array.push("#0" + item)

})

console.log(temp_array.join(" "))

Is there any one liner to do this operation without creating an intermediary temp_array?


问:
How to return a variable using another one Python
After working a lot with swift, I got used to the following syntax:

```<code>private var __privateVar = 100 // Not accessible from outside the Class
public var public_var: Int = {
    return __privateVar // Returns __privateVar, and is get-only variable
}
</code>```

Is there a way to reproduce this in python 3?
Thanks a lot

答:
Python doesn't even have the concept of access modifiers - so if you mean you want a private variable, that's not something you can do. You can, however, use a read-only property:

```<code>class Test:
    def __init__(self):
        self._var = 'some string'

    @property
    def var(self):
        return self._var
</code>```

Then, use it as such:

```<code>obj = Test()
obj.var # works
obj.var = 'whatever' # raises AttributeError
obj._var = 'whatever' # still works
</code>```

It's noteworthy that you can somewhat emulate the behavior of a private variable by prefixing your variable with a double underscore (such as in __var), which introduces name mangling if used in a class scope. This is not foolproof, though, and you can always get around it if you really want to. Generally, however, Python developers know not to assign to variables starting in one or two underscores.

Body:
After working a lot with swift, I got used to the following syntax:

private var __privateVar = 100 // Not accessible from outside the Class
public var public_var: Int = {
    return __privateVar // Returns __privateVar, and is get-only variable
}

Is there a way to reproduce this in python 3?
Thanks a lot

Body:
Python doesn't even have the concept of access modifiers - so if you mean you want a private variable, that's not something you can do. You can, however, use a read-only property:

class Test:
    def __init__(self):
        self._var = 'some string'

    @property
    def var(self):
        return self._var

Then, use it as such:

obj = Test()
obj.var # works
obj.var = 'whatever' # raises AttributeError
obj._var = 'whatever' # still works

It's noteworthy that you can somewhat emulate the behavior of a private variable by prefixing your variable with a double underscore (such as in __var), which introduces name mangling if used in a class scope. This is not foolproof, though, and you can always get around it if you really want to. Generally, however, Python developers know not to assign to variables starting in one or two underscores.


问:
How can I compute the area under a histogram after a certain value?
I am using this to compute the area under the whole histogram. However I cannot find resources that tell how to calculate the area under the histogram after a value or within a particular interval. Any idea regarding this please?
x is my data here and values are the probabilities of occurrence.</p>

```<code>area = sum(np.diff(bins)*values)
</code>```

答:
```<code>area = sum(np.diff(bins)[0]*values[start:])
</code>```

np.diff(bins) helps you find portions of x, which is same along x-axis. Therefor, you can take first element.

Body:
I am using this to compute the area under the whole histogram. However I cannot find resources that tell how to calculate the area under the histogram after a value or within a particular interval. Any idea regarding this please?
x is my data here and values are the probabilities of occurrence.

area = sum(np.diff(bins)*values)

Body:
area = sum(np.diff(bins)[0]*values[start:])

np.diff(bins) helps you find portions of x, which is same along x-axis. Therefor, you can take first element.


问:
Is there a way to highlight a button option displayed through Choice using PromptOptions in MS Chat BOT created in C# and SDKV4?
I am creating a chatBot using microsoft Bot framework using SDKV4 in C#. The BOT has multiple waterfall dialogs.

In this one dialog class shows few choice options in form of buttons using Prompt Options.I want to know whether or is there a way to highlight one(only one) of the buttons displayed in different color.

If we observe, in general the choice buttons are displayed in White(background of button) and Blue(blue text and border of button) combination.

So is there a way to change the white background color? Either only color or making the button to give blinking effect or flashing effect based on a certain conditions.

Let's say there is a bool flag ,if it is true i want to display one of the option in other color or as is if it is false.

Code:

```<code> return await stepContext.PromptAsync(
                        "choicePrompt",
                        new PromptOptions
                        {
                            Prompt = stepContext.Context.Activity.CreateReply("Please click/choose any one from the following: "),
                            Choices = new[] { new Choice { Value = "Option0" }, new Choice { Value = "Option1" }, new Choice { Value = "Option2" }, new Choice { Value = "Option3" }, new Choice { Value = "Option4" }, new Choice { Value = "Option5" }}.ToList(),
                            RetryPrompt = stepContext.Context.Activity.CreateReply("Sorry, I did not understand that. Please choose any one from the options displayed below: "),
                        });
</code>```

I want the Option2 to be displayed in different color based on Bool flag as tried to explain above.

Is this possible? or this is a wrong expectation and it cannot be done?

if it is possible can anyone please provide me the detailed steps to achieve this. Please note that i am a bit new to coding hence i would humbly request to provide detailed steps if this is behaviour is achievable.

Thanks in Advance

Regards

ChaitanyaNG

答:
There's no built-in way to do this, no. The closest thing that PromptOptions offers is the Style property, but even that is only for setting different ListStyles, none of which offer any color customization.

If you're only using Web Chat, there's likely some CSS customization I can help you with. But if you're using any other channel, you're pretty much stuck with how the channel decides to render the choices.

Alternatively, instead of choices, you could send small Adaptive Cards and set a different background image for the first one. Note, however, that the channel doesn't have to display the background image (although it likely will). Non-Microsoft channels (Slack, Facebook, etc) also don't work very well with using Adaptive Cards as inputs.

To answer further comments, I was able to find the appropriate CSS selector for Choices. This may differ in your version of Web Chat, but I used:

.css-1wegtiu > ul > li:first-child > .css-y5o52s > button {
    background: red
}
```

and this resulted in:

Body:
I am creating a chatBot using microsoft Bot framework using SDKV4 in C#. The BOT has multiple waterfall dialogs.

In this one dialog class shows few choice options in form of buttons using Prompt Options.I want to know whether or is there a way to highlight one(only one) of the buttons displayed in different color.

If we observe, in general the choice buttons are displayed in White(background of button) and Blue(blue text and border of button) combination.

So is there a way to change the white background color? Either only color or making the button to give blinking effect or flashing effect based on a certain conditions.

Let's say there is a bool flag ,if it is true i want to display one of the option in other color or as is if it is false.

Code:

 return await stepContext.PromptAsync(
                        "choicePrompt",
                        new PromptOptions
                        {
                            Prompt = stepContext.Context.Activity.CreateReply("Please click/choose any one from the following: "),
                            Choices = new[] { new Choice { Value = "Option0" }, new Choice { Value = "Option1" }, new Choice { Value = "Option2" }, new Choice { Value = "Option3" }, new Choice { Value = "Option4" }, new Choice { Value = "Option5" }}.ToList(),
                            RetryPrompt = stepContext.Context.Activity.CreateReply("Sorry, I did not understand that. Please choose any one from the options displayed below: "),
                        });

I want the Option2 to be displayed in different color based on Bool flag as tried to explain above.

Is this possible? or this is a wrong expectation and it cannot be done?

if it is possible can anyone please provide me the detailed steps to achieve this. Please note that i am a bit new to coding hence i would humbly request to provide detailed steps if this is behaviour is achievable.

Thanks in Advance

Regards

ChaitanyaNG

Body:
There's no built-in way to do this, no. The closest thing that PromptOptions offers is the Style property, but even that is only for setting different ListStyles, none of which offer any color customization.

If you're only using Web Chat, there's likely some CSS customization I can help you with. But if you're using any other channel, you're pretty much stuck with how the channel decides to render the choices.

Alternatively, instead of choices, you could send small Adaptive Cards and set a different background image for the first one. Note, however, that the channel doesn't have to display the background image (although it likely will). Non-Microsoft channels (Slack, Facebook, etc) also don't work very well with using Adaptive Cards as inputs.

To answer further comments, I was able to find the appropriate CSS selector for Choices. This may differ in your version of Web Chat, but I used:

.css-1wegtiu > ul > li:first-child > .css-y5o52s > button {
    background: red
}

and this resulted in: