问:
Acrofields created with libre office are not code fillable unless I edit the pdf once
I am creating a form control in Libre office and am exporting the document to pdf.

Trying to set the text of the control (a textbox) using itextsharp (in other words c# program) only empties the box.

However, if I open the pdf using acrobat reader and edits the text in the box, saving the document results in a pdf where it is possible to write to that textbox.

Why do I have to do that?

##Error reproduction

Cliking the toolbar icon in libre office.

Dragging out a square in the document.

Double clicking that box, giving it the name currenttime.

Exporting to pdf:

c# code

```<code>if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
    {
        using (var fs = new FileStream(saveFileDialog1.FileName, FileMode.Create))
        {
            var reader = new PdfReader(openFileDialog1.FileName);
            {
                using (var pdfStamper = new PdfStamper(reader, fs))
                {
                    var acroFields = pdfStamper.AcroFields;

                    acroFields.SetField("currentdate", DateTime.Now.ToString());

                    pdfStamper.FormFlattening = true;
                    pdfStamper.FreeTextFlattening = true;
                    pdfStamper.Writer.CloseStream = false;
                }
            }
            reader.Close();

            fs.Close();
        }
    }
}
</code>```

#edit

Here comes textual dumps of the pdf. I have changed some binary data places with "some binary data". The textbox has been given the default value "123".

pdf after it has been created with libre office is of version 1.4

```<code>%PDF-1.4
some binary data
2 0 obj
<</Length 3 0 R/Filter/FlateDecode>>
stream
some binary data
endstream
endobj

3 0 obj
78
endobj

7 0 obj
<</Type/FontDescriptor/FontName/LiberationSans
/Flags 4
/FontBBox[-543 -303 1301 980]/ItalicAngle 0
/Ascent 905
/Descent -211
/CapHeight 979
/StemV 80
>>
endobj

8 0 obj
<</Type/Font/Subtype/TrueType/BaseFont/LiberationSans
/Encoding/WinAnsiEncoding
/FirstChar 32 /LastChar 255
/Widths[277 277 354 556 556 889 666 190 333 333 389 583 277 333 277 277
556 556 556 556 556 556 556 556 556 556 277 277 583 583 583 556
1015 666 666 722 722 666 610 777 722 277 500 666 556 833 722 777
666 777 722 666 610 722 666 943 666 666 610 277 277 277 469 556
333 556 556 500 556 556 277 556 556 222 222 500 222 833 556 556
556 556 333 500 277 556 500 722 500 500 500 333 259 333 583 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
277 333 556 556 556 556 259 556 333 736 370 556 583 333 736 552
399 548 333 333 333 576 537 333 333 333 365 556 833 833 833 610
666 666 666 666 666 666 1000 722 666 666 666 666 277 277 277 277
722 722 777 777 777 777 777 583 777 722 722 722 722 666 666 610
556 556 556 556 556 556 889 500 556 556 556 556 277 277 277 277
556 556 556 556 556 556 556 548 610 556 556 556 556 500 556 500
]
/FontDescriptor 7 0 R>>
endobj

5 0 obj
<</F1 8 0 R
>>
endobj

9 0 obj
<</Font 5 0 R
/ProcSet[/PDF/Text]
>>
endobj

1 0 obj
<</Type/Page/Parent 6 0 R/Resources 9 0 R/MediaBox[0 0 595 842]/Annots[
4 0 R ]
/Group<</S/Transparency/CS/DeviceRGB/I true>>/Contents 2 0 R>>
endobj

6 0 obj
<</Type/Pages
/Resources 9 0 R
/MediaBox[ 0 0 595 842 ]
/Kids[ 1 0 R ]
/Count 1>>
endobj

10 0 obj
<</Type/XObject
/Subtype/Form
/BBox[0 0 82.7 23.1]
/Resources 9 0 R
/Length 18
/Filter/FlateDecode
>>
stream
some binary data
endstream
endobj

4 0 obj
<</Type/Annot/Subtype/Widget/F 4
/Rect[59.6 759.3 142.5 782.2]
/FT/Tx
/P 1 0 R
/T(currenttime)
/Ff 4096
/V <FEFF003100320033>
/DV <FEFF003100320033>
/DR<</Font 5 0 R>>
/DA(0 0 0 rg /F1 12 Tf)
/AP<<
/N 10 0 R
>>
>>
endobj

11 0 obj
<</Type/Catalog/Pages 6 0 R
/OpenAction[1 0 R /XYZ null null 0]
/Lang(sv-SE)
/AcroForm<</Fields[
4 0 R
]/DR 9 0 R/NeedAppearances true>>
>>
endobj

12 0 obj
<</Creator<FEFF005700720069007400650072>
/Producer<FEFF004C0069006200720065004F0066006600690063006500200035002E0033>
/CreationDate(D:20170606104859+02'00')>>
endobj

xref
0 13
0000000000 65535 f
0000001431 00000 n
0000000019 00000 n
0000000168 00000 n
0000001843 00000 n
0000001347 00000 n
0000001590 00000 n
0000000187 00000 n
0000000357 00000 n
0000001378 00000 n
0000001688 00000 n
0000002073 00000 n
0000002231 00000 n
trailer
<</Size 13/Root 11 0 R
/Info 12 0 R
/ID [ <5F5DD24A5E7FF740A8BB6B15F88EF602>
<5F5DD24A5E7FF740A8BB6B15F88EF602> ]
/DocChecksum /BFFAD3050AA9FF87945C97B9608B3C6C
>>
startxref
2406
%%EOF
</code>```

after it has been edited in acrobat reader (I changed the default value of the textbox from "123" to "12"), it will be saved in version 1.6 and an interesting x:xmpmeta information is inserted. Also a lot of empty lines are inserted in the document. At this point, it is programmatically editable.

```<code>%PDF-1.6
%âãÏÓ
7 0 obj
<</Linearized 1/L 6449/O 9/E 2599/N 1/T 6160/H [ 451 149]>>
endobj

13 0 obj
<</DecodeParms<</Columns 4/Predictor 12>>/Filter/FlateDecode/ID[<5F5DD24A5E7FF740A8BB6B15F88EF602><FAE65369E246E7409111A7D5BDED1E6F>]/Index[7 17]/Info 6 0 R/Length 52/Prev 6161/Root 8 0 R/Size 24/Type/XRef/W[1 2 1]>>stream
some binary data
endstream
endobj
startxref
0
%%EOF

23 0 obj
<</Filter/FlateDecode/I 92/Length 65/S 38/V 69>>stream
some binary data
endstream
endobj
8 0 obj
<</AcroForm<</DA(/Helv 0 Tf 0 g )/DR 22 0 R/Fields[14 0 R]>>/Lang(sv-SE)/Metadata 1 0 R/OpenAction[9 0 R/XYZ null null 0]/Pages 5 0 R/Type/Catalog>>
endobj
9 0 obj
<</Annots[14 0 R]/Contents 12 0 R/CropBox[0 0 595 842]/Group<</CS/DeviceRGB/I true/S/Transparency>>/MediaBox[0 0 595 842]/Parent 5 0 R/Resources 22 0 R/Rotate 0/Type/Page>>
endobj
10 0 obj
<</BBox[0.0 0.0 82.9 22.9]/Filter/FlateDecode/Length 68/Resources 15 0 R>>stream
some binary data
endstream
endobj
11 0 obj
<</Filter/FlateDecode/First 66/Length 1226/N 9/Type/ObjStm>>stream
some binary data
endstream
endobj
12 0 obj
<</Filter/FlateDecode/Length 78>>stream
some binary data
endstream
endobj
1 0 obj
<</Length 3146/Subtype/XML/Type/Metadata>>stream
<?xpacket begin="ï»¿" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.4-c005 78.147326, 2012/08/23-13:03:03        ">
   <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
      <rdf:Description rdf:about=""
            xmlns:xmp="http://ns.adobe.com/xap/1.0/"
            xmlns:pdf="http://ns.adobe.com/pdf/1.3/"
            xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/"
            xmlns:dc="http://purl.org/dc/elements/1.1/">
         <xmp:CreateDate>2017-06-06T10:48:59+02:00</xmp:CreateDate>
         <xmp:CreatorTool>Writer</xmp:CreatorTool>
         <xmp:ModifyDate>2017-06-06T11:20:41+02:00</xmp:ModifyDate>
         <xmp:MetadataDate>2017-06-06T11:20:41+02:00</xmp:MetadataDate>
         <pdf:Producer>LibreOffice 5.3</pdf:Producer>
         <xmpMM:DocumentID>uuid:fcdf7344-18ca-44b6-934c-8d5ab8fc8ea3</xmpMM:DocumentID>
         <xmpMM:InstanceID>uuid:895fdc09-0aaa-4421-86b2-418c75f88d22</xmpMM:InstanceID>
         <dc:format>application/pdf</dc:format>
      </rdf:Description>
   </rdf:RDF>
</x:xmpmeta>

<?xpacket end="w"?>
endstream
endobj
2 0 obj
<</Filter/FlateDecode/First 4/Length 48/N 1/Type/ObjStm>>stream
some binary data
endstream
endobj
3 0 obj
<</Filter/FlateDecode/First 4/Length 106/N 1/Type/ObjStm>>stream
some binary data
endstream
endobj
4 0 obj
<</DecodeParms<</Columns 3/Predictor 12>>/Filter/FlateDecode/ID[<5F5DD24A5E7FF740A8BB6B15F88EF602><FAE65369E246E7409111A7D5BDED1E6F>]/Info 6 0 R/Length 37/Root 8 0 R/Size 7/Type/XRef/W[1 2 0]>>stream
some binary data
endstream
endobj
startxref
116
%%EOF
</code>```

答:
As already surmised in a comment, the problem is caused by Libre Office creating the PDF with NeedAppearances set to true in the AcroForm dictionary. Furthermore the wrong field name is used.

Field name

In your code you set the field "currentdate" while in your sample PDFs the field is called "currenttime". Obviously you have to use the correct field name.

NeedAppearances flag

This flag tells a PDF viewer that it shall construct appearance streams and appearance dictionaries for all widget annotations in the document. iText, therefore, when filling in the form field

```<code>acroFields.SetField("currentdate", DateTime.Now.ToString());
</code>```

does not create an appearance for that field - any viewer is required to construct new appearances anyways.

Unfortunately form flattening

```<code>pdfStamper.FormFlattening = true;
</code>```

is implemented by using the existing appearances and only them. As no appearance has been created when setting the field, its flattened form turns out to be empty.

(Strictly speaking this implementation of form flattening is wrong: In this case iText is the PDF processor that wants to make use of the appearances; thus, it should create all appearances here, even ignoring existing ones.)

You can fix this by telling iText to create appearances during form fill-ins in spite of the NeedAppearances flag:

```<code>using (var pdfStamper = new PdfStamper(reader, fs))
{
    var acroFields = pdfStamper.AcroFields;
    acroFields.GenerateAppearances = true;// <<<<<<<<<<<<<<<<<<

    acroFields.SetField("currenttime", DateTime.Now.ToString());

    pdfStamper.FormFlattening = true;
    pdfStamper.FreeTextFlattening = true;
    pdfStamper.Writer.CloseStream = false;
}
</code>```

After adding the marked line above, the output of the code includes the changed newly set value.

Additionally Libre Office does not embed the LiberationSans font. As I have not installed it on my system, I only see dots. I would propose you make LibreOffice embed such fonts or else use standard 14 fonts. Otherwise your PDFs won't display as desired on a number of computers.

Body:
I am creating a form control in Libre office and am exporting the document to pdf.

Trying to set the text of the control (a textbox) using itextsharp (in other words c# program) only empties the box.

However, if I open the pdf using acrobat reader and edits the text in the box, saving the document results in a pdf where it is possible to write to that textbox.

Why do I have to do that?

##Error reproduction

Cliking the toolbar icon in libre office.

Dragging out a square in the document.

Double clicking that box, giving it the name currenttime.

Exporting to pdf:

c# code

if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
    {
        using (var fs = new FileStream(saveFileDialog1.FileName, FileMode.Create))
        {
            var reader = new PdfReader(openFileDialog1.FileName);
            {
                using (var pdfStamper = new PdfStamper(reader, fs))
                {
                    var acroFields = pdfStamper.AcroFields;

                    acroFields.SetField("currentdate", DateTime.Now.ToString());

                    pdfStamper.FormFlattening = true;
                    pdfStamper.FreeTextFlattening = true;
                    pdfStamper.Writer.CloseStream = false;
                }
            }
            reader.Close();

            fs.Close();
        }
    }
}

#edit

Here comes textual dumps of the pdf. I have changed some binary data places with "some binary data". The textbox has been given the default value "123".

pdf after it has been created with libre office is of version 1.4

%PDF-1.4
some binary data
2 0 obj
<</Length 3 0 R/Filter/FlateDecode>>
stream
some binary data
endstream
endobj

3 0 obj
78
endobj

7 0 obj
<</Type/FontDescriptor/FontName/LiberationSans
/Flags 4
/FontBBox[-543 -303 1301 980]/ItalicAngle 0
/Ascent 905
/Descent -211
/CapHeight 979
/StemV 80
>>
endobj

8 0 obj
<</Type/Font/Subtype/TrueType/BaseFont/LiberationSans
/Encoding/WinAnsiEncoding
/FirstChar 32 /LastChar 255
/Widths[277 277 354 556 556 889 666 190 333 333 389 583 277 333 277 277
556 556 556 556 556 556 556 556 556 556 277 277 583 583 583 556
1015 666 666 722 722 666 610 777 722 277 500 666 556 833 722 777
666 777 722 666 610 722 666 943 666 666 610 277 277 277 469 556
333 556 556 500 556 556 277 556 556 222 222 500 222 833 556 556
556 556 333 500 277 556 500 722 500 500 500 333 259 333 583 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
277 333 556 556 556 556 259 556 333 736 370 556 583 333 736 552
399 548 333 333 333 576 537 333 333 333 365 556 833 833 833 610
666 666 666 666 666 666 1000 722 666 666 666 666 277 277 277 277
722 722 777 777 777 777 777 583 777 722 722 722 722 666 666 610
556 556 556 556 556 556 889 500 556 556 556 556 277 277 277 277
556 556 556 556 556 556 556 548 610 556 556 556 556 500 556 500
]
/FontDescriptor 7 0 R>>
endobj

5 0 obj
<</F1 8 0 R
>>
endobj

9 0 obj
<>
endobj

1 0 obj
<</Type/Page/Parent 6 0 R/Resources 9 0 R/MediaBox[0 0 595 842]/Annots[
4 0 R ]
/Group<</S/Transparency/CS/DeviceRGB/I true>>/Contents 2 0 R>>
endobj

6 0 obj
<</Type/Pages
/Resources 9 0 R
/MediaBox[ 0 0 595 842 ]
/Kids[ 1 0 R ]
/Count 1>>
endobj

10 0 obj
<</Type/XObject
/Subtype/Form
/BBox[0 0 82.7 23.1]
/Resources 9 0 R
/Length 18
/Filter/FlateDecode
>>
stream
some binary data
endstream
endobj

4 0 obj
<</Type/Annot/Subtype/Widget/F 4
/Rect[59.6 759.3 142.5 782.2]
/FT/Tx
/P 1 0 R
/T(currenttime)
/Ff 4096
/V <FEFF003100320033>
/DV <FEFF003100320033>
/DR<>
/DA(0 0 0 rg /F1 12 Tf)
/AP<<
/N 10 0 R
>>
>>
endobj

11 0 obj
<</Type/Catalog/Pages 6 0 R
/OpenAction[1 0 R /XYZ null null 0]
/Lang(sv-SE)
/AcroForm<</Fields[
4 0 R
]/DR 9 0 R/NeedAppearances true>>
>>
endobj

12 0 obj
<</Creator<FEFF005700720069007400650072>
/Producer<FEFF004C0069006200720065004F0066006600690063006500200035002E0033>
/CreationDate(D:20170606104859+02'00')>>
endobj

xref
0 13
0000000000 65535 f
0000001431 00000 n
0000000019 00000 n
0000000168 00000 n
0000001843 00000 n
0000001347 00000 n
0000001590 00000 n
0000000187 00000 n
0000000357 00000 n
0000001378 00000 n
0000001688 00000 n
0000002073 00000 n
0000002231 00000 n
trailer
<</Size 13/Root 11 0 R
/Info 12 0 R
/ID [ <5F5DD24A5E7FF740A8BB6B15F88EF602>
<5F5DD24A5E7FF740A8BB6B15F88EF602> ]
/DocChecksum /BFFAD3050AA9FF87945C97B9608B3C6C
>>
startxref
2406
%%EOF

after it has been edited in acrobat reader (I changed the default value of the textbox from "123" to "12"), it will be saved in version 1.6 and an interesting x:xmpmeta information is inserted. Also a lot of empty lines are inserted in the document. At this point, it is programmatically editable.

%PDF-1.6
%âãÏÓ
7 0 obj
<</Linearized 1/L 6449/O 9/E 2599/N 1/T 6160/H [ 451 149]>>
endobj

13 0 obj
<</DecodeParms<</Columns 4/Predictor 12>>/Filter/FlateDecode/ID[<5F5DD24A5E7FF740A8BB6B15F88EF602><FAE65369E246E7409111A7D5BDED1E6F>]/Index[7 17]/Info 6 0 R/Length 52/Prev 6161/Root 8 0 R/Size 24/Type/XRef/W[1 2 1]>>stream
some binary data
endstream
endobj
startxref
0
%%EOF

23 0 obj
<</Filter/FlateDecode/I 92/Length 65/S 38/V 69>>stream
some binary data
endstream
endobj
8 0 obj
<</AcroForm<</DA(/Helv 0 Tf 0 g )/DR 22 0 R/Fields[14 0 R]>>/Lang(sv-SE)/Metadata 1 0 R/OpenAction[9 0 R/XYZ null null 0]/Pages 5 0 R/Type/Catalog>>
endobj
9 0 obj
<</Annots[14 0 R]/Contents 12 0 R/CropBox[0 0 595 842]/Group<</CS/DeviceRGB/I true/S/Transparency>>/MediaBox[0 0 595 842]/Parent 5 0 R/Resources 22 0 R/Rotate 0/Type/Page>>
endobj
10 0 obj
<</BBox[0.0 0.0 82.9 22.9]/Filter/FlateDecode/Length 68/Resources 15 0 R>>stream
some binary data
endstream
endobj
11 0 obj
<</Filter/FlateDecode/First 66/Length 1226/N 9/Type/ObjStm>>stream
some binary data
endstream
endobj
12 0 obj
<</Filter/FlateDecode/Length 78>>stream
some binary data
endstream
endobj
1 0 obj
<</Length 3146/Subtype/XML/Type/Metadata>>stream
<?xpacket begin="ï»¿" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.4-c005 78.147326, 2012/08/23-13:03:03        ">
   <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
      <rdf:Description rdf:about=""
            xmlns:xmp="http://ns.adobe.com/xap/1.0/"
            xmlns:pdf="http://ns.adobe.com/pdf/1.3/"
            xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/"
            xmlns:dc="http://purl.org/dc/elements/1.1/">
         <xmp:CreateDate>2017-06-06T10:48:59+02:00</xmp:CreateDate>
         <xmp:CreatorTool>Writer</xmp:CreatorTool>
         <xmp:ModifyDate>2017-06-06T11:20:41+02:00</xmp:ModifyDate>
         <xmp:MetadataDate>2017-06-06T11:20:41+02:00</xmp:MetadataDate>
         <pdf:Producer>LibreOffice 5.3</pdf:Producer>
         <xmpMM:DocumentID>uuid:fcdf7344-18ca-44b6-934c-8d5ab8fc8ea3</xmpMM:DocumentID>
         <xmpMM:InstanceID>uuid:895fdc09-0aaa-4421-86b2-418c75f88d22</xmpMM:InstanceID>
         <dc:format>application/pdf</dc:format>
      </rdf:Description>
   </rdf:RDF>
</x:xmpmeta>

<?xpacket end="w"?>
endstream
endobj
2 0 obj
<</Filter/FlateDecode/First 4/Length 48/N 1/Type/ObjStm>>stream
some binary data
endstream
endobj
3 0 obj
<</Filter/FlateDecode/First 4/Length 106/N 1/Type/ObjStm>>stream
some binary data
endstream
endobj
4 0 obj
<</DecodeParms<</Columns 3/Predictor 12>>/Filter/FlateDecode/ID[<5F5DD24A5E7FF740A8BB6B15F88EF602><FAE65369E246E7409111A7D5BDED1E6F>]/Info 6 0 R/Length 37/Root 8 0 R/Size 7/Type/XRef/W[1 2 0]>>stream
some binary data
endstream
endobj
startxref
116
%%EOF

Body:
As already surmised in a comment, the problem is caused by Libre Office creating the PDF with NeedAppearances set to true in the AcroForm dictionary. Furthermore the wrong field name is used.

Field name

In your code you set the field "currentdate" while in your sample PDFs the field is called "currenttime". Obviously you have to use the correct field name.

NeedAppearances flag

This flag tells a PDF viewer that it shall construct appearance streams and appearance dictionaries for all widget annotations in the document. iText, therefore, when filling in the form field

acroFields.SetField("currentdate", DateTime.Now.ToString());

does not create an appearance for that field - any viewer is required to construct new appearances anyways.

Unfortunately form flattening

pdfStamper.FormFlattening = true;

is implemented by using the existing appearances and only them. As no appearance has been created when setting the field, its flattened form turns out to be empty.

(Strictly speaking this implementation of form flattening is wrong: In this case iText is the PDF processor that wants to make use of the appearances; thus, it should create all appearances here, even ignoring existing ones.)

You can fix this by telling iText to create appearances during form fill-ins in spite of the NeedAppearances flag:

using (var pdfStamper = new PdfStamper(reader, fs))
{
    var acroFields = pdfStamper.AcroFields;
    acroFields.GenerateAppearances = true;// <<<<<<<<<<<<<<<<<<

    acroFields.SetField("currenttime", DateTime.Now.ToString());

    pdfStamper.FormFlattening = true;
    pdfStamper.FreeTextFlattening = true;
    pdfStamper.Writer.CloseStream = false;
}

After adding the marked line above, the output of the code includes the changed newly set value.

Additionally Libre Office does not embed the LiberationSans font. As I have not installed it on my system, I only see dots. I would propose you make LibreOffice embed such fonts or else use standard 14 fonts. Otherwise your PDFs won't display as desired on a number of computers.


来源: stackexchange

问:
Persistently change Windows desktop wallpaper using python
I use the solution provided in this post to change the Windows desktop wallpaper from Python

In particular here is the code sample

```<code>import ctypes
import os
image_file = "myimage.jpg"
print("Setting the wallpaper")
SPI_SETDESKWALLPAPER = 20
ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0,  os.path.abspath(image_file) , 0)
</code>```

The problem is that the change is non persistent, in the sense that the desktop wallpaper gets reset whenever I restart my PC. How can I persistently change the Windows desktop wallpaper from Python?

I use python 3.5

答:
You need to call it like this

```<code>print("Setting the wallpaper")
SPI_SETDESKWALLPAPER = 20
SPIF_UPDATEINIFILE = 1
ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, os.path.abspath(image_file) , SPIF_UPDATEINIFILE)
</code>```

Also have a look at the related documentation

ContentLicense: CC BY-SA 3.0

Body:
I use the solution provided in this post to change the Windows desktop wallpaper from Python

In particular here is the code sample

import ctypes
import os
image_file = "myimage.jpg"
print("Setting the wallpaper")
SPI_SETDESKWALLPAPER = 20
ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0,  os.path.abspath(image_file) , 0)

