问:
how to serialize / deserialize List<class object> with protobuf?
I want to serialize List<ArchiveData> but it nearly always fail. Protobuff throw following exception:

Invalid wire-type; this usually means you have over-written a file
  without truncating or setting the length; see
  Using Protobuf-net, I suddenly got an exception about an unknown wire-type

I have read the post but still can not find a solution. How can i serialize and deserialize this?

My Class and Struct:

```<code>[Serializable, ProtoContract(Name = @"Archive"), ProtoInclude(1, typeof(List<ArchiveData>))]
public partial class Archive : IExtensible
{
    [ProtoMember(1, IsRequired = true, OverwriteList = true, Name = @"data", DataFormat = DataFormat.Default)]
    public List<ArchiveData> data { get; set; }

    public Archive()
    {
        data = new List<ArchiveForm.ArchiveData>();
    }

    private IExtension extensionObject;
    IExtension IExtensible.GetExtensionObject(bool createIfMissing)
    {
        return Extensible.GetExtensionObject(ref extensionObject, createIfMissing);
    }
}

public struct ArchiveData
{
    [ProtoMember(1, IsRequired = false, OverwriteList = true, Name = @"sourcefolder", DataFormat = DataFormat.Default)]
    [global::System.ComponentModel.DefaultValue("")]
    public string sourcefolder { get; set; }

    [ProtoMember(2, IsRequired = false, OverwriteList = true, Name = @"destinationfolder", DataFormat = DataFormat.Default)]
    [global::System.ComponentModel.DefaultValue("")]
    public string destinationfolder { get; set; }

    [ProtoMember(3, IsRequired = false, OverwriteList = true, Name = @"period", DataFormat = DataFormat.FixedSize)]
    [global::System.ComponentModel.DefaultValue((int)0)]
    public int period { get; set; }

    public ArchiveData(string sfolder = "", string dfolder = "", int priod = 0)
    {
        sourcefolder = sfolder;
        destinationfolder = dfolder;
        period = priod;
    }
}
</code>```

I serialize that with following method:

```<code>public static void Refresh(ref Archive arc)
{
    if (File.Exists(probuffile))
    {
        using (var fs = File.OpenRead(probuffile))
        {
            arc = Serializer.Deserialize<Archive>(fs);
        }
    }
}
</code>```

And i deserialize that with following method:

```<code>public static void Update(Archive arc)
{
    using (var fs = File.Create(probuffile))
    {
        Serializer.Serialize<Archive>(fs, arc);
        fs.SetLength(fs.Position);
    }
}
</code>```

And i use it:

```<code>Archive archive = new Archive();
//Add some ArchiveData.
Refresh(ref archive);
</code>```

------------------------------Edit------------------------------

This section has been added for more information. When I use SerializeWithLengthPrefix / DeserializeWithLengthPrefix function like following code, it work properly every time for the first class that i use the Deserialize function. But it return null for the second class that i use the Deserialize function.

```<code>[Serializable, ProtoContract(Name = @"OptionData")]
public class OptionData : IExtensible
{
    [ProtoMember(1, IsRequired = false, OverwriteList = true, Name = @"StartWithWindows", DataFormat = DataFormat.Default)]
    [DefaultValue(false)]
    public bool StartWithWindows { get; set; }

    [ProtoMember(2, IsRequired = false, OverwriteList = true, Name = @"AutoBackup", DataFormat = DataFormat.Default)]
    [DefaultValue(false)]
    public bool AutoBackup { get; set; }

    [ProtoMember(3, IsRequired = false, OverwriteList = true, Name = @"Speed", DataFormat = DataFormat.FixedSize)]
    [DefaultValue((int)0)]
    public int Speed { get; set; }

    private IExtension extensionObject;
    IExtension IExtensible.GetExtensionObject(bool createIfMissing)
    {
        return Extensible.GetExtensionObject(ref extensionObject, createIfMissing);
    }
}

public static void Update(OptionData op)
{
    using (var fs = File.Create(probuffile))
    {
        Serializer.SerializeWithLengthPrefix(fs, op, PrefixStyle.Base128, 3);
    }
}

public static void Update(Archive arc)
{
    using (var fs = File.Create(probuffile))
    {
        Serializer.SerializeWithLengthPrefix<Archive>(fs, arc, PrefixStyle.Base128, 2);
    }
}

public static void Refresh(ref OptionData op)
{
    if (File.Exists(probuffile))
    {
        using (var fs = File.OpenRead(probuffile))
        {
            op = Serializer.DeserializeWithLengthPrefix<OptionData>(fs, PrefixStyle.Base128, 3);
        }
    }
}

public static void Refresh(ref Archive arc)
{
    if (File.Exists(probuffile))
    {
        using (var fs = File.OpenRead(probuffile))
        {
            arc = Serializer.DeserializeWithLengthPrefix<Archive>(fs, PrefixStyle.Base128, 2);
        }
    }
}
</code>```

答:
I'd be happy to help, but I'm struggling to get it to fail. You say "but it nearly always fail", but the following runnable console exer works fine and writes a large range of data of various sizes:

```<code>using ProtoBuf;
using System;
using System.Collections.Generic;
using System.IO;
static class P
{
    static void Main()
    {
        var random = new Random(12345);
        // start with 100
        var archive = CreateData(random, 100);
        Update(archive);
        Refresh(ref archive);

        // make it bigger
        archive = CreateData(random, 200);
        Update(archive);
        Refresh(ref archive);

        // make it smaller
        archive = CreateData(random, 50);
        Update(archive);
        Refresh(ref archive);

        // go wild
        for (int i = 0; i < 1000; i++)
        {
            archive = CreateData(random, random.Next(0, 500));
            Update(archive);
            Refresh(ref archive);
        }

    }
    static Archive CreateData(Random random, int dataCount)
    {
        var archive = new Archive();
        var data = archive.data;
        for (int i = 0; i < dataCount; i++)
        {
            data.Add(new ArchiveData
            {
                period = random.Next(10000),
                sourcefolder = CreateString(random, 50),
                destinationfolder = CreateString(random, 50)
            });
        }
        return archive;
    }

    private static unsafe string CreateString(Random random, int maxLength)
    {
        const string Alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
        int len = random.Next(maxLength + 1);
        char* chars = stackalloc char[len];
        for (int i = 0; i < len; i++)
        {
            chars[i] = Alphabet[random.Next(Alphabet.Length)];
        }
        return new string(chars, 0, len);
    }

    static string probuffile = "my.bin";
    public static void Refresh(ref Archive arc)
    {
        if (File.Exists(probuffile))
        {
            using (var fs = File.OpenRead(probuffile))
            {
                arc = Serializer.Deserialize<Archive>(fs);
                Console.WriteLine("Read: {0} items, {1} bytes", arc.data.Count, fs.Length);
            }
        }
    }

    public static void Update(Archive arc)
    {
        using (var fs = File.Create(probuffile))
        {
            Serializer.Serialize<Archive>(fs, arc);
            fs.SetLength(fs.Position);
            Console.WriteLine("Wrote: {0} items, {1} bytes", arc.data.Count, fs.Length);
        }
    }
}

[Serializable, ProtoContract(Name = @"Archive"), ProtoInclude(1, typeof(List<ArchiveData>))]
public partial class Archive : IExtensible
{
    [ProtoMember(1, IsRequired = true, OverwriteList = true, Name = @"data", DataFormat = DataFormat.Default)]
    public List<ArchiveData> data { get; set; }

    public Archive()
    {
        data = new List<ArchiveData>();
    }

    private IExtension extensionObject;
    IExtension IExtensible.GetExtensionObject(bool createIfMissing)
    {
        return Extensible.GetExtensionObject(ref extensionObject, createIfMissing);
    }
}
[ProtoContract]
public struct ArchiveData
{
    [ProtoMember(1, IsRequired = false, OverwriteList = true, Name = @"sourcefolder", DataFormat = DataFormat.Default)]
    [global::System.ComponentModel.DefaultValue("")]
    public string sourcefolder { get; set; }

    [ProtoMember(2, IsRequired = false, OverwriteList = true, Name = @"destinationfolder", DataFormat = DataFormat.Default)]
    [global::System.ComponentModel.DefaultValue("")]
    public string destinationfolder { get; set; }

    [ProtoMember(3, IsRequired = false, OverwriteList = true, Name = @"period", DataFormat = DataFormat.FixedSize)]
    [global::System.ComponentModel.DefaultValue((int)0)]
    public int period { get; set; }

    public ArchiveData(string sfolder = "", string dfolder = "", int priod = 0)
    {
        sourcefolder = sfolder;
        destinationfolder = dfolder;
        period = priod;
    }
}
</code>```

I'm guessing that whatever the difference is between your real code and the example above : is also the cause of the problem. If you help find what is different, I'd be more than happy to help however I reasonably can.

As a minor note: you don't actually need to set the length when using Create, since that is explicitly "throw away any existing data". The main time you need to worry about the length is when people use OpenWrite to write over an existing file, and then write less data than was already there. But there isn't a problem with explicitly setting the length after Create

Body:
I want to serialize List<ArchiveData> but it nearly always fail. Protobuff throw following exception:

Invalid wire-type; this usually means you have over-written a file
  without truncating or setting the length; see
  Using Protobuf-net, I suddenly got an exception about an unknown wire-type

I have read the post but still can not find a solution. How can i serialize and deserialize this?

My Class and Struct:

[Serializable, ProtoContract(Name = @"Archive"), ProtoInclude(1, typeof(List<ArchiveData>))]
public partial class Archive : IExtensible
{
    [ProtoMember(1, IsRequired = true, OverwriteList = true, Name = @"data", DataFormat = DataFormat.Default)]
    public List<ArchiveData> data { get; set; }

    public Archive()
    {
        data = new List<ArchiveForm.ArchiveData>();
    }

    private IExtension extensionObject;
    IExtension IExtensible.GetExtensionObject(bool createIfMissing)
    {
        return Extensible.GetExtensionObject(ref extensionObject, createIfMissing);
    }
}

public struct ArchiveData
{
    [ProtoMember(1, IsRequired = false, OverwriteList = true, Name = @"sourcefolder", DataFormat = DataFormat.Default)]
    [global::System.ComponentModel.DefaultValue("")]
    public string sourcefolder { get; set; }

    [ProtoMember(2, IsRequired = false, OverwriteList = true, Name = @"destinationfolder", DataFormat = DataFormat.Default)]
    [global::System.ComponentModel.DefaultValue("")]
    public string destinationfolder { get; set; }

    [ProtoMember(3, IsRequired = false, OverwriteList = true, Name = @"period", DataFormat = DataFormat.FixedSize)]
    [global::System.ComponentModel.DefaultValue((int)0)]
    public int period { get; set; }