The problem is that the change is non persistent, in the sense that the desktop wallpaper gets reset whenever I restart my PC. How can I persistently change the Windows desktop wallpaper from Python?

I use python 3.5

Body:
You need to call it like this

print("Setting the wallpaper")
SPI_SETDESKWALLPAPER = 20
SPIF_UPDATEINIFILE = 1
ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, os.path.abspath(image_file) , SPIF_UPDATEINIFILE)

Also have a look at the related documentation


问:
How to get qtserialport to work for NVIDIA TX1 for Native QT?
Hi I need the serial ports for my project.
I'm working with QT natively on my TX1.
I've been trying every tutorial I could find.

Is there any way I can get qtserialport to work?

please help,

Yohann Payet

答:
Answering my own question.
Run these 2 lines (terminal):

sudo apt-get install libqt5serialport5

sudo apt-get install libqt5serialport5-dev

seems to do the job.

Have a nice day


问:
Not able to make a call to javascript function from hyperlink in each row of table
I have created a dynamic table having each row as hyperlink and I am trying to call a js function passing row's text as string parameter.
But it shows(in console): {row's text} is not defined.

When I send no parameter, call to that function is made correctly, but when parameter is passed it shows error. I suspect it is expecting function which accept object as parameter, so I replaced each dot(.) with underscore(_), still it doesn't work.

Following is my code:

```<code>function showMessagePopup(data) {
$('#tbody').html("");
        for (var key in data) {
            keys.push(key);
            var keyStr=""+key;
            keyStr= keyStr.replace(/\./g, '__');
            // keyStr=keyStr.split('.').join("");
            // console.log("type of keyStr: "+keyStr+" "+typeof keyStr);
            var eachrow = '<tr>'
                + '<td><a href="javascript:showMessagePopup('+keyStr+')">' + key + '</a></td>'
                + '<td>' + data[key] + '</td>'
                + '</tr>';
            $('#tbody').append(eachrow);
        }
}

function showMessagePopup(str) {

        console.log("in showMessagePopup");
        // some operation
}
</code>```

I tried following :
keyStr= keyStr.replace(/./g, '__');
keyStr=keyStr.split('.').join("");

on printing type of keyStr:
console.log("type of "+typeof keyStr); and
it prints string, but not sure why its not calling function.

答:
Try onlick:</p>

```<code><a href="#" onlick="showMessagePopup('+keyStr+')">' + key + '</a>
</code>```

Body:
I have created a dynamic table having each row as hyperlink and I am trying to call a js function passing row's text as string parameter.
But it shows(in console): {row's text} is not defined.

When I send no parameter, call to that function is made correctly, but when parameter is passed it shows error. I suspect it is expecting function which accept object as parameter, so I replaced each dot(.) with underscore(_), still it doesn't work.

Following is my code:

function showMessagePopup(data) {
$('#tbody').html("");
        for (var key in data) {
            keys.push(key);
            var keyStr=""+key;
            keyStr= keyStr.replace(/\./g, '__');
            // keyStr=keyStr.split('.').join("");
            // console.log("type of keyStr: "+keyStr+" "+typeof keyStr);
            var eachrow = '
'
                + '' + key + '	'
                + '' + data[key] + '	'
                + '
';
            $('#tbody').append(eachrow);
        }
}

function showMessagePopup(str) {

        console.log("in showMessagePopup");
        // some operation
}

I tried following :
keyStr= keyStr.replace(/./g, '__');
keyStr=keyStr.split('.').join("");

on printing type of keyStr:
console.log("type of "+typeof keyStr); and
it prints string, but not sure why its not calling function.

Body:
Try onlick:

<a href="#" onlick="showMessagePopup('+keyStr+')">' + key + '</a>


问:
Deleting duplicate strings in array
At one point it compares array(1)compareto(array(1)) is this a problem? Amount birds is the amount of elements in array. I am trying to remove duplicate string in the array. Is it fixable or should i re approach.</p>

```<code>for (i = 0; i <= amountBirds - 1; i++)
{
    for (x = 1; x <= amountBirds; x++)
    {
        duplicate = birdArray[i].compareTo(birdArray[x]);

        if (duplicate == 0)
        {
            birdArray[i] = birdArray[x];
        }
    }
}
</code>```

答:
Try this:</p>

```<code>birdArray = new HashSet<String>(Arrays.asList(birdArray)).toArray(new String[0]);
</code>```

Title: Deleting duplicate strings in array

Body:
At one point it compares array(1)compareto(array(1)) is this a problem? Amount birds is the amount of elements in array. I am trying to remove duplicate string in the array. Is it fixable or should i re approach.

for (i = 0; i <= amountBirds - 1; i++)
{
    for (x = 1; x <= amountBirds; x++)
    {
        duplicate = birdArray[i].compareTo(birdArray[x]);

        if (duplicate == 0)
        {
            birdArray[i] = birdArray[x];
        }
    }
}

Body:
Try this:

birdArray = new HashSet<String>(Arrays.asList(birdArray)).toArray(new String[0]);


问:
LinearLayout not getting clicked
I tried a lot but, my Linearlayout as below not getting clicked  :

```<code><ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/ll_top_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:focusableInTouchMode="false"
        android:orientation="vertical">

  <LinearLayout
   android:focusableInTouchMode="true"
   android:clickable="true"
   android:id="@+id/ll_Promos"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_below="@id/vv_divider4"
   android:layout_marginTop="@dimen/dimen_5"
   android:orientation="horizontal"
   android:padding="@dimen/dimen_10">

                <ImageView
                    android:id="@+id/iv_restaurant_promo"
                    android:layout_width="@dimen/dimen_25"
                    android:layout_height="@dimen/dimen_25"
                    android:layout_gravity="center_vertical"
                    android:layout_marginLeft="@dimen/dimen_5"
                    android:layout_marginRight="@dimen/dimen_5"
                    android:src="@drawable/promos" />

                <com.app.thelist.view.CustomTextView
                    android:id="@+id/txt_restaurant_promo"
                    style="@style/RegularFont"
                    android:layout_gravity="center"
                    android:layout_marginRight="@dimen/dimen_5"
                    android:layout_weight="1"
                    android:padding="@dimen/dimen_5"
                    android:text="@string/promo"
                    android:textColor="@color/txt_sub_title"
                    android:textSize="@dimen/sp_15" />

                <ImageView
                    android:id="@+id/iv_restaurant_promo_next"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="@dimen/dimen_5"
                    android:src="@mipmap/app_icon"
                    android:visibility="gone" />

            </LinearLayout>
 </LinearLayout>
</ScrollView>
</code>```

The above is my xml file, and I have make my LinearLayout named : ll_Promos not getting clicked. I have implemented my onClick() as below in java file :

```<code>ll_promos = (LinearLayout) findViewById(R.id.ll_Promos);
        ll_promos.setOnClickListener(this);
 case R.id.ll_Promos:
            Intent intentProm = new Intent(Activity1.this, Activity2.class);
            startActivity(intentProm);
            break;
</code>```

答:
Remove

```<code>  android:focusableInTouchMode="false" // Problem starts from here
</code>```

Set whether this view can receive focus while in touch mode. Setting
  this to true will also ensure that this view is focusable.

And Add

```<code>android:focusableInTouchMode="true"
android:clickable="true"
</code>```

Title: LinearLayout not getting clicked

Body:
I tried a lot but, my Linearlayout as below not getting clicked  :

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/ll_top_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:focusableInTouchMode="false"
        android:orientation="vertical">

  <LinearLayout
   android:focusableInTouchMode="true"
   android:clickable="true"
   android:id="@+id/ll_Promos"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_below="@id/vv_divider4"
   android:layout_marginTop="@dimen/dimen_5"
   android:orientation="horizontal"
   android:padding="@dimen/dimen_10">

                <ImageView
                    android:id="@+id/iv_restaurant_promo"
                    android:layout_width="@dimen/dimen_25"
                    android:layout_height="@dimen/dimen_25"
                    android:layout_gravity="center_vertical"
                    android:layout_marginLeft="@dimen/dimen_5"
                    android:layout_marginRight="@dimen/dimen_5"
                    android:src="@drawable/promos" />

                <com.app.thelist.view.CustomTextView
                    android:id="@+id/txt_restaurant_promo"
                    style="@style/RegularFont"
                    android:layout_gravity="center"
                    android:layout_marginRight="@dimen/dimen_5"
                    android:layout_weight="1"
                    android:padding="@dimen/dimen_5"
                    android:text="@string/promo"
                    android:textColor="@color/txt_sub_title"
                    android:textSize="@dimen/sp_15" />

                <ImageView
                    android:id="@+id/iv_restaurant_promo_next"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="@dimen/dimen_5"
                    android:src="@mipmap/app_icon"
                    android:visibility="gone" />

            </LinearLayout>
 </LinearLayout>
</ScrollView>

The above is my xml file, and I have make my LinearLayout named : ll_Promos not getting clicked. I have implemented my onClick() as below in java file :

ll_promos = (LinearLayout) findViewById(R.id.ll_Promos);
        ll_promos.setOnClickListener(this);
 case R.id.ll_Promos:
            Intent intentProm = new Intent(Activity1.this, Activity2.class);
            startActivity(intentProm);
            break;

Body:
Remove

  android:focusableInTouchMode="false" // Problem starts from here

Set whether this view can receive focus while in touch mode. Setting
  this to true will also ensure that this view is focusable.

And Add

android:focusableInTouchMode="true"
android:clickable="true"


问:
How to fix a Database Error and ghost migration error in Django?
I am getting an DatabaseError saying no column named playlist exists and I'm trying to figure out how to fix it.  I'm using South. I deleted the old files in the my migrations folder and ran:

```<code>python manage.py schemamigration app_name --initial
python manage.py migrate reserve
</code>```

I get this error when I do that:

```<code>south.exceptions.GhostMigrations:

 ! These migrations are in the database but not on disk:
    <reserve: 0002_initial>
 ! I'm not trusting myself; either fix this yourself by fiddling
 ! with the south_migrationhistory table, or pass --delete-ghost-migrations
 ! to South to have it delete ALL of these records (this may not be good).
</code>```

I'm not sure how to get rid of this error, since in my migrations folder I only have init.py(c) and 0001_initial.py(c); I don't have 0002 migration file anymore.

When I try runserver and click "add playlist" in the admin, this is when I get the DatabaseError.  If it helps, my models.py is:

```<code>class UserProfile(models.Model):
    user = models.OneToOneField(User)
    def __unicode__(self):
        return self.user

def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)

post_save.connect(create_user_profile, sender=User)

class Playlist(models.Model):
    playlist = models.CharField('Playlist', max_length = 2000, null=True, blank=True)
    def __unicode__(self):
        return self.playlist

class Video(models.Model):
    video_url = models.URLField('Link to video', max_length = 200, null=True, blank=True)
    def __unicode__(self):
        return self.video_url

class UserPlaylist(models.Model):
    profile = models.ForeignKey(User)
    playlist = models.ForeignKey(Playlist)
    def __unicode__(self):
        return self.playlist

class Videoplaylist(models.Model):
    video = models.ForeignKey(Video)
    playlist = models.ForeignKey(UserPlaylist)
    def __unicode__(self):
        return self.playlist
</code>```

Any advice on how to fix this?

答:
Just run the command where manage.py file is present in your directory

./manage.py migrate appname --delete-ghost-migrations

Body:
I am getting an DatabaseError saying no column named playlist exists and I'm trying to figure out how to fix it.  I'm using South. I deleted the old files in the my migrations folder and ran:

python manage.py schemamigration app_name --initial
python manage.py migrate reserve

I get this error when I do that:

south.exceptions.GhostMigrations:

 ! These migrations are in the database but not on disk:
    <reserve: 0002_initial>
 ! I'm not trusting myself; either fix this yourself by fiddling
 ! with the south_migrationhistory table, or pass --delete-ghost-migrations
 ! to South to have it delete ALL of these records (this may not be good).

I'm not sure how to get rid of this error, since in my migrations folder I only have init.py(c) and 0001_initial.py(c); I don't have 0002 migration file anymore.

When I try runserver and click "add playlist" in the admin, this is when I get the DatabaseError.  If it helps, my models.py is:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    def __unicode__(self):
        return self.user

def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)

post_save.connect(create_user_profile, sender=User)

class Playlist(models.Model):
    playlist = models.CharField('Playlist', max_length = 2000, null=True, blank=True)
    def __unicode__(self):
        return self.playlist

class Video(models.Model):
    video_url = models.URLField('Link to video', max_length = 200, null=True, blank=True)
    def __unicode__(self):
        return self.video_url

class UserPlaylist(models.Model):
    profile = models.ForeignKey(User)
    playlist = models.ForeignKey(Playlist)
    def __unicode__(self):
        return self.playlist

class Videoplaylist(models.Model):
    video = models.ForeignKey(Video)
    playlist = models.ForeignKey(UserPlaylist)
    def __unicode__(self):
        return self.playlist

Any advice on how to fix this?


答: Try Set or LinkedHashSet . Convert your arraylist into Set , It will automatically remove the duplicate from List as Set does not allow Duplicate value.  but Remember it is a Collection rather than a List.</p>

Title: Deleting duplicate strings in array


问:
How to use increment method for findElement code
I'm stuck with how to implicate increment into find element code

this is the code

```<code>driver.findElement(By.xpath("(//a[@class='_8mlbc _vbtk2 _t5r8b'])[13]")).click();
</code>```

I need to change 13 into 13 + 1 and 14 + 1 and so on every time loop happens.

答:
I would go with something like this:

```<code>int ord = 13;
String xpath = "(//a[@class='_8mlbc _vbtk2 _t5r8b'])[%s]";
// some sort of loop starts, e.g. while, for, etc
    driver.findElement(By.xpath(String.format(xpath, ord))).click();
    ord++;
// the loop ends
</code>```

Explanation: String.format() lets you use printf -like string templates. In your case the variable part of the template is the ordinal number, ord. You can increment it with ord++ whenever it seems necessary.

Body:
I'm stuck with how to implicate increment into find element code

this is the code

driver.findElement(By.xpath("(//a[@class='_8mlbc _vbtk2 _t5r8b'])[13]")).click();

I need to change 13 into 13 + 1 and 14 + 1 and so on every time loop happens.

Body:
I would go with something like this:

int ord = 13;
String xpath = "(//a[@class='_8mlbc _vbtk2 _t5r8b'])[%s]";
// some sort of loop starts, e.g. while, for, etc
    driver.findElement(By.xpath(String.format(xpath, ord))).click();
    ord++;
// the loop ends

Explanation: String.format() lets you use printf -like string templates. In your case the variable part of the template is the ordinal number, ord. You can increment it with ord++ whenever it seems necessary.


问:
What versions of avro and parquet formats does Spark support?
Does Spark 2.0 support avro and parquet files? What versions?

I have downloaded spark-avro_2.10-0.1.jar and got this error during load:

```<code>Name: java.lang.IncompatibleClassChangeError
Message: org.apache.spark.sql.sources.TableScan
StackTrace:   at java.lang.ClassLoader.defineClassImpl(Native Method)
  at java.lang.ClassLoader.defineClass(ClassLoader.java:349)
  at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:154)
  at java.net.URLClassLoader.defineClass(URLClassLoader.java:727)
  at java.net.URLClassLoader.access$400(URLClassLoader.java:95)
  at java.net.URLClassLoader$ClassFinder.run(URLClassLoader.java:1182)
  at java.security.AccessController.doPrivileged(AccessController.java:686)
  at java.net.URLClassLoader.findClass(URLClassLoader.java:602)
</code>```

答:
Does spark 2.0 supports avro and parquet files?

Avro format is not supportd in Spark 2.x out of the box. You have to use an external package, e.g. spark-avro.

```<code>Name: java.lang.IncompatibleClassChangeError
Message: org.apache.spark.sql.sources.TableScan
</code>```

The reason for java.lang.IncompatibleClassChangeError is that you used spark-avro_2.10-0.1.jar that was compiled for Scala 2.10, but Spark 2.0 uses Scala 2.11 by default. This inevitably leads to this IncompatibleClassChangeError error.

You should rather load the spark-avro package using --packages command line option (as described in the official documentation of spark-avro in With spark-shell or spark-submit):

```<code>$ bin/spark-shell --packages com.databricks:spark-avro_2.11:3.2.0
</code>```

using --packages ensures that this library and its dependencies will be added to the classpath. The --packages argument can also be used with bin/spark-submit.

Parquet format is the default format when loading or saving datasets.

```<code>// loading parquet datasets
spark.read.load

// saving in parquet format
mydataset.write.save
</code>```

You may want to read up on Parquet Files support in the official documentation:

Spark SQL provides support for both reading and writing Parquet files that automatically preserves the schema of the original data.

Parquet 1.8.2 is used (as you can see in Spark's pom.xml)

Body:
Does Spark 2.0 support avro and parquet files? What versions?

I have downloaded spark-avro_2.10-0.1.jar and got this error during load:

Name: java.lang.IncompatibleClassChangeError
Message: org.apache.spark.sql.sources.TableScan
StackTrace:   at java.lang.ClassLoader.defineClassImpl(Native Method)
  at java.lang.ClassLoader.defineClass(ClassLoader.java:349)
  at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:154)
  at java.net.URLClassLoader.defineClass(URLClassLoader.java:727)
  at java.net.URLClassLoader.access$400(URLClassLoader.java:95)
  at java.net.URLClassLoader$ClassFinder.run(URLClassLoader.java:1182)
  at java.security.AccessController.doPrivileged(AccessController.java:686)
  at java.net.URLClassLoader.findClass(URLClassLoader.java:602)

Body:
Does spark 2.0 supports avro and parquet files?

Avro format is not supportd in Spark 2.x out of the box. You have to use an external package, e.g. spark-avro.

Name: java.lang.IncompatibleClassChangeError
Message: org.apache.spark.sql.sources.TableScan

The reason for java.lang.IncompatibleClassChangeError is that you used spark-avro_2.10-0.1.jar that was compiled for Scala 2.10, but Spark 2.0 uses Scala 2.11 by default. This inevitably leads to this IncompatibleClassChangeError error.

You should rather load the spark-avro package using --packages command line option (as described in the official documentation of spark-avro in With spark-shell or spark-submit):

$ bin/spark-shell --packages com.databricks:spark-avro_2.11:3.2.0

using --packages ensures that this library and its dependencies will be added to the classpath. The --packages argument can also be used with bin/spark-submit.

Parquet format is the default format when loading or saving datasets.

// loading parquet datasets
spark.read.load

// saving in parquet format
mydataset.write.save

You may want to read up on Parquet Files support in the official documentation:

Spark SQL provides support for both reading and writing Parquet files that automatically preserves the schema of the original data.

Parquet 1.8.2 is used (as you can see in Spark's pom.xml)


问:
How to Learn MS SQL Server 2005?
I would like to start learning SQL Server 2005 on my own.  Can anyone recommend good books or websites that will be a good start for me?</p>

答:
If you want to gain an good understanding of SQL Server end-to-end, I have found Robert Vieira's books on SQL Server to be useful.

Here is one I recommend.

It is a good book and I recommend it for assimilating the theory.

If you need a good reference book I have found that Murach's books on SQL server to be useful.

Here is one I recommend.

This a good book for quick "cook book" type solutions.

OwnerDisplayName: Craig G

ContentLicense: CC BY-SA 2.5

Title: How to Learn MS SQL Server 2005?

LastEditorDisplayName: Jonathan Leffler

OwnerDisplayName: Andy Webb


问:
ExecuteCore() vs OnActionExecuting(ActionExecutingContext filterContext)?
Just curious, they sound similar. What are the differences between ExecuteCore() vs OnActionExecuting(ActionExecutingContext filterContext)?

In what situations would one be more useful over the other?

答:
ExecuteCore is invoked just after the controller has been initialized while OnActionExecuting happens at a later stage of the execution pipeline and is called immediately before the controller action is invoked. In the second method you can directly manipulate the actionresult and short-circuit the execution of the action by redirecting for example to some other action:</p>

```<code>filterContext.Result = ...
</code>```

Body:
ExecuteCore is invoked just after the controller has been initialized while OnActionExecuting happens at a later stage of the execution pipeline and is called immediately before the controller action is invoked. In the second method you can directly manipulate the actionresult and short-circuit the execution of the action by redirecting for example to some other action:

filterContext.Result = ...


问:
itextsharp c# need a perfect method for page break
I am using itextsharp library.I design an HTML page and convert to PDF .in that case some table are not split perfectly and row also not split correctly

table.keepTogether;
 table.splitRows;
 table.splitLate

I try this extension but it does not work correctly it mess my CSS and data in PDF. if you have method..answer me:)

答:
finally i got it

```<code>public class TableProcessor : Table
{
    const string NO_ROW_SPLIT = "no-row-split";

    public override IList<IElement> End(IWorkerContext ctx, Tag tag, IList<IElement> currentContent)
    {
        IList<IElement> result = base.End(ctx, tag, currentContent);
        var table = (PdfPTable)result[0];

        if (tag.Attributes.ContainsKey(NO_ROW_SPLIT))
        {
            // if not set,  table **may** be forwarded to next page
            table.KeepTogether = false;
            // next two properties keep <tr> together if possible
            table.SplitRows = true;
            table.SplitLate = true;
        }
        return new List<IElement>() { table };
    }
}
</code>```

use this class and

```<code> var tagfac = Tags.GetHtmlTagProcessorFactory();
                tagfac.AddProcessor(new TableProcessor(), new string[] { HTML.Tag.TABLE });

                htmlContext.SetTagFactory(tagfac);
</code>```

integrate this method with htmlpipeline context

this method every time run when the tag hasno-row-split.if it contain key it will make kept by keep together keyword to make page breaking

html

```<code><table no-row-split style="width:100%">
  <tr>
    <td>
   </td>
  </tr>
</table>
</code>```

Body:
finally i got it

public class TableProcessor : Table
{
    const string NO_ROW_SPLIT = "no-row-split";

    public override IList<IElement> End(IWorkerContext ctx, Tag tag, IList<IElement> currentContent)
    {
        IList<IElement> result = base.End(ctx, tag, currentContent);
        var table = (PdfPTable)result[0];

        if (tag.Attributes.ContainsKey(NO_ROW_SPLIT))
        {
            // if not set,  table **may** be forwarded to next page
            table.KeepTogether = false;
            // next two properties keep <tr> together if possible
            table.SplitRows = true;
            table.SplitLate = true;
        }
        return new List<IElement>() { table };
    }
}

use this class and

 var tagfac = Tags.GetHtmlTagProcessorFactory();
                tagfac.AddProcessor(new TableProcessor(), new string[] { HTML.Tag.TABLE });

                htmlContext.SetTagFactory(tagfac);

integrate this method with htmlpipeline context

this method every time run when the tag hasno-row-split.if it contain key it will make kept by keep together keyword to make page breaking

html

<table no-row-split style="width:100%">
  <tr>
    <td>
   </td>
  </tr>
</table>


问:
IntelliJ and Android Gradle dependencies - unable to find module
I have following directory structure:

```<code>D:\PROJECT
+---javaGradleProject1
+---javaGradleProject2
+---javaGradleProject3
\---AndroidProject
    |   build.gradle
    |   settings.gradle
    \---AndroidModule
            build.gradle
</code>```

Android module depends on all of java gradle projects that are at the same level in root directory as AndroidProject.

In AndroidProject/settings.gradle I have:

```<code>include ':AndroidModule'

include 'javaGradleProject1'
project(':javaGradleProject1').projectDir = new File(rootDir, '../javaGradleProject1')

include 'javaGradleProject2'
project(':javaGradleProject2').projectDir = new File(rootDir, '../javaGradleProject2')

include 'javaGradleProject2'
project(':javaGradleProject2').projectDir = new File(rootDir, '../javaGradleProject2')
</code>```

And then in AndroidProject/AndroidModule/build.gradle I have dependencies set like this:

```<code>compile project(':javaGradleProject1')
compile project(':javaGradleProject2')
compile project(':javaGradleProject3')
</code>```

This structure of dependency perfectly works and project builds when I invoke

```<code>gradle build
</code>```

on AndroidProject/build.gradle.

But when I try to synchronize my IntelliJ with current gradle dependency settings I receive

```<code>Error: Unable to find module with Gradle path ':javaGradleProject1'
Error: Unable to find module with Gradle path ':javaGradleProject2'
Error: Unable to find module with Gradle path ':javaGradleProject3'
</code>```

and because of that my project cannot be run from Run Configurations (it does not compile at all in IDE). I was trying to add these dependencies manually by hitting F4 and module dependencies but after synchronization all of my changes are overwritten (actually, IntelliJ just removes it).

Is there anything wrong in my gradle structure?

I have tested it on IntelliJ IDEA 14.1.4 and Android Studio 1.3.

答: In my case I had to change the external module name to lowercase only.</p>

Body:
I have following directory structure:

D:\PROJECT
+---javaGradleProject1
+---javaGradleProject2
+---javaGradleProject3
\---AndroidProject
    |   build.gradle
    |   settings.gradle
    \---AndroidModule
            build.gradle

Android module depends on all of java gradle projects that are at the same level in root directory as AndroidProject.

In AndroidProject/settings.gradle I have:

include ':AndroidModule'

include 'javaGradleProject1'
project(':javaGradleProject1').projectDir = new File(rootDir, '../javaGradleProject1')

include 'javaGradleProject2'
project(':javaGradleProject2').projectDir = new File(rootDir, '../javaGradleProject2')

include 'javaGradleProject2'
project(':javaGradleProject2').projectDir = new File(rootDir, '../javaGradleProject2')

And then in AndroidProject/AndroidModule/build.gradle I have dependencies set like this:

compile project(':javaGradleProject1')
compile project(':javaGradleProject2')
compile project(':javaGradleProject3')

This structure of dependency perfectly works and project builds when I invoke

gradle build

on AndroidProject/build.gradle.

But when I try to synchronize my IntelliJ with current gradle dependency settings I receive

Error: Unable to find module with Gradle path ':javaGradleProject1'
Error: Unable to find module with Gradle path ':javaGradleProject2'
Error: Unable to find module with Gradle path ':javaGradleProject3'

and because of that my project cannot be run from Run Configurations (it does not compile at all in IDE). I was trying to add these dependencies manually by hitting F4 and module dependencies but after synchronization all of my changes are overwritten (actually, IntelliJ just removes it).

Is there anything wrong in my gradle structure?

I have tested it on IntelliJ IDEA 14.1.4 and Android Studio 1.3.


问:
How to make use of jquery script in react component?
```<code><script>
    $(document).ready(function() {
        var source;
        var destination;
        var fn = function(event, ui) {
            toDrop = $(ui.draggable).clone();
            if ($("#droppable").find("li[uniqueIdentity=" + toDrop.attr("uniqueIdentity") + "]").length <= 0) {
                $("#droppable").append(toDrop);
            }
            else
                return false;
        };
        $("#draggable li").draggable({
            helper: 'clone'
        });
        $("#droppable").droppable({ drop: fn });
    });
</script>
</code>```

I am using drap and drop feature by using this jquuey in html its working properly how to make use of this in react component.

答:
you can import the npm dependency as

```<code>npm install jquery
</code>```

and then in your component you can import it as

```<code>import $ from "jquery"
</code>```

and then you can write your code using$ as $(document).ready(function() {)};

Here is a workaround for jquery in npm https://github.com/reactjs/react-rails/issues/209

Body:
you can import the npm dependency as

npm install jquery

and then in your component you can import it as

import $ from "jquery"

and then you can write your code using$ as $(document).ready(function() {)};

Here is a workaround for jquery in npm https://github.com/reactjs/react-rails/issues/209


问:
ERROR: In exporting mysqli query results into excel using php
I am trying to export MySQL query results into excel. Therefore I wrote the following PHP script:

```<code><?php
$conn = mysqli_connect('localhost','root','xyz','abc');
$select = "SELECT * FROM table_name";
$export = mysqli_query( $conn,$select) or die ( "Sql error : " .
mysqli_error($conn) );
$fields = mysqli_num_rows ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
//But this line giving error continuously
$header .= mysqli_fetch_field_direct($export,$i) . "\t";
 }
while( $row = mysqli_fetch_row( $export ) )
{
 $line = '';
 foreach( $row as $value )
 {
  if ( ( !isset( $value ) ) || ( $value == "" ) )
  {
    $value = "\t";
  }
  else
  {
     $value = str_replace( '"' , '""' , $value );
     $value = '"' . $value . '"' . "\t";
  }
  $line .= $value;
 }
$data .= trim( $line ) . "\n";
 }
$data = str_replace( "\r" , "" , $data );
if ( $data == "" )
{
  $data = "\n(0) Records Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=random.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
</code>```

But I am getting this error:

```<code>PHP Recoverable fatal error:
Object of class stdClass could not be converted to string in this line
$header .= mysqli_fetch_field_direct($export,$i) . "\t";
</code>```

and now I'm facing problem in debugging this code.

答:
Look to description and examples.

This mysqli_fetch_field_direct returns an object

Or try typecasting : (string)mysqli_fetch_field_direct($export,$i)

http://php.net/manual/en/mysqli-result.fetch-field-direct.php

ContentLicense: CC BY-SA 4.0

Body:
I am trying to export MySQL query results into excel. Therefore I wrote the following PHP script:

<?php
$conn = mysqli_connect('localhost','root','xyz','abc');
$select = "SELECT * FROM table_name";
$export = mysqli_query( $conn,$select) or die ( "Sql error : " .
mysqli_error($conn) );
$fields = mysqli_num_rows ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
//But this line giving error continuously
$header .= mysqli_fetch_field_direct($export,$i) . "\t";
 }
while( $row = mysqli_fetch_row( $export ) )
{
 $line = '';
 foreach( $row as $value )
 {
  if ( ( !isset( $value ) ) || ( $value == "" ) )
  {
    $value = "\t";
  }
  else
  {
     $value = str_replace( '"' , '""' , $value );
     $value = '"' . $value . '"' . "\t";
  }
  $line .= $value;
 }
$data .= trim( $line ) . "\n";
 }
$data = str_replace( "\r" , "" , $data );
if ( $data == "" )
{
  $data = "\n(0) Records Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=random.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";

But I am getting this error:

PHP Recoverable fatal error:
Object of class stdClass could not be converted to string in this line
$header .= mysqli_fetch_field_direct($export,$i) . "\t";

and now I'm facing problem in debugging this code.


问:
HTML removing all events from element
I have some javascript functions in my main program(im not able to modify this code) and some of them are not needed. I want to add new javascript and disable unnecessary events(for example onClick).
I tried someething like this:

```<code>function disableClickEvent(){
    var elems = document.body.getElementsByTagName("a");
    for (i = 0; i < elems.length; i++) {
        for (var key in toDisableMap) {
             if(elems[i].innerHTML == key ){
                 elems[i].unbind();
                 break;
             }
         }
    }
}
</code>```

but there is an error (in console):

```<code>jQuery.Deferred exception: a[i].unbind is not a function disableClickEvent
</code>```

I am not sure that unbind is right way for disable events. How is it possible to solve this problem?

答:
Check this if it works.Used  $(elems[i]).removeAttr('onclick'); to remove the click event from the anchor tag. Once the button pressed the click event from the anchor tag will be removed

function disableClickEvent(){

    var elems = document.body.getElementsByTagName("a");
    for (i = 0; i < elems.length; i++) {

         $(elems[i]).removeAttr('onclick');

       /* for (var key in toDisableMap) {
             if(elems[i].innerHTML == key ){
                 elems[i].unbind();
                 break;
             }
         }*/
    }
}

function clickevent(event){
  event.preventDefault();
  console.log("clicked")
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="disableClickEvent()"> Remove events </button>

Anchor tag click</code>```

Title: HTML removing all events from element

Body:
I have some javascript functions in my main program(im not able to modify this code) and some of them are not needed. I want to add new javascript and disable unnecessary events(for example onClick).
I tried someething like this:

function disableClickEvent(){
    var elems = document.body.getElementsByTagName("a");
    for (i = 0; i < elems.length; i++) {
        for (var key in toDisableMap) {
             if(elems[i].innerHTML == key ){
                 elems[i].unbind();
                 break;
             }
         }
    }
}

but there is an error (in console):

jQuery.Deferred exception: a[i].unbind is not a function disableClickEvent

I am not sure that unbind is right way for disable events. How is it possible to solve this problem?

Body:
Check this if it works.Used  $(elems[i]).removeAttr('onclick'); to remove the click event from the anchor tag. Once the button pressed the click event from the anchor tag will be removed

function disableClickEvent(){

    var elems = document.body.getElementsByTagName("a");
    for (i = 0; i < elems.length; i++) {

         $(elems[i]).removeAttr('onclick');

       /* for (var key in toDisableMap) {
             if(elems[i].innerHTML == key ){
                 elems[i].unbind();
                 break;
             }
         }*/
    }
}

function clickevent(event){
  event.preventDefault();
  console.log("clicked")
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="disableClickEvent()"> Remove events </button>

<a href="" onclick="clickevent(event)">Anchor tag click</a>


问:
c# Windows Service Console.Writeln
I wrote, installed, and successfully started a Windows Service in c# that does nothing :)  Initially I just want echo stuff to the console, db queries the service makes etc.  I used the OnStart in my service, but from a cmd prompt when I do a     net start "My Service"  where do these messages show up?

I'm open to better ways.  I'm new to this and feeling my way through it step by step by echoing back to the console my progress.  Should I echo to the event log instead? How do I do that?(I know, I know, google it)

```<code> protected override void OnStart(string[] args)
    {
        base.OnStart(args);
        Console.WriteLine("Sham-Wow!");
    }
</code>```

答:
If you want to run your application as a console application (so you can see your console output) or as a service you can achieve this with the following:

Ensure that your application is compiled as a Console application.

Alter the application's Main method so that you can branch for service or console execution.

Run your application as follows to get a console "myservice.exe /console".

It's been years since I have done this so might need a little tweaking, but something like follows:

```<code>static void Main(string[]] args)
{
    if (args.Length == 0)
    {
          //Service entry
          System.ServiceProcess.ServiceBase[] services;
          services = new System.ServiceProcess.ServiceBase[] { new WinService1() };
          System.ServiceProcess.ServiceBase.Run(services);
    }
    else
    {
          //Console entry
          OnStart(args);
    }
}

protected override void OnStart(string[] args)
{
    base.OnStart(args);
    Console.WriteLine("Sham-Wow!");
}
</code>```

This is fine for some early experimentation, but I would recommend Log4Net once you have got your head around things.

Title: c# Windows Service Console.Writeln

Body:
I wrote, installed, and successfully started a Windows Service in c# that does nothing :)  Initially I just want echo stuff to the console, db queries the service makes etc.  I used the OnStart in my service, but from a cmd prompt when I do a     net start "My Service"  where do these messages show up?

I'm open to better ways.  I'm new to this and feeling my way through it step by step by echoing back to the console my progress.  Should I echo to the event log instead? How do I do that?(I know, I know, google it)

 protected override void OnStart(string[] args)
    {
        base.OnStart(args);
        Console.WriteLine("Sham-Wow!");
    }

Body:
If you want to run your application as a console application (so you can see your console output) or as a service you can achieve this with the following:

Ensure that your application is compiled as a Console application.

Alter the application's Main method so that you can branch for service or console execution.

Run your application as follows to get a console "myservice.exe /console".

It's been years since I have done this so might need a little tweaking, but something like follows:

static void Main(string[]] args)
{
    if (args.Length == 0)
    {
          //Service entry
          System.ServiceProcess.ServiceBase[] services;
          services = new System.ServiceProcess.ServiceBase[] { new WinService1() };
          System.ServiceProcess.ServiceBase.Run(services);
    }
    else
    {
          //Console entry
          OnStart(args);
    }
}

protected override void OnStart(string[] args)
{
    base.OnStart(args);
    Console.WriteLine("Sham-Wow!");
}

This is fine for some early experimentation, but I would recommend Log4Net once you have got your head around things.


问:
Php: How can one automate a script to change dates everyday?
```<code>#!/usr/bin/php

<?php
$username = "user";
$password = "pass";
$url      = '10.168.8.666';
// Make our connection
$connection = ssh2_connect($url);

// Authenticate
if (!ssh2_auth_password($connection, $username, $password))
     {echo('Unable to connect.');}

// Create our SFTP resource
if (!$sftp = ssh2_sftp($connection))
     {echo ('Unable to create SFTP connection.');}

$localDir  = 'file:///home/batman/Downloads/dbs';
$remoteDir = '/home/batbackup/Dropbox/dbs';
// download all the files
$files = scandir ('ssh2.sftp://' . $sftp . $remoteDir);
if (!empty($files)) {
  foreach ($files as $file) {
    if ($file != '.' && $file != '..') {
        if (substr($file, 0, 11)=='07-Jun-2017'){
            # code...
              ssh2_scp_recv($connection, "$remoteDir/$file", "$localDir/$file");

        }

    }
  }
}
?>
</code>```

I use this script to download backups from an sftp server everyday but i ve to manually change the date (in bold) in the script everyday. Question: is there a way i can make the script to change the date automatically so that i can set up a cron job?

答:
Replace your date with

```<code>date('d-M-Y')
</code>```

http://php.net/manual/fr/function.date.php

This will take server current time.

Body:
#!/usr/bin/php

<?php
$username = "user";
$password = "pass";
$url      = '10.168.8.666';
// Make our connection
$connection = ssh2_connect($url);

// Authenticate
if (!ssh2_auth_password($connection, $username, $password))
     {echo('Unable to connect.');}

// Create our SFTP resource
if (!$sftp = ssh2_sftp($connection))
     {echo ('Unable to create SFTP connection.');}

$localDir  = 'file:///home/batman/Downloads/dbs';
$remoteDir = '/home/batbackup/Dropbox/dbs';
// download all the files
$files = scandir ('ssh2.sftp://' . $sftp . $remoteDir);
if (!empty($files)) {
  foreach ($files as $file) {
    if ($file != '.' && $file != '..') {
        if (substr($file, 0, 11)=='07-Jun-2017'){
            # code...
              ssh2_scp_recv($connection, "$remoteDir/$file", "$localDir/$file");

        }

    }
  }
}
?>

I use this script to download backups from an sftp server everyday but i ve to manually change the date (in bold) in the script everyday. Question: is there a way i can make the script to change the date automatically so that i can set up a cron job?

Body:
Replace your date with

date('d-M-Y')

http://php.net/manual/fr/function.date.php

This will take server current time.


问:
I could't insert data into MySQL table
I am facing the issue only when I try to insert data, where the same code runs perfectly well when I try inserting data to another table with different set of values.

```<code><?php

class crud
{
    private $db;

    function __construct($DB_con)
    {
        $this->db = $DB_con;
    }

    public function create($atitle,$agen,$ams,$adob,$afn,$aln,$acob,$acoc,$aemail,$amob,$aaddr,$amesse)    {
        try
        {
            $stmt = $this->db->prepare("INSERT INTO contacts(title,gen,ms,dob,fn,ln,cob,coc,email,mob,addr,messe) VALUES(:atitle,:agen,:ams,:adob,:afn,:aln,:acob,:acoc,:aemail,:amob,:aaddr,:amesse)");
            $stmt->bindparam(":atitle",$atitle);
            $stmt->bindparam(":agen",$agen);
            $stmt->bindparam(":ams",$ams);
            $stmt->bindparam(":adob",$adob);
            $stmt->bindparam(":afn",$afn);
            $stmt->bindparam(":aln",$aln);
            $stmt->bindparam(":acob",$acob);
            $stmt->bindparam(":acoc",$acoc);
            $stmt->bindparam(":aemail",$aemail);
            $stmt->bindparam(":amob",$amob);
            $stmt->bindparam(":aaddr",$aaddr);
            $stmt->bindparam(":amesse",$amesse);
            $stmt->execute();
            return true;
        }
        catch(PDOException $e)
        {
            echo $e->getMessage();
            return false;
        }

    }
}
</code>```

Above is the class used to insert data.

```<code><?php
include_once 'dbconfig.php';
if(isset($_POST['btn-save']))
{
    $atitle = $_POST['actitle'];
    $agen = $_POST['acgen'];
    $ams = $_POST['acms'];
    $acdate = $_POST['acdate'];
    $adob = date('Y-m-d', strtotime(str_replace('-', '/', $acdate)));
    $afn = $_POST['acfn'];
    $aln = $_POST['acln'];
    $acob = $_POST['accob'];
    $acoc = $_POST['accoc'];
    $aemail = $_POST['aemail'];
    $amob = $_POST['acmob'];
    $aaddr = $_POST['acaddr'];
    $amesse = $_POST['acmesse'];

    if($crud->create($atitle,$agen,$ams,$adob,$afn,$aln,$acob,$acoc,$aemail,$amob,$aaddr,$amesse))
    {
        header("Location: add-con.php?inserted");
    }
    else
    {
        header("Location: add-con.php?failure");
    }
}
?>
    <?php include_once 'header.php'; ?>
    <div class="clearfix"></div>

    <?php
if(isset($_GET['inserted']))
{
    ?>
    <div class="container">
        <div class="alert alert-info">
            <strong>WOW!</strong> Record was inserted successfully <a href="index.php">HOME</a>!
        </div>
    </div>
    <?php
}
else if(isset($_GET['failure']))
{
    ?>
        <div class="container">
            <div class="alert alert-warning">
                <strong>SORRY!</strong> ERROR while inserting record !
            </div>
        </div>
        <?php
}
?>

        <div class="clearfix"></div><br />

        <div class="container">

            <form method='post'>

                <table class='table table-bordered'>

                    <tr>
                        <td>Title</td>
                        <td><input type='text' name='actitle' class='form-control' required></td>
                    </tr>
                    <tr>
                        <td>Gender</td>
                        <td><input type='text' name='acgen' class='form-control' required></td>
                    </tr>
                    <tr>
                        <td>Marital Status</td>
                        <td><input type='text' name='acms' class='form-control' required></td>
                    </tr>
                    <tr>
                        <td>DOB</td>
                        <td><input type='text' name='acdate' class='form-control' required></td>
                    </tr>
                    <tr>
                        <td>First Name</td>
                        <td><input type='text' name='acfn' class='form-control' required></td>
                    </tr>
                    <tr>
                        <td>Last Name</td>
                        <td><input type='text' name='acln' class='form-control' required></td>
                    </tr>
                    <tr>
                        <td>Country of Birth</td>
                        <td><input type='text' name='accob' class='form-control' required></td>
                    </tr>
                    <tr>
                        <td>COC</td>
                        <td><input type='text' name='accoc' class='form-control' required></td>
                    </tr>
                    <tr>
                        <td>email</td>
                        <td><input type='text' name='acemail' class='form-control' required></td>
                    </tr>
                    <tr>
                        <td>mob</td>
                        <td><input type='text' name='acmob' class='form-control' required></td>
                    </tr>
                    <tr>
                        <td>address</td>
                        <td><input type='text' name='acaddr' class='form-control' required></td>
                    </tr>

                    <tr>
                        <td>messege</td>
                        <td><input type='text' name='acmesse' class='form-control' required></td>
                    </tr>
                    <td colspan="2">
                        <button type="submit" class="btn btn-primary" name="btn-save">
            <span class="glyphicon glyphicon-plus"></span> Create New Record
            </button>
                        <a href="index.php" class="btn btn-large btn-success"><i class="glyphicon glyphicon-backward"></i>   Back to index</a>
                    </td>
                    </tr>

                </table>
            </form>

        </div>

        <?php
include_once 'footer.php';
?>
</code>```

This is my html part, where I enter my values.

```<code><?php

$DB_host = "localhost";
$DB_user = "root";
$DB_pass = "";
$DB_name = "event";

try
{
    $DB_con = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass);
    $DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
    echo $e->getMessage();
}