    public ArchiveData(string sfolder = "", string dfolder = "", int priod = 0)
    {
        sourcefolder = sfolder;
        destinationfolder = dfolder;
        period = priod;
    }
}

I serialize that with following method:

public static void Refresh(ref Archive arc)
{
    if (File.Exists(probuffile))
    {
        using (var fs = File.OpenRead(probuffile))
        {
            arc = Serializer.Deserialize<Archive>(fs);
        }
    }
}

And i deserialize that with following method:

public static void Update(Archive arc)
{
    using (var fs = File.Create(probuffile))
    {
        Serializer.Serialize<Archive>(fs, arc);
        fs.SetLength(fs.Position);
    }
}

And i use it:

Archive archive = new Archive();
//Add some ArchiveData.
Refresh(ref archive);

------------------------------Edit------------------------------

This section has been added for more information. When I use SerializeWithLengthPrefix / DeserializeWithLengthPrefix function like following code, it work properly every time for the first class that i use the Deserialize function. But it return null for the second class that i use the Deserialize function.

[Serializable, ProtoContract(Name = @"OptionData")]
public class OptionData : IExtensible
{
    [ProtoMember(1, IsRequired = false, OverwriteList = true, Name = @"StartWithWindows", DataFormat = DataFormat.Default)]
    [DefaultValue(false)]
    public bool StartWithWindows { get; set; }

    [ProtoMember(2, IsRequired = false, OverwriteList = true, Name = @"AutoBackup", DataFormat = DataFormat.Default)]
    [DefaultValue(false)]
    public bool AutoBackup { get; set; }

    [ProtoMember(3, IsRequired = false, OverwriteList = true, Name = @"Speed", DataFormat = DataFormat.FixedSize)]
    [DefaultValue((int)0)]
    public int Speed { get; set; }

    private IExtension extensionObject;
    IExtension IExtensible.GetExtensionObject(bool createIfMissing)
    {
        return Extensible.GetExtensionObject(ref extensionObject, createIfMissing);
    }
}

public static void Update(OptionData op)
{
    using (var fs = File.Create(probuffile))
    {
        Serializer.SerializeWithLengthPrefix(fs, op, PrefixStyle.Base128, 3);
    }
}

public static void Update(Archive arc)
{
    using (var fs = File.Create(probuffile))
    {
        Serializer.SerializeWithLengthPrefix<Archive>(fs, arc, PrefixStyle.Base128, 2);
    }
}

public static void Refresh(ref OptionData op)
{
    if (File.Exists(probuffile))
    {
        using (var fs = File.OpenRead(probuffile))
        {
            op = Serializer.DeserializeWithLengthPrefix<OptionData>(fs, PrefixStyle.Base128, 3);
        }
    }
}

public static void Refresh(ref Archive arc)
{
    if (File.Exists(probuffile))
    {
        using (var fs = File.OpenRead(probuffile))
        {
            arc = Serializer.DeserializeWithLengthPrefix<Archive>(fs, PrefixStyle.Base128, 2);
        }
    }
}

Body:
I'd be happy to help, but I'm struggling to get it to fail. You say "but it nearly always fail", but the following runnable console exer works fine and writes a large range of data of various sizes:

using ProtoBuf;
using System;
using System.Collections.Generic;
using System.IO;
static class P
{
    static void Main()
    {
        var random = new Random(12345);
        // start with 100
        var archive = CreateData(random, 100);
        Update(archive);
        Refresh(ref archive);

        // make it bigger
        archive = CreateData(random, 200);
        Update(archive);
        Refresh(ref archive);

        // make it smaller
        archive = CreateData(random, 50);
        Update(archive);
        Refresh(ref archive);

        // go wild
        for (int i = 0; i < 1000; i++)
        {
            archive = CreateData(random, random.Next(0, 500));
            Update(archive);
            Refresh(ref archive);
        }

    }
    static Archive CreateData(Random random, int dataCount)
    {
        var archive = new Archive();
        var data = archive.data;
        for (int i = 0; i < dataCount; i++)
        {
            data.Add(new ArchiveData
            {
                period = random.Next(10000),
                sourcefolder = CreateString(random, 50),
                destinationfolder = CreateString(random, 50)
            });
        }
        return archive;
    }

    private static unsafe string CreateString(Random random, int maxLength)
    {
        const string Alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
        int len = random.Next(maxLength + 1);
        char* chars = stackalloc char[len];
        for (int i = 0; i < len; i++)
        {
            chars[i] = Alphabet[random.Next(Alphabet.Length)];
        }
        return new string(chars, 0, len);
    }

    static string probuffile = "my.bin";
    public static void Refresh(ref Archive arc)
    {
        if (File.Exists(probuffile))
        {
            using (var fs = File.OpenRead(probuffile))
            {
                arc = Serializer.Deserialize<Archive>(fs);
                Console.WriteLine("Read: {0} items, {1} bytes", arc.data.Count, fs.Length);
            }
        }
    }

    public static void Update(Archive arc)
    {
        using (var fs = File.Create(probuffile))
        {
            Serializer.Serialize<Archive>(fs, arc);
            fs.SetLength(fs.Position);
            Console.WriteLine("Wrote: {0} items, {1} bytes", arc.data.Count, fs.Length);
        }
    }
}

[Serializable, ProtoContract(Name = @"Archive"), ProtoInclude(1, typeof(List<ArchiveData>))]
public partial class Archive : IExtensible
{
    [ProtoMember(1, IsRequired = true, OverwriteList = true, Name = @"data", DataFormat = DataFormat.Default)]
    public List<ArchiveData> data { get; set; }

    public Archive()
    {
        data = new List<ArchiveData>();
    }

    private IExtension extensionObject;
    IExtension IExtensible.GetExtensionObject(bool createIfMissing)
    {
        return Extensible.GetExtensionObject(ref extensionObject, createIfMissing);
    }
}
[ProtoContract]
public struct ArchiveData
{
    [ProtoMember(1, IsRequired = false, OverwriteList = true, Name = @"sourcefolder", DataFormat = DataFormat.Default)]
    [global::System.ComponentModel.DefaultValue("")]
    public string sourcefolder { get; set; }

    [ProtoMember(2, IsRequired = false, OverwriteList = true, Name = @"destinationfolder", DataFormat = DataFormat.Default)]
    [global::System.ComponentModel.DefaultValue("")]
    public string destinationfolder { get; set; }

    [ProtoMember(3, IsRequired = false, OverwriteList = true, Name = @"period", DataFormat = DataFormat.FixedSize)]
    [global::System.ComponentModel.DefaultValue((int)0)]
    public int period { get; set; }

    public ArchiveData(string sfolder = "", string dfolder = "", int priod = 0)
    {
        sourcefolder = sfolder;
        destinationfolder = dfolder;
        period = priod;
    }
}

I'm guessing that whatever the difference is between your real code and the example above : is also the cause of the problem. If you help find what is different, I'd be more than happy to help however I reasonably can.

As a minor note: you don't actually need to set the length when using Create, since that is explicitly "throw away any existing data". The main time you need to worry about the length is when people use OpenWrite to write over an existing file, and then write less data than was already there. But there isn't a problem with explicitly setting the length after Create


来源: stackexchange

问:
Getting nth tag A in a table
I am very new to Powershell and not expert in HTML/JS

I have this table in a webpage, note that it's not the only table on the page nor these are the only A tags - there are many a tags and tables before it.

```<code><table id="row" class="simple">
   <thead>
      <tr>
         <th></th>
         <th class="centerjustify">File Name</th>
         <th class="centerjustify">File ID</th>
         <th class="datetime">Creation Date</th>
         <th class="datetime">Upload Date</th>
         <th class="centerjustify">Processing Status</th>
         <th class="centerjustify">Exceptions</th>
         <th class="centerjustify">Unprocessed Count</th>
         <th class="centerjustify">Discarded Count</th>
         <th class="centerjustify">Rejected Count</th>
         <th class="centerjustify">Void Count</th>
         <th class="centerjustify">PO Total Count</th>
         <th class="centerjustify">PO Total Amount</th>
         <th class="centerjustify">CM Total Count</th>
         <th class="centerjustify">CM Total Amount</th>
         <th class="centerjustify">PO Processed Count</th>
         <th class="centerjustify">PO Processed Amount</th>
         <th class="centerjustify">CM Processed Count</th>
         <th class="centerjustify">CM Processed Amount</th>
         <th class="centerjustify">Counts At Upload</th>
      </tr>
   </thead>
   <tbody>
      <tr class="odd">
         <td><input type="radio" disabled="disabled" name="checkedValue" value="12047" /></td>
         <td class="leftjustify textColorBlack">
            <a href="loadConfirmationDetails.htm?fId=12047">520100000000000_520100000000000_20170327_01.txt</a>
         </td>
         <td class="centerjustify textColorBlack">1</td>
         <td class="datetime textColorBlack">Mar 27, 2017 0:00</td>
         <td class="datetime textColorBlack">Mar 27, 2017 10:33:24 PM +03:00</td>
         <td class="centerjustify textColorBlack">
</code>```

What I want is to browse automatically to a href="loadConfirmationDetails.htm?fId=12047  but the fId part is dynamic so I can't use this href as static, but the cell location of this href is always the same; the static part of it is  href="loadConfirmationDetails.htm?fId

This A tag (that contains the wanted href) is the 105th a on the page, I was thinking if I can use some cellindex in PS but I didn't find anything on it!

I've tried this but didn't work:

```<code>$ParsedHTML=(Invoke-WebRequest "https://uat.website.com/xxx/community/loadConfirmations.htm?initial=false&action=search").ParsedHtml | Where-Object {$_.TagName -eq 'a' } | Select-Object InnerHtml -First 105
$ParsedHTML.click()
</code>```

Probably because this select all 105 first A tag but I want only to click on the 105th.

I wonder also I can use $ie.Document.IHTMLDocument3_getElementById("row") piped with something  like get child and where picking its first A tag or something - but I can't figure how.

答:
If you know it's always the 105th "A" Link on the page then you should be able to get it from the .Links property as follows:

```<code>$Web = Invoke-WebRequest "https://uat.website.com/xxx/community/loadConfirmations.htm?initial=false&action=search"
$Link = $Web.Links[104].href
</code>```

This is 104 because the array starts at 0.

If it's the 105th element (e.g of all HTML elements) on the page then you should be able to access it via:

```<code>$Web.AllElements[104]
</code>```

Also you should beware that the Links collection does not have a "Click" method as you are trying to use, but it seems this is possible via an Internet Explorer COM object as described here:

Click a hyperlink using powershell

FYI I also expanded my answer on your previous question with a couple of other options on how to get to the element on the page that you want: https://stackoverflow.com/a/43057670/2796058

ContentLicense: CC BY-SA 3.0

Title: Getting nth tag A in a table

Body:
I am very new to Powershell and not expert in HTML/JS

I have this table in a webpage, note that it's not the only table on the page nor these are the only A tags - there are many a tags and tables before it.

         File Name
         File ID
         Creation Date
         Upload Date
         Processing Status
         Exceptions
         Unprocessed Count
         Discarded Count
         Rejected Count
         Void Count
         PO Total Count
         PO Total Amount
         CM Total Count
         CM Total Amount
         PO Processed Count
         PO Processed Amount
         CM Processed Count
         CM Processed Amount
         Counts At Upload

         <input type="radio" disabled="disabled" name="checkedValue" value="12047" />

            520100000000000_520100000000000_20170327_01.txt

         1
         Mar 27, 2017 0:00
         Mar 27, 2017 10:33:24 PM +03:00

What I want is to browse automatically to a href="loadConfirmationDetails.htm?fId=12047  but the fId part is dynamic so I can't use this href as static, but the cell location of this href is always the same; the static part of it is  href="loadConfirmationDetails.htm?fId

This A tag (that contains the wanted href) is the 105th a on the page, I was thinking if I can use some cellindex in PS but I didn't find anything on it!

I've tried this but didn't work:

$ParsedHTML=(Invoke-WebRequest "https://uat.website.com/xxx/community/loadConfirmations.htm?initial=false&action=search").ParsedHtml | Where-Object {$_.TagName -eq 'a' } | Select-Object InnerHtml -First 105
$ParsedHTML.click()

Probably because this select all 105 first A tag but I want only to click on the 105th.

I wonder also I can use $ie.Document.IHTMLDocument3_getElementById("row") piped with something  like get child and where picking its first A tag or something - but I can't figure how.

Body:
If you know it's always the 105th "A" Link on the page then you should be able to get it from the .Links property as follows:

$Web = Invoke-WebRequest "https://uat.website.com/xxx/community/loadConfirmations.htm?initial=false&action=search"
$Link = $Web.Links[104].href

This is 104 because the array starts at 0.

If it's the 105th element (e.g of all HTML elements) on the page then you should be able to access it via:

$Web.AllElements[104]

Also you should beware that the Links collection does not have a "Click" method as you are trying to use, but it seems this is possible via an Internet Explorer COM object as described here:

Click a hyperlink using powershell

FYI I also expanded my answer on your previous question with a couple of other options on how to get to the element on the page that you want: https://stackoverflow.com/a/43057670/2796058


问:
Searching in SQL field WHERE LIKE %$user_id%
I have a small problem.

I have my table as follows:

tbl_groups

```<code>id (int) | teacher_id (int) | student_ids (text)
------------------------------------------------
1        | 14               | 2015,2016,2017
2        | 35               | 15,16,17
3        | 14               | 631
</code>```

student_ids will get filled by a PHP array using implode().

However, when I execute the following query to search the group's id by a student id:

```<code>SELECT `id` FROM `tbl_groups` WHERE `student_ids` LIKE '%15%'
</code>```

I get row 1 and 2 returned. This happens because student_ids "15" will be searched for, and "2015" contains "15" so it will also return it.

How can I prevent this?

Body:
I have a small problem.

I have my table as follows:

tbl_groups

id (int) | teacher_id (int) | student_ids (text)
------------------------------------------------
1        | 14               | 2015,2016,2017
2        | 35               | 15,16,17
3        | 14               | 631

student_ids will get filled by a PHP array using implode().

However, when I execute the following query to search the group's id by a student id:

SELECT `id` FROM `tbl_groups` WHERE `student_ids` LIKE '%15%'

I get row 1 and 2 returned. This happens because student_ids "15" will be searched for, and "2015" contains "15" so it will also return it.

How can I prevent this?

Body:
You can use FIND_in_SET like this:. it will return a value > 0 if it in the set.

SELECT `id` FROM `tbl_groups`
WHERE FIND_IN_SET('15',`student_ids`);

sample

mysql> SELECT  FIND_IN_SET('15','15,16,17');
+------------------------------+
| FIND_IN_SET('15','15,16,17') |
+------------------------------+
|                            1 |
+------------------------------+
1 row in set (0,00 sec)

mysql> SELECT  FIND_IN_SET('1','15,16,17');
+-----------------------------+
| FIND_IN_SET('1','15,16,17') |
+-----------------------------+
|                           0 |
+-----------------------------+
1 row in set (0,00 sec)

mysql> SELECT  FIND_IN_SET('17','15,16,17');
+------------------------------+
| FIND_IN_SET('17','15,16,17') |
+------------------------------+
|                            3 |
+------------------------------+
1 row in set (0,00 sec)

mysql>


问:
Is it possible to make a css declaration override a style set in the element's style property?
Is it possible to make a css declaration override a style set in the element's style property?

eg:

```<code><div class="root"><p style="font-size:13px;">hello</p></div>
</code>```

Is there someway I can override the font size with css?

I already tried .root p{font-size:16px !important;}

The reason I want to do this is that I am making a javascript rich text editor, and sometimes when someone pastes into the editor, it adds styles like that.  But I don't want it to appear as smaller text.

答:
The following code looks wrong , remove the class=root on closing div.

```<code><div class="root"><p style="font-size:13px;">hello</p></div class="root">
</code>```

with jquery you can do it as below

fontsize can be a variable which you set dynamically

```<code>('selector').css('font-size',fontsize);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Is it possible to make a css declaration override a style set in the element's style property?

eg:

hello

Is there someway I can override the font size with css?

I already tried .root p{font-size:16px !important;}

The reason I want to do this is that I am making a javascript rich text editor, and sometimes when someone pastes into the editor, it adds styles like that.  But I don't want it to appear as smaller text.

Body:
The following code looks wrong , remove the class=root on closing div.

<div class="root"><p style="font-size:13px;">hello</p></div class="root">

with jquery you can do it as below

fontsize can be a variable which you set dynamically

('selector').css('font-size',fontsize);


答:
You can create indexes for align data, column Timestamp in df2 is converted to date:

```<code>df1 = df1.set_index('Timestamp')
s = df2.set_index(df2.Timestamp.dt.date)
df1['Consumption'] = df1['Consumption'].add(s['Consumption'])
#if necessary convert to int
df1['Consumption'] = df1['Consumption'].astype(int)
df1 = df1.reset_index()
print (df1)
   Timestamp  Consumption
0 2017-03-21         4903
1 2017-03-22         4987
2 2017-03-23         5037
3 2017-03-24         4883
4 2017-03-25         4894
5 2017-03-26         4973
6 2017-03-27         4962
7 2017-03-28         4901
8 2017-03-29         4925
9 2017-03-30         4762
</code>```

Title: Sum of column values of dataframes with date time index

Body:
I have two dataframes like this:

df1:

Timestamp    Consumption
2017-03-21    2903
2017-03-22    2982
2017-03-23    3011
2017-03-24    2964
2017-03-25    2961
2017-03-26    2967
2017-03-27    2967
2017-03-28    2903
2017-03-29    2923
2017-03-30    3032

df2:

Timestamp             Consumption
2017-03-21 23:00:00    2000.0
2017-03-22 23:00:00    2005.0
2017-03-23 23:00:00    2026.0
2017-03-24 23:00:00    1919.0
2017-03-25 23:00:00    1933.0
2017-03-26 23:00:00    2006.0
2017-03-27 23:00:00    1995.0
2017-03-28 23:00:00    1998.0
2017-03-29 23:00:00    2002.0
2017-03-30 23:00:00    1730.0

I want to add the values of Consumption column with respective date but i couldn't able to do that.

Desired output:

Timestamp    Consumption
2017-03-21    4903
2017-03-22    4987
2017-03-23    5037
2017-03-24    4883
2017-03-25    4894
2017-03-26    4973
2017-03-27    4962
2017-03-28    4901
2017-03-29    4925
2017-03-30    4762

I tried this:

sum = df1['Consumption'] + df2['Consumption'][match(df1.index,df2.index)]

Output:

Timestamp           Consumption
2017-03-21 00:00:00   NaN
2017-03-21 23:00:00   NaN
2017-03-22 00:00:00   NaN
2017-03-22 23:00:00   NaN
2017-03-23 00:00:00   NaN
2017-03-23 23:00:00   NaN
2017-03-24 00:00:00   NaN
2017-03-24 23:00:00   NaN
2017-03-25 00:00:00   NaN
2017-03-25 23:00:00   NaN
2017-03-26 00:00:00   NaN
2017-03-26 23:00:00   NaN
2017-03-27 00:00:00   NaN
2017-03-27 23:00:00   NaN
2017-03-28 00:00:00   NaN
2017-03-28 23:00:00   NaN
2017-03-29 00:00:00   NaN
2017-03-29 23:00:00   NaN
2017-03-30 00:00:00   NaN
2017-03-30 23:00:00   NaN

Help me achieve this.

Body:
You can create indexes for align data, column Timestamp in df2 is converted to date:

df1 = df1.set_index('Timestamp')
s = df2.set_index(df2.Timestamp.dt.date)
df1['Consumption'] = df1['Consumption'].add(s['Consumption'])
#if necessary convert to int
df1['Consumption'] = df1['Consumption'].astype(int)
df1 = df1.reset_index()
print (df1)
   Timestamp  Consumption
0 2017-03-21         4903
1 2017-03-22         4987
2 2017-03-23         5037
3 2017-03-24         4883
4 2017-03-25         4894
5 2017-03-26         4973
6 2017-03-27         4962
7 2017-03-28         4901
8 2017-03-29         4925
9 2017-03-30         4762


问:
Returning a promise inside promise (JavaScript)
Is it a good practice to use promises inside a promise?

Thank you.

答: There is no problem using promises inside promises, it is even required sometimes to create fully asynchronous scripts.</p>


问:
Android java.lang.NoSuchMethodError: java.util.List.stream use java 8 Lambda Expressions
Using java 8 Lambda Expressions

I am using Java JDK version jdk1.8.0_77 for both Android Studio.

I have also add jackOptions  in gradle

I have create simple list and add method  filter and sorted but after long time i have search but not any solution.

Gradle file

```<code>android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
    jackOptions {
        enabled true
    }
    applicationId "com.mobisharnam.meme"
    minSdkVersion 18
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
compileOptions {

    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:25.1.0'
compile 'com.android.support:design:25.1.0'
</code>```

MainActivity

```<code>import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    List<String> list =
            Arrays.asList("a1", "a2", "a3", "b1", "c2", "c1");

   list.stream().
            filter(s -> s.startsWith("c")).
            sorted().forEach(s -> Log.d("TEST", s));

}
}
</code>```

答:
The problem is that you are NOT chaining the stream methods properly, you can look below code:</p>

```<code>list.stream().
            filter(s -> s.startsWith("c")).
            sorted().forEach(s -> Log.d("TEST", s));