include_once 'class.crud.php';

$crud = new crud($DB_con);

?>
</code>```

This is the db configuration file.

Please help me where did I go wrong?

答:
i had the same problem. This worked for me, maybe for you too.

Make for all the string variable maybe for the date time also (don't know your database) this:

```<code>$atitle = '"'.$_POST['actitle'].'"';
</code>```

Or in place of " do `.

I hope this helps for you^^

Title: I could't insert data into MySQL table

Body:
I am facing the issue only when I try to insert data, where the same code runs perfectly well when I try inserting data to another table with different set of values.

<?php

class crud
{
    private $db;

    function __construct($DB_con)
    {
        $this->db = $DB_con;
    }

    public function create($atitle,$agen,$ams,$adob,$afn,$aln,$acob,$acoc,$aemail,$amob,$aaddr,$amesse)    {
        try
        {
            $stmt = $this->db->prepare("INSERT INTO contacts(title,gen,ms,dob,fn,ln,cob,coc,email,mob,addr,messe) VALUES(:atitle,:agen,:ams,:adob,:afn,:aln,:acob,:acoc,:aemail,:amob,:aaddr,:amesse)");
            $stmt->bindparam(":atitle",$atitle);
            $stmt->bindparam(":agen",$agen);
            $stmt->bindparam(":ams",$ams);
            $stmt->bindparam(":adob",$adob);
            $stmt->bindparam(":afn",$afn);
            $stmt->bindparam(":aln",$aln);
            $stmt->bindparam(":acob",$acob);
            $stmt->bindparam(":acoc",$acoc);
            $stmt->bindparam(":aemail",$aemail);
            $stmt->bindparam(":amob",$amob);
            $stmt->bindparam(":aaddr",$aaddr);
            $stmt->bindparam(":amesse",$amesse);
            $stmt->execute();
            return true;
        }
        catch(PDOException $e)
        {
            echo $e->getMessage();
            return false;
        }

    }
}

Above is the class used to insert data.

<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-save']))
{
    $atitle = $_POST['actitle'];
    $agen = $_POST['acgen'];
    $ams = $_POST['acms'];
    $acdate = $_POST['acdate'];
    $adob = date('Y-m-d', strtotime(str_replace('-', '/', $acdate)));
    $afn = $_POST['acfn'];
    $aln = $_POST['acln'];
    $acob = $_POST['accob'];
    $acoc = $_POST['accoc'];
    $aemail = $_POST['aemail'];
    $amob = $_POST['acmob'];
    $aaddr = $_POST['acaddr'];
    $amesse = $_POST['acmesse'];

    if($crud->create($atitle,$agen,$ams,$adob,$afn,$aln,$acob,$acoc,$aemail,$amob,$aaddr,$amesse))
    {
        header("Location: add-con.php?inserted");
    }
    else
    {
        header("Location: add-con.php?failure");
    }
}
?>
    <?php include_once 'header.php'; ?>

    <?php
if(isset($_GET['inserted']))
{
    ?>

            WOW! Record was inserted successfully HOME!

    <?php
}
else if(isset($_GET['failure']))
{
    ?>

                SORRY! ERROR while inserting record !

        <?php
}
?>

            <form method='post'>

                        Title
                        <input type='text' name='actitle' class='form-control' required>

                        Gender
                        <input type='text' name='acgen' class='form-control' required>

                        Marital Status
                        <input type='text' name='acms' class='form-control' required>

                        DOB
                        <input type='text' name='acdate' class='form-control' required>

                        First Name
                        <input type='text' name='acfn' class='form-control' required>

                        Last Name
                        <input type='text' name='acln' class='form-control' required>

                        Country of Birth
                        <input type='text' name='accob' class='form-control' required>

                        COC
                        <input type='text' name='accoc' class='form-control' required>

                        email
                        <input type='text' name='acemail' class='form-control' required>

                        mob
                        <input type='text' name='acmob' class='form-control' required>

                        address
                        <input type='text' name='acaddr' class='form-control' required>

                        messege
                        <input type='text' name='acmesse' class='form-control' required>

                        <button type="submit" class="btn btn-primary" name="btn-save">
             Create New Record
            </button>
                           Back to index

            </form>

        <?php