</code>```

Body:
Using java 8 Lambda Expressions

I am using Java JDK version jdk1.8.0_77 for both Android Studio.

I have also add jackOptions  in gradle

I have create simple list and add method  filter and sorted but after long time i have search but not any solution.

Gradle file

android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
    jackOptions {
        enabled true
    }
    applicationId "com.mobisharnam.meme"
    minSdkVersion 18
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
compileOptions {

    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:25.1.0'
compile 'com.android.support:design:25.1.0'

MainActivity

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    List<String> list =
            Arrays.asList("a1", "a2", "a3", "b1", "c2", "c1");

   list.stream().
            filter(s -> s.startsWith("c")).
            sorted().forEach(s -> Log.d("TEST", s));

}
}

Body:
The problem is that you are NOT chaining the stream methods properly, you can look below code:

list.stream().
            filter(s -> s.startsWith("c")).
            sorted().forEach(s -> Log.d("TEST", s));


问:
Having trouble with select statements in a stored function
What I'm trying to do here is execute GetValue3 with @ID and get the @results that list @fullname, @phonenumber, @email, @city.

I'm getting 2 errors and I've been trying to figure out how to fix both.

Error #1

Select statements included within a function cannot return data to a client

Error #2

A select statement that assigns a value to a variable must not be combined with data-retrieval

What should I do?

```<code>Create Function GetValue3 (@ID INT)
returns nvarchar(350)
as
begin
    declare @results nvarchar(350)
    declare @fullname nvarchar(75)
    declare @phonenumber nvarchar(100)
    declare @email nvarchar(50)
    declare @city nvarchar(20)

    select -- this is where I get the first error.
        @fullname = p.Full_Name,
        @phonenumber = c.Phone,
        @email = c.Email,
        @city = c.CityID,
        @results = @fullname,
        @phonenumber, @email, @city -- this is where I get the 2nd error.
    from
        d_People p, d_Contacts c
    where
        c.PeopleID = p.PeopleID
        and p.PeopleID = @ID;

    return @results
end
</code>```

答:
```<code>Create Function GetValue3 (@ID INT)
returns table
as
return select p.Full_Name, c.Phone, c.Email, c.CityID
              from d_People p, d_Contacts c
              where c.PeopleID=p.PeopleID and p.PeopleID=@ID;
</code>```

Body:
What I'm trying to do here is execute GetValue3 with @ID and get the @results that list @fullname, @phonenumber, @email, @city.

I'm getting 2 errors and I've been trying to figure out how to fix both.

Error #1

Select statements included within a function cannot return data to a client

Error #2

A select statement that assigns a value to a variable must not be combined with data-retrieval

What should I do?

Create Function GetValue3 (@ID INT)
returns nvarchar(350)
as
begin
    declare @results nvarchar(350)
    declare @fullname nvarchar(75)
    declare @phonenumber nvarchar(100)
    declare @email nvarchar(50)
    declare @city nvarchar(20)

    select -- this is where I get the first error.
        @fullname = p.Full_Name,
        @phonenumber = c.Phone,
        @email = c.Email,
        @city = c.CityID,
        @results = @fullname,
        @phonenumber, @email, @city -- this is where I get the 2nd error.
    from
        d_People p, d_Contacts c
    where
        c.PeopleID = p.PeopleID
        and p.PeopleID = @ID;

    return @results
end


问:
Entity Framework optional foreign key creating redundant FK field in dependant
I'm trying to establish a 0-1 relationship between User and TeamMember using this model

```<code>public class User
    {
        [Key]
        public Guid Id { get; set; }

        public Guid? TeamMemberId { get; set; }

        public virtual TeamMember TeamMember { get; set; }
    }

    public partial class TeamMember
    {

        [Key]
        [Column(Order = 0)]
        public Guid TeamId { get; set; }

        [Key]
        [Column(Order = 1)]
        public Guid UserId { get; set; }

        public virtual MSUCTeam Team { get; set; }

        public virtual User User { get; set; }

    }

    public class Team
    {
        [Key]
        public Guid Id { get; set; }

        public virtual ICollection<TeamMember> TeamMembers { get; set; }
    }
</code>```

To tell EF all about the relationship, I'm using the fluent API as follows

```<code>            modelBuilder.Entity<Team>()
            .HasMany(e => e.TeamMembers)
            .WithRequired(e => e.Team)
            .HasForeignKey(e => e.TeamId).WillCascadeOnDelete();

             modelBuilder.Entity<User>()
            .HasOptional(e => e.TeamMember)
            .WithRequired(e => e.User);
</code>```

And the tables themselves are defined on the context

```<code>        public virtual DbSet<Team> Teams { get; set; }

        public virtual DbSet<TeamMembers> TeamMembers { get; set; }
</code>```

This generates the required tables in the DB, but the TeamMembers Table has 3 columns:

1) TeamId (Guid, non nullable): PK and FK linked to Team.Id.
2) UserId (Guid, non nullable): PK.
3) User_Id (Guid, non nullable): FK linked to User.Id

How do I make the UserId colum be both the PK and the FK linked to the User table? There won't be a TeamMember entry without both UserId and TeamId but I must be telling EF wrong about what I want it to do.

答:
use this:

```<code>public class User
{
    [Key]
    public Guid Id { get; set; }

    public virtual TeamMember TeamMember { get; set; }
}

public partial class TeamMember
{
    [Key, ForeignKey("User")]
    public Guid Id{ get; set; }

    public virtual User User { get; set; }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<TeamMember>()
                .HasRequired(p => p.User)
                .WithOptional(p => p.TeamMember);
}
</code>```

for more information about split table check this link;

Body:
I'm trying to establish a 0-1 relationship between User and TeamMember using this model

public class User
    {
        [Key]
        public Guid Id { get; set; }

        public Guid? TeamMemberId { get; set; }

        public virtual TeamMember TeamMember { get; set; }
    }

    public partial class TeamMember
    {

        [Key]
        [Column(Order = 0)]
        public Guid TeamId { get; set; }

        [Key]
        [Column(Order = 1)]
        public Guid UserId { get; set; }

        public virtual MSUCTeam Team { get; set; }

        public virtual User User { get; set; }

    }

    public class Team
    {
        [Key]
        public Guid Id { get; set; }

        public virtual ICollection<TeamMember> TeamMembers { get; set; }
    }

To tell EF all about the relationship, I'm using the fluent API as follows

            modelBuilder.Entity<Team>()
            .HasMany(e => e.TeamMembers)
            .WithRequired(e => e.Team)
            .HasForeignKey(e => e.TeamId).WillCascadeOnDelete();

             modelBuilder.Entity<User>()
            .HasOptional(e => e.TeamMember)
            .WithRequired(e => e.User);

And the tables themselves are defined on the context

        public virtual DbSet<Team> Teams { get; set; }

        public virtual DbSet<TeamMembers> TeamMembers { get; set; }

This generates the required tables in the DB, but the TeamMembers Table has 3 columns:

1) TeamId (Guid, non nullable): PK and FK linked to Team.Id.
2) UserId (Guid, non nullable): PK.
3) User_Id (Guid, non nullable): FK linked to User.Id

How do I make the UserId colum be both the PK and the FK linked to the User table? There won't be a TeamMember entry without both UserId and TeamId but I must be telling EF wrong about what I want it to do.

Body:
use this:

public class User
{
    [Key]
    public Guid Id { get; set; }

    public virtual TeamMember TeamMember { get; set; }
}

public partial class TeamMember
{
    [Key, ForeignKey("User")]
    public Guid Id{ get; set; }

    public virtual User User { get; set; }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<TeamMember>()
                .HasRequired(p => p.User)
                .WithOptional(p => p.TeamMember);
}

for more information about split table check this link;


问:
Convert CSV to XML when CSV contains both character and number data
From this thread, I got the basic info on how to parse CSV to create XML. Unfortunately, the text fields (all enclosed in quotes) sometimes contain commas, so line.split(',') gives me too many columns. I can't figure out how to parse the CSV so line.split(',') distinguishes between commas within a text field, and commas separating fields. Any thoughts on how to do that?

Thanks!

答:
Try FileHelpers.

The FileHelpers are a free and easy to use .NET library to import/export data from fixed length or delimited records in files, strings or streams.


问:
OneToOneField is not working django
I have create OneToOneField relation in model and want to get data related data

Here is my model code

```<code>class Login (models.Model):
    login_id = models.AutoField(primary_key = True)
    user_name = models.CharField(max_length = 150)
    password = models.CharField(max_length = 255)
    role_id = models.IntegerField()
    user_id = models.IntegerField(unique = True)

    class Meta:
        db_table = 'login'

    def __str__(self):
        return self.login_id

class Catcher(models.Model):
    catcher_id = models.OneToOneField('Login', to_field = 'user_id', primary_key = True)
    catcher_fname = models.CharField(max_length = 128, blank = True)
    catcher_lname = models.CharField(max_length = 128, blank = True)
    api_key = models.CharField(max_length = 100, blank = False)

    class Meta:
        db_table = 'catcher'

    def __str__(self):
        return self.catcher_id
</code>```

I have Login table and login_id is PK, 2 table is Catcher and catcher_id is PK key.

In Login table user_id is FK and that is related to Catcher_id(PK) in catcher table.

When i run a query on catcher table without relation it's return me table data

```<code>catcher_id = models.AutoField(primary_key = True)
</code>```

Query
    loginDetail = Catcher.objects.get(catcher_id =742 ) # Runing succssfully

But when i create a relation it return an error

```<code>catcher_id = models.OneToOneField('Login', to_field = 'user_id', primary_key = True)

loginDetail = Catcher.objects.get(catcher_id =742 ) # Get an error