include_once 'footer.php';
?>

This is my html part, where I enter my values.

<?php

$DB_host = "localhost";
$DB_user = "root";
$DB_pass = "";
$DB_name = "event";

try
{
    $DB_con = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass);
    $DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
    echo $e->getMessage();
}

include_once 'class.crud.php';

$crud = new crud($DB_con);

?>

This is the db configuration file.

Please help me where did I go wrong?

Body:
i had the same problem. This worked for me, maybe for you too.

Make for all the string variable maybe for the date time also (don't know your database) this:

$atitle = '"'.$_POST['actitle'].'"';

Or in place of " do `.

I hope this helps for you^^


问:
Height issue with elements in a row using flexbox and scrolling
I have a couple of element which are positioned horizontally, but they are taller than the parent, meeaning they scroll. It looks like this

Although the scroll behaviour is correct, the content of the first block overflows.

The HTML looks like this

```<code><section>
    <div> <!-- very long content --> </div>
    <div>b</div>
    ....
</section>
</code>```

CSS:

```<code>section {
    display: flex;
    border: 2px solid red;
    height: 100px;
    align-items: stretch;
    overflow:auto;
}

div {
    background-color: green;
    margin: 5px;
    flex: 1;
}
</code>```

DEMO

As you can see in the demo, the element with the green background color is not tall enough to fit all the content. How can this be achieved ? It would be nice if all divs have the same height, is that possible?

答: If you you want all the items to be 100px high without overflow then set overflow: hidden;. If you want all the items to be as high as the highest item, then remove the height property.

Body:
I have a couple of element which are positioned horizontally, but they are taller than the parent, meeaning they scroll. It looks like this

Although the scroll behaviour is correct, the content of the first block overflows.

The HTML looks like this

b

    ....

CSS:

section {
    display: flex;
    border: 2px solid red;
    height: 100px;
    align-items: stretch;
    overflow:auto;
}

div {
    background-color: green;
    margin: 5px;
    flex: 1;
}

DEMO

As you can see in the demo, the element with the green background color is not tall enough to fit all the content. How can this be achieved ? It would be nice if all divs have the same height, is that possible?


问:
Consecutive asynchronous test steps in ava

The problem

The popular ava package features a simple and powerful testing framework for javascript:

import test from 'ava';

test('single step', t => {
    t.is('bar', 'bar');
    t.end();
});
```

Testing is dead simple for synchronous code. However, I am not sure how to write tests with multiple, consecutive, dependent steps.

For example, I would like to test a REST API. I would like to create a resource using POST, make sure it exists with GET call, and delete it with DELETE.

Needless to say, the order matters: the POST call must be finished before the GET call can start, and sometimes we even want a sleep time between steps.

What have I tried

Tried a series of setTimeouts where where the callback of each call is the next test step. It is fairly unreadable.

My question

What's the right way to write a test with multiple consecutive steps with ava?

These steps are asynchronous and consecutive

答: If you're looking to have all these steps in a single test, make sure you can get promises out of your request library. Then use async / await.

Body:
The problem

The popular ava package features a simple and powerful testing framework for javascript:

import test from 'ava';

test('single step', t => {
    t.is('bar', 'bar');
    t.end();
});

Testing is dead simple for synchronous code. However, I am not sure how to write tests with multiple, consecutive, dependent steps.

For example, I would like to test a REST API. I would like to create a resource using POST, make sure it exists with GET call, and delete it with DELETE.

Needless to say, the order matters: the POST call must be finished before the GET call can start, and sometimes we even want a sleep time between steps.

What have I tried

Tried a series of setTimeouts where where the callback of each call is the next test step. It is fairly unreadable.

My question

What's the right way to write a test with multiple consecutive steps with ava?

These steps are asynchronous and consecutive


问:
How to hide COM object Dispatched from Python
I'm using COM in Python and I want the object to run in background - hidden.
With Excel I do:

```<code>Import win32com.client
Excel=win32com.client.Dispatch("Excel.Application")
Excel.Visible=1
</code>```

but my application do not have property .Visible - is there any other way to hide it? Maybe some special parameter to Dispatch?

Thanks in advance
R

答:
If you know your application title or class, you can hide it via ShowWindow:

```<code>import win32com.client
import win32con
import win32gui
import time

print "Start"
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = 1   # Visible via automation
time.sleep(2)
hwnd = win32gui.FindWindow(None, "Microsoft Excel")  # Class or title
print "Hide"
win32gui.ShowWindow(hwnd, win32con.SW_HIDE) # Hide via Win32Api
time.sleep(2)
print "Show"
win32gui.ShowWindow(hwnd, win32con.SW_SHOW) # Show via Win32Api
time.sleep(2)

###
</code>```

HTH,
Pablo

Body:
I'm using COM in Python and I want the object to run in background - hidden.
With Excel I do:

Import win32com.client
Excel=win32com.client.Dispatch("Excel.Application")
Excel.Visible=1

but my application do not have property .Visible - is there any other way to hide it? Maybe some special parameter to Dispatch?

Thanks in advance
R

Body:
If you know your application title or class, you can hide it via ShowWindow:

import win32com.client
import win32con
import win32gui
import time

print "Start"
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = 1   # Visible via automation
time.sleep(2)
hwnd = win32gui.FindWindow(None, "Microsoft Excel")  # Class or title
print "Hide"
win32gui.ShowWindow(hwnd, win32con.SW_HIDE) # Hide via Win32Api
time.sleep(2)
print "Show"
win32gui.ShowWindow(hwnd, win32con.SW_SHOW) # Show via Win32Api
time.sleep(2)

###

HTH,
Pablo


问:
Add one day to calendar to make test if-else
I use DateTime values in my app. I can create Lessons, and I have to set the beginning nd the end of that lesson.

Let's say I create like this :

```<code>English - Beginning 07.05.2017 End 07.07.2017
</code>```

Then I want to modify the end of that lesson and put :

```<code>07.06.2017
</code>```

I check to see if the dates are OK, but I'm not sure about what I did, because I dont want to let the user to modifiy or create lessons in the past, but if he creates a lesson that finishes the current day, that's ok.

I wrote like this in my if else :

```<code>       String date1 = datedebut.getText().toString();
        String date2 = datefin.getText().toString();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date_debutnew = dateFormat.parse(date_initial);
        Date date_derniernew = dateFormat.parse(date_derniercours);
 Calendar calendar = Calendar.getInstance();

     if (date_debutnew.after(date_derniernew) || date_derniernew.before(calendar.getTime()))

    { ... }
</code>```

How can I add one day to that calendar ?

Thank you for the future hlep.

答:
You can use compareTo() method of Date.

It will return,

a value 0 if the argument Date is equal to this Date;

a value less than 0 if this Date is before the Date argument;

a value greater than 0 if this Date is after the Date argument.

Body:
I use DateTime values in my app. I can create Lessons, and I have to set the beginning nd the end of that lesson.

Let's say I create like this :

English - Beginning 07.05.2017 End 07.07.2017

Then I want to modify the end of that lesson and put :

07.06.2017

I check to see if the dates are OK, but I'm not sure about what I did, because I dont want to let the user to modifiy or create lessons in the past, but if he creates a lesson that finishes the current day, that's ok.

I wrote like this in my if else :

       String date1 = datedebut.getText().toString();
        String date2 = datefin.getText().toString();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date_debutnew = dateFormat.parse(date_initial);
        Date date_derniernew = dateFormat.parse(date_derniercours);
 Calendar calendar = Calendar.getInstance();

     if (date_debutnew.after(date_derniernew) || date_derniernew.before(calendar.getTime()))

    { ... }

How can I add one day to that calendar ?

Thank you for the future hlep.


问:
How can I rethrow an Inner Exception while maintaining the stack trace generated so far?
Duplicate of: In C#, how can I rethrow InnerException without losing stack trace?

I have some operations that I invoke asynchronously on a background thread.  Sometimes, things go bad.  When this happens, I tend to get a TargetInvocationException, which, while appropriate, is quite useless.  What I really need is the TargetInvocationException's InnerException, like this:

```<code>    try
    {
        ReturnValue = myFunctionCall.Invoke(Target, Parameters);
    }
    catch (TargetInvocationException err)
    {
        throw err.InnerException;
    }
</code>```

That way, my callers are served up with the REAL exception that occured.  The problem is, that the throw statement seems to reset the stack trace.  I'd like to basically rethrow the inner exception, but keep the stack trace it originally had.  How do I do that?

CLARIFICATION:
The reason I want only the inner exception is that this class tries to 'abstract away' the whole fact that these functions (delegates supplied by caller) are run on other threads and whatnot.  If there is an exception, then odds are it has nothing to do with being run on a background thread, and the caller would really like the stack trace that goes into their delegate and finds the real issue, not my call to invoke.

答:
It is possible with .net 4.5:</p>

```<code>catch(Exception e)
{
   ExceptionDispatchInfo.Capture(e.InnerException).Throw();
}
</code>```

Body:
Duplicate of: In C#, how can I rethrow InnerException without losing stack trace?

I have some operations that I invoke asynchronously on a background thread.  Sometimes, things go bad.  When this happens, I tend to get a TargetInvocationException, which, while appropriate, is quite useless.  What I really need is the TargetInvocationException's InnerException, like this:

    try
    {
        ReturnValue = myFunctionCall.Invoke(Target, Parameters);
    }
    catch (TargetInvocationException err)
    {
        throw err.InnerException;
    }

That way, my callers are served up with the REAL exception that occured.  The problem is, that the throw statement seems to reset the stack trace.  I'd like to basically rethrow the inner exception, but keep the stack trace it originally had.  How do I do that?

CLARIFICATION:
The reason I want only the inner exception is that this class tries to 'abstract away' the whole fact that these functions (delegates supplied by caller) are run on other threads and whatnot.  If there is an exception, then odds are it has nothing to do with being run on a background thread, and the caller would really like the stack trace that goes into their delegate and finds the real issue, not my call to invoke.

Body:
It is possible with .net 4.5:

catch(Exception e)
{
   ExceptionDispatchInfo.Capture(e.InnerException).Throw();
}


问:
Inline SVG in Firefox
I'm a bit stumped with this one. I'm rendering SVG visualizations using Protovis, a JS library, and it works perfectly well in Chrome as well as Firefox. I save the rendered SVG on my server and try to re-render it in a "gallery" view using a PHP function, and this fails in Firefox. All I see is the text in the SVG, but not the SVG.

I save the full svg content, like so:

```<code><svg height="220" width="880" stroke-width="1.5" stroke="none" fill="none" font-family="sans-serif" font-size="10px"><g transform="translate(30, 10)"><line stroke-width="1"
</code>```

I've tried using <object> but all that does is prompt Firefox to download a plugin it can't find.

It works in FF4 beta, but I can't see why it won't work even in Firefox 3.6. Is this something I ought to give up on? You can see a demo here:

http://www.rioleo.org/protoviewer (click on "gallery")

Thanks once again!

答:
Inline SVG only works in Firefox in two situations:

Firefox has the experimental HTML5 parser enabled (ie. you're using a 4.0 nightly)

The document being parsed is not HTML but XHTML (Content-type: application/xhtml+xml)

The object approach suggested by Rob should work, as long as the separate SVG file is coming from your server with Content-type: image/svg+xml and you use the correct syntax:

```<code><object data="foo.svg" type="image/svg+xml" width="400" height="300">
</code>```

See Damian Cugley's article 'SVG: object or embed?' for details of some other options, or use SVGWeb.

Title: Inline SVG in Firefox

Body:
I'm a bit stumped with this one. I'm rendering SVG visualizations using Protovis, a JS library, and it works perfectly well in Chrome as well as Firefox. I save the rendered SVG on my server and try to re-render it in a "gallery" view using a PHP function, and this fails in Firefox. All I see is the text in the SVG, but not the SVG.

I save the full svg content, like so:

<svg height="220" width="880" stroke-width="1.5" stroke="none" fill="none" font-family="sans-serif" font-size="10px"><g transform="translate(30, 10)"><line stroke-width="1"

I've tried using <object> but all that does is prompt Firefox to download a plugin it can't find.

It works in FF4 beta, but I can't see why it won't work even in Firefox 3.6. Is this something I ought to give up on? You can see a demo here:

http://www.rioleo.org/protoviewer (click on "gallery")

Thanks once again!

Body:
Inline SVG only works in Firefox in two situations:

Firefox has the experimental HTML5 parser enabled (ie. you're using a 4.0 nightly)

The document being parsed is not HTML but XHTML (Content-type: application/xhtml+xml)

The object approach suggested by Rob should work, as long as the separate SVG file is coming from your server with Content-type: image/svg+xml and you use the correct syntax:

<object data="foo.svg" type="image/svg+xml" width="400" height="300">

See Damian Cugley's article 'SVG: object or embed?' for details of some other options, or use SVGWeb.


问:
Volt directory can't be written
The error I am getting is

```<code>Warning: Phalcon\Mvc\View\Engine\Volt\Compiler::compileFile(../app/views/index/index.phtml.php): failed to open stream: Permission denied in /Users/mattstephens/Sites/magpie/public/index.php on line 26 Phalcon Exception: Volt directory can't be written
</code>```

I have declared the volt engine usage in my bootstrap like so

```<code>$view->registerEngines(array(
      '.phtml' => 'Phalcon\Mvc\View\Engine\Volt'
    ));
</code>```

The mention of line 26 in my code points to the application handle function shown below

```<code>echo $application->handle()->getContent();
</code>```

Is this a permissions related thing or due to a missing directory?

答:
Just go to /project_name/store/app/config/config.php and change cacheDir from 'cacheDir'       => __DIR__ . '/../../app/cache/' to 'cacheDir'       => __DIR__ . '/../../cache/'.

Also, change its write permission to 777.

Title: Volt directory can't be written

Body:
The error I am getting is

Warning: Phalcon\Mvc\View\Engine\Volt\Compiler::compileFile(../app/views/index/index.phtml.php): failed to open stream: Permission denied in /Users/mattstephens/Sites/magpie/public/index.php on line 26 Phalcon Exception: Volt directory can't be written

I have declared the volt engine usage in my bootstrap like so

$view->registerEngines(array(
      '.phtml' => 'Phalcon\Mvc\View\Engine\Volt'
    ));

The mention of line 26 in my code points to the application handle function shown below

echo $application->handle()->getContent();

Is this a permissions related thing or due to a missing directory?


问:
python "shell" not print return value 0 after each successfully executed line
when i run (for example)

```<code>print("Hello")
</code>```

the interpreter shows

```<code>Hello
</code>```

thats perfect, but...

```<code>from subprocess import call
ls = 'ls'
call(ls)
</code>```

prints

```<code>file1 file2 file3
0
</code>```

im guessing that the 0 is the return value saying it was successfull (still very new to programming :)   )

soooo..... my question is how to get rid of the 0 so that i only get the output from it, with this example and others as well?

lol im probably over looking something simple here

any help is greatly apreciated!!! :)

EDIT: something like

```<code>@echo off
</code>```

in windows batch scripts would be prefered(so i can use it once and ignore it)

答:
You can use the following:</p>

```<code>import subprocess
subprocess.check_output('ls')
# subprocess.check_output('ls', shell=True)
</code>```

Body:
when i run (for example)

print("Hello")

the interpreter shows

Hello

thats perfect, but...

from subprocess import call
ls = 'ls'
call(ls)

prints

file1 file2 file3
0

im guessing that the 0 is the return value saying it was successfull (still very new to programming :)   )

soooo..... my question is how to get rid of the 0 so that i only get the output from it, with this example and others as well?

lol im probably over looking something simple here

any help is greatly apreciated!!! :)

EDIT: something like

@echo off

in windows batch scripts would be prefered(so i can use it once and ignore it)

Body:
You can use the following:

import subprocess
subprocess.check_output('ls')
# subprocess.check_output('ls', shell=True)


问:
Recursive hierarchical Oracle SQL query
I have a source table like below:

```<code>Emp_ID| Name| Manager_ID
001|abc|005
005|cde|010
010|xyz|050
050 | bcg| 100
100|sta|NULL
</code>```

My requirement is to populate the target table like below:

```<code>Emp_ID| Name| Manager_1| Manager_2| Manager_3| Manager_4
005|cde|xyz|bcg|sta|NULL
050|bcg|sta| NULL|NULL|NULL
100|sta|NULL|NULL|NULL
001|abc|cde|xyz|bcg|sta
</code>```

I am able to use recursive select through Connect by clause and populate the value for Manager_1 but not able to get through the logic to populate Manager_2, Manager_3 , Manager_4 values as different column values in a single row depending on how many level of hierarchy is present for a certain employee.
Please help.

答:
I think the following query will help you. But to split the string to individual manager id, you need to know the max no of level of managers.</p>

```<code>WITH data_set AS
     (SELECT '001' emp_id, 'aaa' emp_name, '005' mgr_id
        FROM DUAL
      UNION
      SELECT '005' emp_id, 'bbb' emp_name, '010' mgr_id
        FROM DUAL
      UNION
      SELECT '010' emp_id, 'ccc' emp_name, '050' mgr_id
        FROM DUAL
      UNION
      SELECT '020' emp_id, 'ddd' emp_name, '050' mgr_id
        FROM DUAL
      UNION
      SELECT '050' emp_id, 'eee' emp_name, '100' mgr_id
        FROM DUAL
      UNION
      SELECT '100' emp_id, 'fff' emp_name, '200' mgr_id
        FROM DUAL
      UNION
      SELECT '200' emp_id, 'ggg' emp_name, NULL mgr_id
        FROM DUAL)
SELECT     emp_id, emp_name, mgr_id,
           LTRIM (SYS_CONNECT_BY_PATH (emp_id, '-'), '-') chain
      FROM data_set
START WITH mgr_id IS NULL
CONNECT BY mgr_id = PRIOR emp_id
  ORDER SIBLINGS BY emp_id;
</code>```

Title: Recursive hierarchical Oracle SQL query

Body:
I have a source table like below:

Emp_ID| Name| Manager_ID
001|abc|005
005|cde|010
010|xyz|050
050 | bcg| 100
100|sta|NULL

My requirement is to populate the target table like below:

Emp_ID| Name| Manager_1| Manager_2| Manager_3| Manager_4
005|cde|xyz|bcg|sta|NULL
050|bcg|sta| NULL|NULL|NULL
100|sta|NULL|NULL|NULL
001|abc|cde|xyz|bcg|sta

I am able to use recursive select through Connect by clause and populate the value for Manager_1 but not able to get through the logic to populate Manager_2, Manager_3 , Manager_4 values as different column values in a single row depending on how many level of hierarchy is present for a certain employee.
Please help.

Body:
I think the following query will help you. But to split the string to individual manager id, you need to know the max no of level of managers.

WITH data_set AS
     (SELECT '001' emp_id, 'aaa' emp_name, '005' mgr_id
        FROM DUAL
      UNION
      SELECT '005' emp_id, 'bbb' emp_name, '010' mgr_id
        FROM DUAL
      UNION
      SELECT '010' emp_id, 'ccc' emp_name, '050' mgr_id
        FROM DUAL
      UNION
      SELECT '020' emp_id, 'ddd' emp_name, '050' mgr_id
        FROM DUAL
      UNION
      SELECT '050' emp_id, 'eee' emp_name, '100' mgr_id
        FROM DUAL
      UNION
      SELECT '100' emp_id, 'fff' emp_name, '200' mgr_id
        FROM DUAL
      UNION
      SELECT '200' emp_id, 'ggg' emp_name, NULL mgr_id
        FROM DUAL)
SELECT     emp_id, emp_name, mgr_id,
           LTRIM (SYS_CONNECT_BY_PATH (emp_id, '-'), '-') chain
      FROM data_set
START WITH mgr_id IS NULL
CONNECT BY mgr_id = PRIOR emp_id
  ORDER SIBLINGS BY emp_id;