OperationalError at /login/login/
(1054, "Unknown column 'catcher.catcher_id_id' in 'field list'")
</code>```

why it return me field name like this catcher_id_id ??

答:
First of all. If you are using keys you should not use 'id' in the name. Django use 'id' so then your column name in the database will be 'user_id_id'. I think you don't want this name in your database. It is redundant.

Second thing, you should pass object to the query. Because OneToOneField is related to Login model, you should pass Login object. So try something like this, you have to change your values:

```<code>loginDetail = Catcher.objects.get(catcher_id=Login.objects.get(user_id=742))  # you should change only on 'login' and only on 'user'
</code>```

But you can use join over the models (database tables) also:

```<code>loginDetail = Catcher.objects.filter(catcher_id__user_id=742)
</code>```

And also based on PEP you should not use spaces between name of parameter and equal sign. Write only this: .get(user_id=742)) not .get(user_id =742))

Title: OneToOneField is not working django

Body:
I have create OneToOneField relation in model and want to get data related data

Here is my model code

class Login (models.Model):
    login_id = models.AutoField(primary_key = True)
    user_name = models.CharField(max_length = 150)
    password = models.CharField(max_length = 255)
    role_id = models.IntegerField()
    user_id = models.IntegerField(unique = True)

    class Meta:
        db_table = 'login'

    def __str__(self):
        return self.login_id

class Catcher(models.Model):
    catcher_id = models.OneToOneField('Login', to_field = 'user_id', primary_key = True)
    catcher_fname = models.CharField(max_length = 128, blank = True)
    catcher_lname = models.CharField(max_length = 128, blank = True)
    api_key = models.CharField(max_length = 100, blank = False)

    class Meta:
        db_table = 'catcher'

    def __str__(self):
        return self.catcher_id

I have Login table and login_id is PK, 2 table is Catcher and catcher_id is PK key.

In Login table user_id is FK and that is related to Catcher_id(PK) in catcher table.

When i run a query on catcher table without relation it's return me table data

catcher_id = models.AutoField(primary_key = True)

Query
    loginDetail = Catcher.objects.get(catcher_id =742 ) # Runing succssfully

But when i create a relation it return an error

catcher_id = models.OneToOneField('Login', to_field = 'user_id', primary_key = True)

loginDetail = Catcher.objects.get(catcher_id =742 ) # Get an error

OperationalError at /login/login/
(1054, "Unknown column 'catcher.catcher_id_id' in 'field list'")

why it return me field name like this catcher_id_id ??

Body:
First of all. If you are using keys you should not use 'id' in the name. Django use 'id' so then your column name in the database will be 'user_id_id'. I think you don't want this name in your database. It is redundant.

Second thing, you should pass object to the query. Because OneToOneField is related to Login model, you should pass Login object. So try something like this, you have to change your values:

loginDetail = Catcher.objects.get(catcher_id=Login.objects.get(user_id=742))  # you should change only on 'login' and only on 'user'

But you can use join over the models (database tables) also:

loginDetail = Catcher.objects.filter(catcher_id__user_id=742)

And also based on PEP you should not use spaces between name of parameter and equal sign. Write only this: .get(user_id=742)) not .get(user_id =742))


问:
How assign char * value to char using C
I have variable char * amount; and char t_amount;
I want to assign amount to t_amount.

```<code>char * amount = "sdf";
char t_amount = amount;
printf("%s t_amount \n", t_amount);
// I am expecting : sdf t_amount
</code>```

when i print, segmentation error occurs so how do i fix this?
Hope you guys can help me.

答:
```<code>char * amount = "sdf";
char t_amount = amount;
printf("%s t_amount \n", t_amount);

amount is a pointer you can not assign that kind of address to a variable. its an error.
when you declare char t_amount = amount, you assign a string to a char because an address is a string.
</code>```

Title: How assign char * value to char using C

Body:
I have variable char * amount; and char t_amount;
I want to assign amount to t_amount.

char * amount = "sdf";
char t_amount = amount;
printf("%s t_amount \n", t_amount);
// I am expecting : sdf t_amount

when i print, segmentation error occurs so how do i fix this?
Hope you guys can help me.


问:
What is the easiest/most effective way to learn Delphi?
I am totally new to programming and I have chosen Delphi as the programming language that I would like to learn.

I basically want to build tools that will fill and submit web forms using sockets and I want them to be multi threaded as well.

I would love for them to be feature rich and perform correctly.

I am in no real rush to do this as I do understand that it takes time to become efficient at anything (especially programming). However, I do want to take the shortest path that I can in learning.

If it were possible I would love to go to school to learn the language but it seems like there are no schools in the US that teach it.

I have found quite a good bit of information on the internet that has helped me gain a basic knowledge of how things work inside the IDE and how to build basic apps but I want to be able to build really good apps that these tutorial do not teach me how to do.

So.. My question is how do I go about becoming an expert Delphi programmer without having any "Real Teacher" to guide me? How did you guys learn?

Would learning another programming language with the help of a teacher and them coming back to delphi make sense?

答:
I basically want to build tools that
  will fill and submit web forms using
  sockets and I want them to be multi
  threaded as well.

If I understand what you are attempting properly...you are starting at he hard end..

I have been programming (Windows apps) in Delphi for a long time and My first attempt at a multi threaded http server conversation (using Indy) failed miserably - it did work (sort of) even at first-ish attempt but really it was miserable failure. So multi threading is "tricky" or just hard, maybe.

To fill and submit a web form - first work out how to fill in the online form itself - this will educated you about what is going on, you can do this quite reasonably with the TWebBrowser component (I've just done it). Then work out how to press the submit button on the online form. Remember you will be dealing with a process that is removed from you and that you do not have ultimate control over. Good luck (you will need perseverance too).

ContentLicense: CC BY-SA 4.0


问:
I want to create a listview like in play store installed apps fragment
I want to create a list view which shows some detail (batch name in my case) on the top of some listview items like this screenshot of play store. Here it shows downloading on top of a few items and updates or installed on others. How can I do this?</p>

答:
You can use CardView - Design library.

add library in app level Gradle-

```<code>compile 'com.android.support:cardview-v7:25.0.+'
</code>```

here is guide of card view

https://developer.android.com/reference/android/support/v7/widget/CardView.html

Body:
You can use CardView - Design library.

add library in app level Gradle-

compile 'com.android.support:cardview-v7:25.0.+'

here is guide of card view

https://developer.android.com/reference/android/support/v7/widget/CardView.html


问:
When does a process get SIGABRT (signal 6)?
What are the scenarios where a process gets a SIGABRT in C++?  Does this signal always come from within the process or can this signal be sent from one process to another?

Is there a way to identify which process is sending this signal?

答:
A case when process get SIGABRT from itself:
Hrvoje mentioned about a buried pure virtual being called from ctor generating an abort, i recreated an example for this.
Here when d is to be constructed, it first calls its base class A ctor,
and passes inside pointer to itself.
the A ctor calls pure virtual method before table was filled with valid pointer,
because d is not constructed yet.

```<code>#include<iostream>
using namespace std;
class A {
public:
 A(A *pa){pa->f();}
 virtual void f()=0;
};
class D : public A {
public:
 D():A(this){}
 virtual void f() {cout<<"D::f\n";}
};
int main(){
 D d;
 A *pa = &d;
 pa->f();
 return 0;
}
</code>```

compile: g++ -o aa aa.cpp

ulimit -c unlimited

run: ./aa

```<code>pure virtual method called
terminate called without an active exception
Aborted (core dumped)
</code>```

now lets quickly see the core file, and validate that SIGABRT was indeed called:

```<code>gdb aa core
</code>```

see regs:

```<code>i r
rdx            0x6      6
rsi            0x69a    1690
rdi            0x69a    1690
rip            0x7feae3170c37
</code>```

check code:

disas 0x7feae3170c37

```<code>mov    $0xea,%eax  = 234  <- this is the kill syscall, sends signal to process
syscall   <-----
</code>```

http://blog.rchapman.org/posts/Linux_System_Call_Table_for_x86_64/

234 sys_tgkill  pid_t tgid  pid_t pid   int sig = 6 = SIGABRT

:)

Body:
A case when process get SIGABRT from itself:
Hrvoje mentioned about a buried pure virtual being called from ctor generating an abort, i recreated an example for this.
Here when d is to be constructed, it first calls its base class A ctor,
and passes inside pointer to itself.
the A ctor calls pure virtual method before table was filled with valid pointer,
because d is not constructed yet.

#include<iostream>
using namespace std;
class A {
public:
 A(A *pa){pa->f();}
 virtual void f()=0;
};
class D : public A {
public:
 D():A(this){}
 virtual void f() {cout<<"D::f\n";}
};
int main(){
 D d;
 A *pa = &d;
 pa->f();
 return 0;
}

compile: g++ -o aa aa.cpp

ulimit -c unlimited

run: ./aa

pure virtual method called
terminate called without an active exception
Aborted (core dumped)

now lets quickly see the core file, and validate that SIGABRT was indeed called:

gdb aa core

see regs:

i r
rdx            0x6      6
rsi            0x69a    1690
rdi            0x69a    1690
rip            0x7feae3170c37

check code:

disas 0x7feae3170c37

mov    $0xea,%eax  = 234  <- this is the kill syscall, sends signal to process
syscall   <-----

http://blog.rchapman.org/posts/Linux_System_Call_Table_for_x86_64/

234 sys_tgkill  pid_t tgid  pid_t pid   int sig = 6 = SIGABRT

:)


问:
How do I stop make clean executing on every build?
First ever attempt at writing a small Makefile, but hitting a problem - how do I stop it executing make clean after every build?</p>

```<code>TASS64=64tass
EXOMIZER=exomizer
EXOMIZERFLAGS=sfx basic -n
VICE=/Applications/VICE/x64.app/Contents/MacOS/x64
VICEFLAGS=-sidenginemodel 1803 -keybuf "\88"
SOURCES=$(wildcard *.asm)
OBJECTS=$(SOURCES:.asm=.prg)

.PRECIOUS=Calvin.prg

all: $(TARGETS)

%.prg: %.asm
    $(TASS64) -C -a -o $@ -i $<

%: %.prg
    $(VICE) $(VICEFLAGS) $<

.PHONY: clean
clean:
    rm $(OBJECTS)
</code>```

答:
I guess, it does not execute 'make clean'. However, what may happen is that intermediate (secondary) results are deleted. GNU Make does that by default. To prevent make from doing so, mention those intermediate results X1, X2, ... in

```<code> .SECONDARY: X1 X2 ...
</code>```

Or, in order to leave any secondary result in place, simply type:

```<code> .SECONDARY:
</code>```

without any specific target.

Body:
First ever attempt at writing a small Makefile, but hitting a problem - how do I stop it executing make clean after every build?

TASS64=64tass
EXOMIZER=exomizer
EXOMIZERFLAGS=sfx basic -n
VICE=/Applications/VICE/x64.app/Contents/MacOS/x64
VICEFLAGS=-sidenginemodel 1803 -keybuf "\88"
SOURCES=$(wildcard *.asm)
OBJECTS=$(SOURCES:.asm=.prg)

.PRECIOUS=Calvin.prg

all: $(TARGETS)

%.prg: %.asm
    $(TASS64) -C -a -o $@ -i $<

%: %.prg
    $(VICE) $(VICEFLAGS) $<

.PHONY: clean
clean:
    rm $(OBJECTS)

Body:
I guess, it does not execute 'make clean'. However, what may happen is that intermediate (secondary) results are deleted. GNU Make does that by default. To prevent make from doing so, mention those intermediate results X1, X2, ... in

 .SECONDARY: X1 X2 ...

Or, in order to leave any secondary result in place, simply type:

 .SECONDARY:

without any specific target.


问:
why would cipher.getOutputSize() return value higher than required?
I'm trying to decrypt a file encrypted with AES256 CBC, and here's my code to do that:

```<code>PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
cipher.init(false, new ParametersWithIV(new KeyParameter(key), iv));
byte[] outBuf = new byte[cipher.getOutputSize(data.length)];
int processed = cipher.processBytes(data, 0, data.length, outBuf, 0);
processed += cipher.doFinal(outBuf, processed);
</code>```

It's quite simple, however cipher.getOutputSize(data.length) would always return a value which is larger than needed. I always end up with some weird characters at the end of the buffer.

I have tried to decrypt two html files, and here's the end of them:

```<code></HTML>����������������
// Processed: 9304 Size: 9312
</code>```

and

```<code></body></html>��������
// Processed: 636 Buffer size: 640
</code>```

So the additional bytes size is not consistent, I cannot just decrement 'by some'.

What am I doing wrong when calculating the size of the output array?

答:
TL;DR: getOutputSize() lets you know what sized buffer to allocate (a worst case), return values from processBytes/doFinal tell you how much of the buffer was actually used (exact).

You are using PaddedBufferedBlockCipher for decryption (above code defaults to PKCS7 padding). getOutputSize() cannot determine the exact amount of output plaintext until it actually sees the decrypted data for the final block, so the returned value will be an upper bound, which is why the return value is there for processBytes/doFinal to let you know how much was actually output.

For simplicity, PaddedBufferedBlockCipher also ignores the details of the particular padding scheme used - it assumes only that the final block could contain some amount of padding that will be removed.

The unused bytes at the end of 'outBuf' are not written to by the cipher. In particular, they will not contain the padding. Presumably the "weird characters" are zero bytes from the array initialisation.

Body:
I'm trying to decrypt a file encrypted with AES256 CBC, and here's my code to do that:

PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
cipher.init(false, new ParametersWithIV(new KeyParameter(key), iv));
byte[] outBuf = new byte[cipher.getOutputSize(data.length)];
int processed = cipher.processBytes(data, 0, data.length, outBuf, 0);
processed += cipher.doFinal(outBuf, processed);

It's quite simple, however cipher.getOutputSize(data.length) would always return a value which is larger than needed. I always end up with some weird characters at the end of the buffer.

I have tried to decrypt two html files, and here's the end of them:

����������������
// Processed: 9304 Size: 9312

and

��������
// Processed: 636 Buffer size: 640

So the additional bytes size is not consistent, I cannot just decrement 'by some'.

What am I doing wrong when calculating the size of the output array?


问:
Wiremock stub working like ECHO
my JS application is using wiremocks to mock backend calls. Is it possible to create such Wiremock definition in order to create echo service (the body JSON content of response shoould be the same as  body JSON content of request).</p>

答: You should be able to do that with the new response templating feature: http://wiremock.org/docs/response-templating/</p>

Title: Wiremock stub working like ECHO


问:
Caching entity manager's (hibernate session) find query
I am currently setting up query caches for my JPQL (Named) queries.
However, some methods are implemented using entityManager.find(clazz, id) and i cannot find a way to make it work as a cached query.
Since this is a module that is read-only I would like to set caches for all queries. Is it possible to define a ehcache region for em.find() method without manualy typing named SELECTs for each entity?</p>

答:
Did you check if the persistant unit has
    property name="javax.persistence.sharedCache.mode" value="ALL"

in it.


问:
Guess the number game
Im getting a few errors not sure how to fix them i am very new to coding.
Would be really great to get some help thanks.</p>

```<code>#Author : John Smith
#Date   : 3/19/17
#
#Guess the number game
#1 Player vs. Computer
import random
minGuess = 1
maxGuess =6

#Ask the user for their name and their guess
name = input("What is your name")
print("Hi + name")
print("Enter a number between: " +minGuess + " and " + maxGuess)
guess = int(input("what is your guess?"))

#Generate a random number and tell the user if they have won or lost
secretNumber = random.randint(minGuess, maxGuess)
if (guess != ??????)
    print("congratz you got it right")
else:
    print("You loose the number was ???")

print("Thankyou for playing guess the number.")
</code>```

答:
print("Hi + name")  should be  print("Hi "+ name) if you want to use the variable name from the line above.

I guess your error is coming from this line  if (guess != ??????).  You need to change the "??????", (since it doesn't mean anything for Python) into something else. What do you think "guess" should be compared to ?

Title: Guess the number game

Body:
Im getting a few errors not sure how to fix them i am very new to coding.
Would be really great to get some help thanks.

#Author : John Smith
#Date   : 3/19/17
#
#Guess the number game
#1 Player vs. Computer
import random
minGuess = 1
maxGuess =6

#Ask the user for their name and their guess
name = input("What is your name")
print("Hi + name")
print("Enter a number between: " +minGuess + " and " + maxGuess)
guess = int(input("what is your guess?"))

#Generate a random number and tell the user if they have won or lost
secretNumber = random.randint(minGuess, maxGuess)
if (guess != ??????)
    print("congratz you got it right")
else:
    print("You loose the number was ???")

print("Thankyou for playing guess the number.")


问:
Redirects in PHP website not working properly
I have written htaccess file. I want to redirect https://example.com/index.php?route=product/category&path=1 to https://example.com/fashion.

My htaccess is

```<code>RewriteEngine On
RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]
</code>```

But it is not redirecting to the link I have shown

答:
You may use something like this to redirect all request to your index.php and then manage the requests from there usint*HTTP-PATH. var_dump($_SERVER) to see the actual request.

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]
</code>```

If you want to redirect a specific request, then someone else may help you here later on.

Body:
I have written htaccess file. I want to redirect https://example.com/index.php?route=product/category&path=1 to https://example.com/fashion.

My htaccess is

RewriteEngine On
RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]

But it is not redirecting to the link I have shown

Body:
You may use something like this to redirect all request to your index.php and then manage the requests from there usint*HTTP-PATH. var_dump($_SERVER) to see the actual request.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]

If you want to redirect a specific request, then someone else may help you here later on.


答:
In the sqlite3 command-line shell, you can use the writefile() function to put the blob into a file:

```<code>SELECT writefile('body.zlib', SomeColumn) FROM SomeTable WHERE ID = 42;
</code>```

Then use gzip or openssl or zlib-flate or a Python script to decompress this file:

```<code>printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" | cat - body.zlib | gzip -dc
</code>```

```<code>openssl zlib -d < body.zlib
</code>```

```<code>zlib-flate -uncompress < body.zlib
</code>```

import zlib
import sys

with open('body.zlib', 'rb') as compressed:
    with open('body.txt', 'wb') as expanded:
        data = zlib.decompress(compressed.read())
        expanded.write(data)
```

Title: deflate zlib from a sqlite android database

Body:
im trying to uncompress the data retrieve from sqlite gmail database to do some triggers. How can i do this?

This is the output from bodyCompressed.

pë☼IìÑ61UX 4×►▒▒ü4`¼┬♠6~ó©DX?┴¯╠ß1╝Q.
Cmhs↓×♥ògS'â%ÅÙÅDR½òÙ%Á┌┐e"Ì↓fÚp§Y7±[±☻¸h"X

You can see on this image

I need to do this in terminal but i dont know what can i do.

EDIT ADDING HEX

789CAD56CB72E246145D8FBFA2C354668524B031D8209478FC20F178ECB19D729C6C522DF59568DCEA96FB6183BF2659669155FE60FC63B92D60603C76D5A4128A424D3FEE3DE7DC731B6297C4914B36365E6DBC5ABD9FBCFC62CCF81D31762660D84869765368E5240B322594EEBF6E753A9D6D18CCBFDD8FB985468271624B5301CB6325D50597FD563525D4594596834149A7C13D6776DCDF6EE1E4E0A5F8754C0CAA93D832824BA6A272D8D86C24312F8B659AB5480D6274366C8CADAD4C3F8A32DE0D0BA50A01CE80CE94B4206D98A932AAB49ACEA2CDEBE3F7873FBD3D85D3B46AC13B3B7DFB70B32F8A8CA9AAB0E9E5E9E4E0FCE4E8846F5EFE3A1E6FFDDC15E2C3F9556F66A6B7EF1F46C1E1F1B4DAFDE117713E34AD8005D00E72FBDA67C6C43C447C4ED7A9663F1E5FC9CB2A9C5405E28E2CF31FFA336654F0027965880E74639DE892638ED803C31FA0BFE5059B2B1BA4CA5A55F67B483C39757047895496E73CA3197FFC5B1206244E93D1D9C90315AABDBBD389A3741DC232FF5727F9F8FB33A75F469FC4948C35E4F38AA02EF7F7F7610AB6CE17828918B5CA042548432710F922495A42D4EEECB67ABD4EAFDDEB767A6F68590DC07C9262CD73CF1987A59D3C1F5494312E8B7EDB7BAEDD45362B72ED1DFC2AB884600CBC18DB7E3BDCDA1AA44A33D081A68C3BD3DFC22D16A6366090294D2D57B22F95846F7859296DA9B40D62511FB0C3C66FA9A0F2A641900C0D0CCD4103E31A32EBB45879D1539F7BB17605AE7D3716433035BDDBE17F10E8DBCDEE228C514E67302C4ACA453DE18C1DFABD3BDDB62FFF6EA7D56A2D168AE1DED1F964FF74343AB93659F7E8E2DDB5CACDE86847F0D1E8EA81EDCEF87923B9024D4E3F794AC938A22F78F80B0FB5B7BFF0909F7A62A2E7FBFB9968AD65456ABBF527488DE7B34559FDEE3EB7B89435924363812C2423D813580C5E70A69ABE1F4A2A415302D34C38C3EF689350621CAE60388905D45C9119A91CE0DEF985810A70992B5D2E9A0A6773CE40669C0ADC6ADC042CC5262006320D78CDE1DD928341B1A86892CCCD3C823B278AC579A908267BFC8354A04B6E39A3042D45042502662139C40CD4288F754C534C8E4EE229C2F7A756BCFC11D05AE9261E235A15B45486DC3AA859D6701176894E44524D4C6A885088BD7492E32E52AF203D9CD21A30B840C36AC4C73385296B600AB5910ED3A260D47AC61EFFCC13CC0061D7CA81E0252A57AFA198E6F12F9FC51F45465E4447C5ADE34884A9CC217C5488B289AB9F8294DC942A247B86D7A39ACD1C65B6645407E28882A76E91265315A7441167B9E00FABDB6E5DA226515F9BBFB9DA45EB8CB9F32364972335812562CD79D1A4273FF6F5A0E669D9A8C639060283959557A5CEC56AFC27671F0E50395CBC38C07173E13098E0CF124213CA9FC44A8F71B0175E84FBE159B866D702AF2087FE5E950D7C8F939826DE9BDFAF5D19BE43C3676EE9FFABBBFE45F7AE055CFC3824B1DF937CFC93BC057BE97791CDB0D5EEC5513DFF59647CFA3F13388C236C20FCCBF20FFDA7054B

EDITED WITH JAVA CODE TRYING THIS

private String getTextMail(){
String mail="";
Process sh = null;
try {
    sh = Runtime.getRuntime().exec("su", null,null);
} catch (IOException e) {
    e.printStackTrace();
}

OutputStream os = sh.getOutputStream();
try {
    os.write(("sqlite3 /data/data/com.google.android.gm/databases/mailstore.romapudelca@gmail.com.db \"SELECT bodyCompressed FROM MESSAGES WHERE dateSentMs=(SELECT max(dateSentMs) from messages)\"").getBytes("ASCII"));
    os.flush();
    os.close();
    InputStream is=sh.getInputStream();
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    int nRead;
    byte[] data = new byte[16384];

    while ((nRead = is.read(data, 0, data.length)) != -1) {
        buffer.write(data, 0, nRead);
    }
    Inflater decompresser = new Inflater(true);
    decompresser.setInput(buffer.toByteArray());
    byte[] result = new byte[4096];
    int resultLength = decompresser.inflate(result);
    decompresser.end();
    sh.waitFor();
    mail=new String(result);
} catch (InterruptedException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} catch (DataFormatException e) {
    e.printStackTrace();
}

return mail;
}

Java code return me this:

W/System.err: java.util.zip.DataFormatException: invalid stored block lengths
W/System.err:     at java.util.zip.Inflater.inflateImpl(Native Method)
W/System.err:     at java.util.zip.Inflater.inflate(Inflater.java:237)
W/System.err:     at java.util.zip.Inflater.inflate(Inflater.java:214)
W/System.err:     at cpc.cpc_dectect.MainActivity$telegramTask$override.getTextMail(MainActivity.java:229)
W/System.err:     at cpc.cpc_dectect.MainActivity$telegramTask$override.doInBackground(MainActivity.java:249)
W/System.err:     at cpc.cpc_dectect.MainActivity$telegramTask$override.access$dispatch(MainActivity.java)
W/System.err:     at cpc.cpc_dectect.MainActivity$telegramTask.doInBackground(MainActivity.java:0)
W/System.err:     at cpc.cpc_dectect.MainActivity$telegramTask.doInBackground(MainActivity.java:196)
W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:307)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
W/System.err:     at java.lang.Thread.run(Thread.java:833)

ERROR USING PRINTF MODE

\x08\x00\x00\x00\x00\x00" |cat - fich.gz| gzip -d                                   <

bla bla bla bl abl abla

<d
iv>

Links:

┬á 1. <a href="https://arpo.com/2asajshkdashjkashdjka0a gzip: failed gz
close

If i use -dc params in gzip the system returns:

-dc: No such file or directory
sush: cat: <stdout>: Broken pipe

Body:
In the sqlite3 command-line shell, you can use the writefile() function to put the blob into a file:

SELECT writefile('body.zlib', SomeColumn) FROM SomeTable WHERE ID = 42;

Then use gzip or openssl or zlib-flate or a Python script to decompress this file:

printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" | cat - body.zlib | gzip -dc

openssl zlib -d < body.zlib

zlib-flate -uncompress < body.zlib

import zlib
import sys

with open('body.zlib', 'rb') as compressed:
    with open('body.txt', 'wb') as expanded:
        data = zlib.decompress(compressed.read())
        expanded.write(data)


问:
Copying children of a
 to another
 using jQuery
How can I copy copy content of a ul that is li's inside it to another ul.

Say we have t = $("ul#target") and s = $("ul#source").

Title: Copying children of a <ul> to another <ul> using jQuery

Body: s.children().clone().appendTo(t)


问:
Writing an Integer Array into a File
I'm trying to make a method that reads the file and returns an array of integers, and then convert each line of data to an integer. Then I'm trying to sort the data using a bubble sort before taking the resulting array and writing them back into a file. I'm pretty sure my bubble sort code is right, but I'm having issues trying to write the integers back into the file... I've copied and pasted the entire code I've got below :)</p>

```<code>import java.io.*;
import java.util.Scanner;

public class Main {

public static void main(String[] args) throws IOException,
    FileNotFoundException {

 String filename = "/Users/Desktop/13-2/src/pkg13/pkg2/sort.txt";
processFile(filename);
writeToFile(filename);//calls method processFile
}

public static void processFile (String file)
throws IOException, FileNotFoundException{
//String line;
 //lines is declared as a string

String filename = "/Users/Desktop/13-2/src/pkg13/pkg2/sort.txt";
try (BufferedReader inputReader = new BufferedReader (new      InputStreamReader(new     FileInputStream("/Users/Desktop/writeTofile/src/writetofile/scorewrite.txt")))) {
        String line;
        while ((line = inputReader.readLine()) != null) {
            double number = Double.parseDouble(line);
        }
//Scanner scanner = new Scanner(new File(filename));
//int i = 0;
//while(scanner.hasNextInt()){
  // bubble[i++] = scanner.nextInt();

}
}

public static void writeToFile (String filename) throws IOException {
PrintWriter outputWriter = new PrintWriter(new FileWriter(filename));

    outputWriter.println();

outputWriter.flush();
outputWriter.close();
}
private int[] array = new int[25];

public int maxi(int[]a, int first){
   int max = 0;
    for(int i=first; i<a.length; i++)
    {
        if (a[max]<a[i]){
            max =i;
        }
    }
    return max;
}

public void bubble(double number) {
    boolean a = false;
    for (int i=0; i<array.length-1; i++) {
        if (array [i]> array [i+1]) {
            int temp = array [i];
            array [i] = array [i+1];
            array [i+1] = temp ;}
        a= true;

        }
    }
}
</code>```

答:
you are writing only one empty line to the output file here:

```<code>outputWriter.println();
</code>```

You need to write all numbers from your array, but you don't even store them anywhere:

```<code>double number = Double.parseDouble(line);
</code>```

after this line, the number read from input file needs to be stored in an array.

Hint snippet:

```<code>int i=0;
while ((line = inputReader.readLine()) != null) {
        array[i++] = Integer.parseInt(line);
    }
</code>```

You are also mixing doubles with ints :(

You are also wrong that your bubble sort is correct :(

I suggest start with something more simple, just read the array of ints and write it back to file.

Title: Writing an Integer Array into a File

Body:
I'm trying to make a method that reads the file and returns an array of integers, and then convert each line of data to an integer. Then I'm trying to sort the data using a bubble sort before taking the resulting array and writing them back into a file. I'm pretty sure my bubble sort code is right, but I'm having issues trying to write the integers back into the file... I've copied and pasted the entire code I've got below :)

import java.io.*;
import java.util.Scanner;

public class Main {

public static void main(String[] args) throws IOException,
    FileNotFoundException {

 String filename = "/Users/Desktop/13-2/src/pkg13/pkg2/sort.txt";
processFile(filename);
writeToFile(filename);//calls method processFile
}

public static void processFile (String file)
throws IOException, FileNotFoundException{
//String line;
 //lines is declared as a string

String filename = "/Users/Desktop/13-2/src/pkg13/pkg2/sort.txt";
try (BufferedReader inputReader = new BufferedReader (new      InputStreamReader(new     FileInputStream("/Users/Desktop/writeTofile/src/writetofile/scorewrite.txt")))) {
        String line;
        while ((line = inputReader.readLine()) != null) {
            double number = Double.parseDouble(line);
        }
//Scanner scanner = new Scanner(new File(filename));
//int i = 0;
//while(scanner.hasNextInt()){
  // bubble[i++] = scanner.nextInt();

}
}

public static void writeToFile (String filename) throws IOException {
PrintWriter outputWriter = new PrintWriter(new FileWriter(filename));

    outputWriter.println();

outputWriter.flush();
outputWriter.close();
}
private int[] array = new int[25];

public int maxi(int[]a, int first){
   int max = 0;
    for(int i=first; i<a.length; i++)
    {
        if (a[max]<a[i]){
            max =i;
        }
    }
    return max;
}

public void bubble(double number) {
    boolean a = false;
    for (int i=0; i<array.length-1; i++) {
        if (array [i]> array [i+1]) {
            int temp = array [i];
            array [i] = array [i+1];
            array [i+1] = temp ;}
        a= true;

        }
    }
}

Body:
you are writing only one empty line to the output file here:

outputWriter.println();

You need to write all numbers from your array, but you don't even store them anywhere:

double number = Double.parseDouble(line);

after this line, the number read from input file needs to be stored in an array.

Hint snippet:

int i=0;
while ((line = inputReader.readLine()) != null) {
        array[i++] = Integer.parseInt(line);
    }

You are also mixing doubles with ints :(

You are also wrong that your bubble sort is correct :(

I suggest start with something more simple, just read the array of ints and write it back to file.


问:
How to fix test failing with "No ModelAndView found"?
This class is in the top of my tests hierarchy:

```<code>@TestPropertySource("/test.properties")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public abstract class ApplicationAbstractTest {
}
</code>```

And few more test classes:

```<code>@WebAppConfiguration
@ActiveProfiles("mysql")
abstract public class AbstractControllerTest extends ApplicationAbstractTest {

    protected MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @PostConstruct
    private void postConstruct() {
        mockMvc = MockMvcBuilders
                .webAppContextSetup(webApplicationContext)
                .apply(springSecurity())
                .build();
    }
}
</code>```

JsonUserServiceTest:

```<code>@ActiveProfiles("json")
public class JsonUserServiceTest extends ApplicationAbstractTest {
    @Before
    public void setUp() throws Exception {
        ...
    }
}
</code>```

ContactControllerTest:

```<code>public class ContactControllerTest extends AbstractControllerTest {
    @Test
    public void testGet() throws Exception {
        mockMvc.perform(get("/update-" + ID + "-contact")
                .with(userAuth(USER)))
//                .andExpect(status().isOk())
                .andDo(print())
                .andExpect(view().name("details"))
                .andExpect(forwardedUrl("/WEB-INF/jsp/details.jsp"));
    }
}
</code>```

So, when I run ContactControllerTest along - it is successfull, and print method shows me:

```<code>Handler:
             Type = com.telecom.web.ContactController
           Method = public java.lang.String com.myApp.web.ContactController.details(java.lang.Integer,org.springframework.ui.ModelMap)
</code>```

But when I run all tests, so JsonUserServiceTest runs first, ContactControllerTest fails. And print shows:

```<code>Handler:
             Type = null
...
java.lang.AssertionError: No ModelAndView found
</code>```

What is wrong in configuration? Or how troubleshoot it?

UPD:
at the same time, test like this, allways works fine:

```<code>public class UserControllerTest extends AbstractControllerTest {
    @Test
    public void testRegister() throws Exception {
        mockMvc.perform(get("/register"))
                .andDo(print())
                .andExpect(view().name("profile"))
                .andExpect(forwardedUrl("/WEB-INF/jsp/profile.jsp"));
    }
}
</code>```

UPD:
There is controller's method I'm testing:

```<code>@GetMapping("/update-{id}-contact")
public String details(@PathVariable Integer id, ModelMap model) {
    Integer userId = AuthorizedUser.id();
    LOG.info("get contact {} for User {}", id, userId);
    Contact contact = service.get(id, userId);
    model.addAttribute("contact", contact);
    return "details";
}
</code>```

I also have such bean:

```<code>@Bean
public InternalResourceViewResolver viewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/WEB-INF/jsp/");
    viewResolver.setSuffix(".jsp");

    return viewResolver;
}
</code>```

UPD: I've tried configure mockMvc in separate class:

```<code>@Configuration
public class TestConfig {

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Bean
    public MockMvc mockMvc() {
        return MockMvcBuilders
                .webAppContextSetup(webApplicationContext)
                .apply(springSecurity())
                .build();
    }
}
</code>```

And added it here:

```<code>@WebAppConfiguration
@ContextConfiguration(classes = {TestConfig.class})
@ActiveProfiles("mysql")
abstract public class AbstractControllerTest extends ApplicationAbstractTest {
</code>```

but I've received:

java.lang.IllegalStateException: springSecurityFilterChain cannot be
  null. Ensure a Bean with the name springSecurityFilterChain
  implementing Filter is present or inject the Filter to be used.

答:
Create a configuration file that will initialize mocking objects for your test cases. And put at all test case classes.

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestConfig.class})
</code>```

It will initialize all your mocking objects only once and cached after that and reused for all test cases.

Or if you don't want to use mocking configuration, you can directly
  pass the actual application configuration to ContextConfiguration as
  below

For annotation based application configuration (here AppConfig and AppConfig2 are your configuration class)

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AppConfig.class, AppConfig2.class})
</code>```

For xml based application configuration (here appConfig.xml and appConfig2.xml are your configuration files)

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:pathTo/appConfig.xml","classpath:pathTo/appConfig2.xml"})
</code>```

Reference : JUnit + Spring integration example

Body:
This class is in the top of my tests hierarchy:

@TestPropertySource("/test.properties")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public abstract class ApplicationAbstractTest {
}

And few more test classes:

@WebAppConfiguration
@ActiveProfiles("mysql")
abstract public class AbstractControllerTest extends ApplicationAbstractTest {

    protected MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @PostConstruct
    private void postConstruct() {
        mockMvc = MockMvcBuilders
                .webAppContextSetup(webApplicationContext)
                .apply(springSecurity())
                .build();
    }
}

JsonUserServiceTest:

@ActiveProfiles("json")
public class JsonUserServiceTest extends ApplicationAbstractTest {
    @Before
    public void setUp() throws Exception {
        ...
    }
}

ContactControllerTest:

public class ContactControllerTest extends AbstractControllerTest {
    @Test
    public void testGet() throws Exception {
        mockMvc.perform(get("/update-" + ID + "-contact")
                .with(userAuth(USER)))
//                .andExpect(status().isOk())
                .andDo(print())
                .andExpect(view().name("details"))
                .andExpect(forwardedUrl("/WEB-INF/jsp/details.jsp"));
    }
}

So, when I run ContactControllerTest along - it is successfull, and print method shows me:

Handler:
             Type = com.telecom.web.ContactController
           Method = public java.lang.String com.myApp.web.ContactController.details(java.lang.Integer,org.springframework.ui.ModelMap)

But when I run all tests, so JsonUserServiceTest runs first, ContactControllerTest fails. And print shows:

Handler:
             Type = null
...
java.lang.AssertionError: No ModelAndView found

What is wrong in configuration? Or how troubleshoot it?

UPD:
at the same time, test like this, allways works fine:

public class UserControllerTest extends AbstractControllerTest {
    @Test
    public void testRegister() throws Exception {
        mockMvc.perform(get("/register"))
                .andDo(print())
                .andExpect(view().name("profile"))
                .andExpect(forwardedUrl("/WEB-INF/jsp/profile.jsp"));
    }
}

UPD:
There is controller's method I'm testing:

@GetMapping("/update-{id}-contact")
public String details(@PathVariable Integer id, ModelMap model) {
    Integer userId = AuthorizedUser.id();
    LOG.info("get contact {} for User {}", id, userId);
    Contact contact = service.get(id, userId);
    model.addAttribute("contact", contact);
    return "details";
}

I also have such bean:

@Bean
public InternalResourceViewResolver viewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/WEB-INF/jsp/");
    viewResolver.setSuffix(".jsp");

    return viewResolver;
}

UPD: I've tried configure mockMvc in separate class:

@Configuration
public class TestConfig {

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Bean
    public MockMvc mockMvc() {
        return MockMvcBuilders
                .webAppContextSetup(webApplicationContext)
                .apply(springSecurity())
                .build();
    }
}

And added it here:

@WebAppConfiguration
@ContextConfiguration(classes = {TestConfig.class})
@ActiveProfiles("mysql")
abstract public class AbstractControllerTest extends ApplicationAbstractTest {

but I've received:

java.lang.IllegalStateException: springSecurityFilterChain cannot be
  null. Ensure a Bean with the name springSecurityFilterChain
  implementing Filter is present or inject the Filter to be used.

Body:
Create a configuration file that will initialize mocking objects for your test cases. And put at all test case classes.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestConfig.class})

It will initialize all your mocking objects only once and cached after that and reused for all test cases.

Or if you don't want to use mocking configuration, you can directly
  pass the actual application configuration to ContextConfiguration as
  below

For annotation based application configuration (here AppConfig and AppConfig2 are your configuration class)

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AppConfig.class, AppConfig2.class})

For xml based application configuration (here appConfig.xml and appConfig2.xml are your configuration files)

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:pathTo/appConfig.xml","classpath:pathTo/appConfig2.xml"})

Reference : JUnit + Spring integration example


问:
Just creating a new Xamarin Forms Content Page Xaml makes the project uncompilable as ContentPageViewModel is uknown
Adding this to my PCL, the code behind file has this line:

```<code>BindingContext = new ContentPageViewModel();
</code>```

In the constructor. The compiler does not know about ContentPageViewModel.

How is it possible that things break this fast? Am I not supposed to use ContentPages with a Xamarin Forms app?

答:
It seems that this is a bug in the current templates. Check the bug on the Xamarin Bugzilla here.

You can work around it by implementing the actual ViewModel yourself, or just removing the line if you do not wish to use it.

Body:
Adding this to my PCL, the code behind file has this line:

BindingContext = new ContentPageViewModel();

In the constructor. The compiler does not know about ContentPageViewModel.

How is it possible that things break this fast? Am I not supposed to use ContentPages with a Xamarin Forms app?


问:
Error on substr(explode)
Do you have any idea what I did wrong in the code row below.
Get an error from my DW editor with no description.</p>

```<code>$oauth = explode('&',base64_decode($_POST['oauth_token'])); // is ak
$user_id = substr(explode('=',$oauth['1'])['1'],4); // get error
</code>```

答:
explode() returns an array and then you attempt to use a value of this array by indexing directly the value returned by the explode() call:

```<code>explode(...)['1']
</code>```

This improvement of the syntax was introduced in PHP 5.4. Dreamweaver either doesn't know about it or it thinks (was configured this way?) you use an older PHP version.

Title: Error on substr(explode)

Body:
Do you have any idea what I did wrong in the code row below.
Get an error from my DW editor with no description.

$oauth = explode('&',base64_decode($_POST['oauth_token'])); // is ak
$user_id = substr(explode('=',$oauth['1'])['1'],4); // get error

Body:
explode() returns an array and then you attempt to use a value of this array by indexing directly the value returned by the explode() call:

explode(...)['1']

This improvement of the syntax was introduced in PHP 5.4. Dreamweaver either doesn't know about it or it thinks (was configured this way?) you use an older PHP version.


问:
How To Read DateTime From DataBase Using Java Script in ASp.net
im trying to set endtime(expired/CountDown)

```<code>       <p id="demo"></p>

<script>
    // Set the date we're counting down to
    var countDownDate = new Date("Jan 5, 2018 15:37:25").getTime();

    // Update the count down every 1 second
    var x = setInterval(function () {

        // Get todays date and time
        var now = new Date().getTime();

        // Find the distance between now an the count down date
        var distance = countDownDate - now;

        // Time calculations for days, hours, minutes and seconds
        var days = Math.floor(distance / (1000 * 60 * 60 * 24));
        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);

        // Output the result in an element with id="demo"
        document.getElementById("demo").innerHTML = days + "d " + hours + "h "
        + minutes + "m " + seconds + "s ";

        // If the count down is over, write some text
        if (distance < 0) {
            clearInterval(x);
            document.getElementById("demo").innerHTML = "EXPIRED";
        }
    }, 1000);
</script>
</code>```

this code worked but the date is static
i need to change var countDownDate = new Date("Jan 5, 2018 15:37:25").getTime(); to value from database
how do that ?

in asp.net and entitiyframework

答:
You can create an ApiController, with a method that gets data from the database and returns it, then using ajax request you get your data in javascript. You have here an example:

```<code>public class YourApiController : ApiController
{

    [HttpGet]
    [Route("api/getDateFromServer")]
    public DateTime GetDateFromServer()
    {
        //TODO retrieve data from where you want, by now we will return DateTime.Now
        return DateTime.Now;
    }
}
</code>```

Then, in your javascript you add this:

```<code>    $.ajax({
        type: 'GET',
        context: this,
        url: '/api/getDateFromServer',
    }).done(function (data) {
       //Here you have your data from server in your javascript
       countDownDate = data;
    });
</code>```

Body:
im trying to set endtime(expired/CountDown)

this code worked but the date is static
i need to change var countDownDate = new Date("Jan 5, 2018 15:37:25").getTime(); to value from database
how do that ?

in asp.net and entitiyframework

Body:
You can create an ApiController, with a method that gets data from the database and returns it, then using ajax request you get your data in javascript. You have here an example:

public class YourApiController : ApiController
{

    [HttpGet]
    [Route("api/getDateFromServer")]
    public DateTime GetDateFromServer()
    {
        //TODO retrieve data from where you want, by now we will return DateTime.Now
        return DateTime.Now;
    }
}

Then, in your javascript you add this:

    $.ajax({
        type: 'GET',
        context: this,
        url: '/api/getDateFromServer',
    }).done(function (data) {
       //Here you have your data from server in your javascript
       countDownDate = data;
    });


答:
it could be nice if you will write the errors you got.
the only problem i can see is if(guess != ??????)
the expression ?????? is undefined and also invalid in python as var name

Title: Guess the number game