问:
Display marks from least to high
I'm trying to display the marks from least to high from user input.The code gets the array of students name and array of marks.Then it has to show the output from least to high marks along with student name.I'm struck at displaying the name of student.The code just shows the marks from least to high.</p>

```<code>int n = 5;//total no of students
Scanner in = new Scanner(System.in);
System.out.println("Enter Students name:");
String[] s = new String[n];
for (int i = 0; i<s.length; i++)
{
  s[i] = in.nextLine();
}
System.out.println("Enter marks:");
int array[] = new int[n];
for (int i = 0; i<n; i++)
{
 array[i] = in.nextInt();
}
Arrays.sort(array);
for (int i = 0; i < array.length; i++)
{
  System.out.println(array[i]);
}
</code>```

答:
Create a wrapper class (say, Student) to store the student name and mark. Then sort them using a comparator to compare the marks.

```<code>import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

public class testing {
    public static void main(String[] args) {
        int n = 5;//total no of students
        Scanner in = new Scanner(System.in);
        System.out.println("Enter Students name:");
        Student[] students = new Student[n];
        for (int i = 0; i<n; i++)
        {
            students[i] = new Student();
            students[i].name = in.nextLine();
        }
        System.out.println("Enter marks:");
        for (int i = 0; i<n; i++)
        {
            students[i].mark = in.nextInt();
        }
        Arrays.sort(students, new MarkComparator());
        for (int i = 0; i < n; i++)
        {
            System.out.println(students[i].name + " - "+ students[i].mark);
        }
    }
}

class Student {
    int mark;
    String name;
}

class MarkComparator implements Comparator {
    public int compare(Object o1,Object o2){
        Student s1=(Student)o1;
        Student s2=(Student)o2;
        if(s1.mark>=s2.mark) {
            return 1;
        } else {
            return -1;
        }
    }
}
</code>```

Sample output:

```<code>Enter Students name:
alex
bertha
chris
dan
ervin
Enter marks:
50
40
30
20
10

ervin - 10
dan - 20
chris - 30
bertha - 40
alex - 50
</code>```

Title: Display marks from least to high

Body:
I'm trying to display the marks from least to high from user input.The code gets the array of students name and array of marks.Then it has to show the output from least to high marks along with student name.I'm struck at displaying the name of student.The code just shows the marks from least to high.

int n = 5;//total no of students
Scanner in = new Scanner(System.in);
System.out.println("Enter Students name:");
String[] s = new String[n];
for (int i = 0; i<s.length; i++)
{
  s[i] = in.nextLine();
}
System.out.println("Enter marks:");
int array[] = new int[n];
for (int i = 0; i<n; i++)
{
 array[i] = in.nextInt();
}
Arrays.sort(array);
for (int i = 0; i < array.length; i++)
{
  System.out.println(array[i]);
}

Body:
Create a wrapper class (say, Student) to store the student name and mark. Then sort them using a comparator to compare the marks.

import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

public class testing {
    public static void main(String[] args) {
        int n = 5;//total no of students
        Scanner in = new Scanner(System.in);
        System.out.println("Enter Students name:");
        Student[] students = new Student[n];
        for (int i = 0; i<n; i++)
        {
            students[i] = new Student();
            students[i].name = in.nextLine();
        }
        System.out.println("Enter marks:");
        for (int i = 0; i<n; i++)
        {
            students[i].mark = in.nextInt();
        }
        Arrays.sort(students, new MarkComparator());
        for (int i = 0; i < n; i++)
        {
            System.out.println(students[i].name + " - "+ students[i].mark);
        }
    }
}

class Student {
    int mark;
    String name;
}

class MarkComparator implements Comparator {
    public int compare(Object o1,Object o2){
        Student s1=(Student)o1;
        Student s2=(Student)o2;
        if(s1.mark>=s2.mark) {
            return 1;
        } else {
            return -1;
        }
    }
}

Sample output:

Enter Students name:
alex
bertha
chris
dan
ervin
Enter marks:
50
40
30
20
10

ervin - 10
dan - 20
chris - 30
bertha - 40
alex - 50


来源: stackexchange

问:
Adding missing nodes to XML via XSLT
I'm using a tool to import XML files into Dynamics NAV, but some parties providing the XML files skip empty nodes. My tool (external) can not handle those situation so I want to include XSLT to add the missing nodes. The xslt works fine for 1 node, but adding multiple nodes does not work. So I must be doing something wrong.

I'm building an integration to Dynamics NAV to insert Sales Orders. The orders are delivered from multiple parties using a XML file. However some of the parties providing the XML do not list all nodes in their XML file, they skip the empty ones. I'm using a tool build within Dynamics NAV (Add-on from other vendor) to import those files. However some XML files go wrong because of the fact that some (empty) nodes are missing in the XML file. I know this is an issue within the add-on but I need a solution on short notice. So created an XSLT to add the missing nodes. It works fine with 1 missing node, but it is not able to add both missing nodes. I'm not that familiar with XSLT so most of the times it is trial & error. Perhaps someone can help me with this.

This is the XML file format that is provided, The nodes that are sometimes missing is the DeliveryParty node and the DeliveryAddress part.

```<code><?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<Orders>
  <Order>
    <Partner>
  <SenderEANCode>9999999999999</SenderEANCode>
      <RecipientEANCode>9999999999999</RecipientEANCode>
    </Partner>
    <OrderHeader>
      <OrderVersion>008</OrderVersion>
      <OrderTypeCode>220</OrderTypeCode>
      <Document>
        <DocumentNumber>34034040</DocumentNumber>
        <Date>2019-04-18</Date>
      </Document>
      <DeliveryDate>2019-04-24</DeliveryDate>
      <CompleteDelivery>YES</CompleteDelivery>
      <Supplier>9999999999999</Supplier>
      <Buyer>9999999999999</Buyer>
      <Invoicee>9999999999999</Invoicee>
      <DeliveryParty>9999999999999</DeliveryParty>
      <DeliveryAddress>
        <DeliveryName>Private     Customer</DeliveryName>
        <DeliveryStreet>Teststraat</DeliveryStreet>
        <DeliveryCity>TestCity</DeliveryCity>
        <DeliveryCountry>NL</DeliveryCountry>
        <DeliveryTelNo></DeliveryTelNo>
        <DeliveryEmail>test@test.com</DeliveryEmail>
      </DeliveryAddress>
    </OrderHeader>
    <OrderLine>
      <LineItemNumber>1</LineItemNumber>
      <GTIN>9999999999999</GTIN>
      <OrderedQuantity>
        <Quantity>260</Quantity>
      </OrderedQuantity>
    </OrderLine>
  </Order>
</Orders>
</code>```

Sometimes the DeliveryParty node is missing and other times the DeliveryAddress part including subnodes is missing. I created the following XSLT to add those nodes but as it is trail and error I need some help to fix this. I'm a novice to XSLT, I can so some small changes but I do not use it frequently so knowledge is fading away quickly.

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>

<xsl:template match="@*|node()">
   <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
   </xsl:copy>
</xsl:template>

<xsl:template match="Orders/Order/OrderHeader[not(DeliveryParty)]">
  <xsl:copy-of select="*"/>
  <DeliveryParty/>
</xsl:template>

<xsl:template match="Orders/Order/OrderHeader[not(//DeliveryAddress)]">
 <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
     <DeliveryAddress>
       <DeliveryName></DeliveryName>
       <DeliveryStreet></DeliveryStreet>
       <DeliveryPostalCode></DeliveryPostalCode>
       <DeliveryCity></DeliveryCity>
       <DeliveryCountry></DeliveryCountry>
       <DeliveryTelNo></DeliveryTelNo>
       <DeliveryEmail></DeliveryEmail>
     </DeliveryAddress>
   </xsl:copy>
</xsl:template>
</code>```

With above mentioned XSLT the DeliveryAddress node with it's subnodes is added but the deliveryparty is not.

When the file is delivered like this:

```<code><?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<Orders>
  <Order>
    <Partner>
  <SenderEANCode>9999999999999</SenderEANCode>
      <RecipientEANCode>9999999999999</RecipientEANCode>
    </Partner>
    <OrderHeader>
      <OrderVersion>008</OrderVersion>
      <OrderTypeCode>220</OrderTypeCode>
      <Document>
        <DocumentNumber>34034040</DocumentNumber>
        <Date>2019-04-18</Date>
      </Document>
      <DeliveryDate>2019-04-24</DeliveryDate>
      <CompleteDelivery>YES</CompleteDelivery>
      <Supplier>9999999999999</Supplier>
      <Buyer>9999999999999</Buyer>
      <Invoicee>9999999999999</Invoicee>
    </OrderHeader>
    <OrderLine>
      <LineItemNumber>1</LineItemNumber>
      <GTIN>9999999999999</GTIN>
      <OrderedQuantity>
        <Quantity>260</Quantity>
      </OrderedQuantity>
    </OrderLine>
  </Order>
</Orders>
</code>```

The outcome should be this:

```<code><?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<Orders>
  <Order>
    <Partner>
  <SenderEANCode>9999999999999</SenderEANCode>
      <RecipientEANCode>9999999999999</RecipientEANCode>
    </Partner>
    <OrderHeader>
      <OrderVersion>008</OrderVersion>
      <OrderTypeCode>220</OrderTypeCode>
      <Document>
        <DocumentNumber>34034040</DocumentNumber>
        <Date>2019-04-18</Date>
      </Document>
      <DeliveryDate>2019-04-24</DeliveryDate>
      <CompleteDelivery>YES</CompleteDelivery>
      <Supplier>9999999999999</Supplier>
      <Buyer>9999999999999</Buyer>
      <Invoicee>9999999999999</Invoicee>
      <DeliveryParty></DeliveryParty>
      <DeliveryAddress>
        <DeliveryName></DeliveryName>
        <DeliveryStreet></DeliveryStreet>
        <DeliveryCity></DeliveryCity>
        <DeliveryCountry></DeliveryCountry>
        <DeliveryTelNo></DeliveryTelNo>
        <DeliveryEmail></DeliveryEmail>
      </DeliveryAddress>
    </OrderHeader>
    <OrderLine>
      <LineItemNumber>1</LineItemNumber>
      <GTIN>9999999999999</GTIN>
      <OrderedQuantity>
        <Quantity>260</Quantity>
      </OrderedQuantity>
    </OrderLine>
  </Order>
</Orders>
</code>```

答:
How about:

XSLT 1.0

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="OrderHeader">
    <xsl:copy>
        <xsl:apply-templates/>
        <xsl:if test="not(DeliveryParty)">
            <DeliveryParty/>
        </xsl:if>
        <xsl:if test="not(DeliveryAddress)">
            <DeliveryAddress>
                <DeliveryName/>
                <DeliveryStreet/>
                <DeliveryPostalCode/>
                <DeliveryCity/>
                <DeliveryCountry/>
                <DeliveryTelNo/>
                <DeliveryEmail/>
            </DeliveryAddress>
        </xsl:if>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Adding missing nodes to XML via XSLT

Body:
I'm using a tool to import XML files into Dynamics NAV, but some parties providing the XML files skip empty nodes. My tool (external) can not handle those situation so I want to include XSLT to add the missing nodes. The xslt works fine for 1 node, but adding multiple nodes does not work. So I must be doing something wrong.

I'm building an integration to Dynamics NAV to insert Sales Orders. The orders are delivered from multiple parties using a XML file. However some of the parties providing the XML do not list all nodes in their XML file, they skip the empty ones. I'm using a tool build within Dynamics NAV (Add-on from other vendor) to import those files. However some XML files go wrong because of the fact that some (empty) nodes are missing in the XML file. I know this is an issue within the add-on but I need a solution on short notice. So created an XSLT to add the missing nodes. It works fine with 1 missing node, but it is not able to add both missing nodes. I'm not that familiar with XSLT so most of the times it is trial & error. Perhaps someone can help me with this.

This is the XML file format that is provided, The nodes that are sometimes missing is the DeliveryParty node and the DeliveryAddress part.

<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<Orders>
  <Order>
    <Partner>
  <SenderEANCode>9999999999999</SenderEANCode>
      <RecipientEANCode>9999999999999</RecipientEANCode>
    </Partner>
    <OrderHeader>
      <OrderVersion>008</OrderVersion>
      <OrderTypeCode>220</OrderTypeCode>
      <Document>
        <DocumentNumber>34034040</DocumentNumber>
        <Date>2019-04-18</Date>
      </Document>
      <DeliveryDate>2019-04-24</DeliveryDate>
      <CompleteDelivery>YES</CompleteDelivery>
      <Supplier>9999999999999</Supplier>
      <Buyer>9999999999999</Buyer>
      <Invoicee>9999999999999</Invoicee>
      <DeliveryParty>9999999999999</DeliveryParty>
      <DeliveryAddress>
        <DeliveryName>Private     Customer</DeliveryName>
        <DeliveryStreet>Teststraat</DeliveryStreet>
        <DeliveryCity>TestCity</DeliveryCity>
        <DeliveryCountry>NL</DeliveryCountry>
        <DeliveryTelNo></DeliveryTelNo>
        <DeliveryEmail>test@test.com</DeliveryEmail>
      </DeliveryAddress>
    </OrderHeader>
    <OrderLine>
      <LineItemNumber>1</LineItemNumber>
      <GTIN>9999999999999</GTIN>
      <OrderedQuantity>
        <Quantity>260</Quantity>
      </OrderedQuantity>
    </OrderLine>
  </Order>
</Orders>

Sometimes the DeliveryParty node is missing and other times the DeliveryAddress part including subnodes is missing. I created the following XSLT to add those nodes but as it is trail and error I need some help to fix this. I'm a novice to XSLT, I can so some small changes but I do not use it frequently so knowledge is fading away quickly.

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>

<xsl:template match="@*|node()">
   <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
   </xsl:copy>
</xsl:template>

<xsl:template match="Orders/Order/OrderHeader[not(DeliveryParty)]">
  <xsl:copy-of select="*"/>
  <DeliveryParty/>
</xsl:template>

<xsl:template match="Orders/Order/OrderHeader[not(//DeliveryAddress)]">
 <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
     <DeliveryAddress>
       <DeliveryName></DeliveryName>
       <DeliveryStreet></DeliveryStreet>
       <DeliveryPostalCode></DeliveryPostalCode>
       <DeliveryCity></DeliveryCity>
       <DeliveryCountry></DeliveryCountry>
       <DeliveryTelNo></DeliveryTelNo>
       <DeliveryEmail></DeliveryEmail>
     </DeliveryAddress>
   </xsl:copy>
</xsl:template>

With above mentioned XSLT the DeliveryAddress node with it's subnodes is added but the deliveryparty is not.

When the file is delivered like this:

<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<Orders>
  <Order>
    <Partner>
  <SenderEANCode>9999999999999</SenderEANCode>
      <RecipientEANCode>9999999999999</RecipientEANCode>
    </Partner>
    <OrderHeader>
      <OrderVersion>008</OrderVersion>
      <OrderTypeCode>220</OrderTypeCode>
      <Document>
        <DocumentNumber>34034040</DocumentNumber>
        <Date>2019-04-18</Date>
      </Document>
      <DeliveryDate>2019-04-24</DeliveryDate>
      <CompleteDelivery>YES</CompleteDelivery>
      <Supplier>9999999999999</Supplier>
      <Buyer>9999999999999</Buyer>
      <Invoicee>9999999999999</Invoicee>
    </OrderHeader>
    <OrderLine>
      <LineItemNumber>1</LineItemNumber>
      <GTIN>9999999999999</GTIN>
      <OrderedQuantity>
        <Quantity>260</Quantity>
      </OrderedQuantity>
    </OrderLine>
  </Order>
</Orders>

The outcome should be this:

<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<Orders>
  <Order>
    <Partner>
  <SenderEANCode>9999999999999</SenderEANCode>
      <RecipientEANCode>9999999999999</RecipientEANCode>
    </Partner>
    <OrderHeader>
      <OrderVersion>008</OrderVersion>
      <OrderTypeCode>220</OrderTypeCode>
      <Document>
        <DocumentNumber>34034040</DocumentNumber>
        <Date>2019-04-18</Date>
      </Document>
      <DeliveryDate>2019-04-24</DeliveryDate>
      <CompleteDelivery>YES</CompleteDelivery>
      <Supplier>9999999999999</Supplier>
      <Buyer>9999999999999</Buyer>
      <Invoicee>9999999999999</Invoicee>
      <DeliveryParty></DeliveryParty>
      <DeliveryAddress>
        <DeliveryName></DeliveryName>
        <DeliveryStreet></DeliveryStreet>
        <DeliveryCity></DeliveryCity>
        <DeliveryCountry></DeliveryCountry>
        <DeliveryTelNo></DeliveryTelNo>
        <DeliveryEmail></DeliveryEmail>
      </DeliveryAddress>
    </OrderHeader>
    <OrderLine>
      <LineItemNumber>1</LineItemNumber>
      <GTIN>9999999999999</GTIN>
      <OrderedQuantity>
        <Quantity>260</Quantity>
      </OrderedQuantity>
    </OrderLine>
  </Order>
</Orders>

Body:
How about:

XSLT 1.0

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="OrderHeader">
    <xsl:copy>
        <xsl:apply-templates/>
        <xsl:if test="not(DeliveryParty)">
            <DeliveryParty/>
        </xsl:if>
        <xsl:if test="not(DeliveryAddress)">
            <DeliveryAddress>
                <DeliveryName/>
                <DeliveryStreet/>
                <DeliveryPostalCode/>
                <DeliveryCity/>
                <DeliveryCountry/>
                <DeliveryTelNo/>
                <DeliveryEmail/>
            </DeliveryAddress>
        </xsl:if>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>


问:
banner image loads with bigger size on mobile devices
I'm using: https://ready.mobi for testing my website for all devices. I'm interested in correctly set the image on the header for the index.
Right now the image is not looking great in all devices. Also the blue and orange buttons are too close to each other, and the
image appears too big (you have to scroll to see it).

Current result:

I've set media queries to handle this. Apparently they are not working well.

https://ready.mobi/#1164495-2wd6 (enter here to check the site on different devices online)

Desired result:

https://ready.mobi/#1164490-t8g2 (enter here to check the site on different devices online)

Codepen: https://codepen.io/anon/pen/EzOONJ

```<code>.my_header_bg_color {

    /*background-color: #4FB99F;*/
    /*background-color: #00ADB5;*/
    /*background-color: #6BB983;*/
    background-color: #00AD80;

}

/* Standard media queries breakpoints */

@media (min-width: 320px) and (max-width: 480px) {
    /* smartphones, iPhone, portrait 480x320 phones */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .productos_finales_home img {

        padding-bottom: 15px;
    }

    .my_home_banner_image {

        bottom: 0;
        top: 0;
        position: relative;
        z-index: 0;
        width: 60%;
        display: block;
        margin-right: auto;
        margin-left: 165px;
    }

    /*.my_home_banner_image {*/
    /*display: none;*/
    /*}*/
    .my_home_banner_title {
        color: white;
        font-size: 36px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        text-decoration: none;
        background-color: #969696;
        display: inline-block;
        text-align: center;
        vertical-align: middle;
        cursor: pointer;
        color: #fff;
        font-weight: 700;
        font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
        text-shadow: 0 -1px 0 rgba(0, 0, 0, .25);
        letter-spacing: 0;
        line-height: 1.2;
        -webkit-font-smoothing: antialiased;
        -webkit-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -ms-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -moz-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -o-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        background-image: linear-gradient(to bottom, rgba(255, 255, 255, .09) 0%, rgba(0, 0, 0, .09) 100%);
        font-size: 1.4rem;
        padding: 22px 30px;
        border-radius: 6px;
        border: none;
    }

.my_home_banner_left {
    margin-left: 10px;
    z-index: 100;
}

.stickers_referenciales {
    margin-bottom: 5px;
}

}

@media (min-width: 481px) {
    /* portrait e-readers (Nook/Kindle), smaller tablets @ 600 or @ 640 wide. */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 40%;
        display: block;
        margin-right: auto;
        margin-left: 185px;
    }

    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

}

@media (min-width: 641px) {
    /* portrait tablets, portrait iPad, landscape e-readers, landscape 800x480 or 854x480 phones */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 70%;
    }

    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

    .my_home_banner_lef_text {
        margin-left: 10px;
        z-index: 100;
    }

}

@media (min-width: 961px) {
    /* tablet, landscape iPad, lo-res laptops ands desktops */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 60%;
    }

    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

}

@media (min-width: 1025px) {
    /* big landscape tablets, laptops, and desktops */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 55%;
    }

    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

    .subscribe_field {
        width: 350px;
    }

}

@media (min-width: 1281px) {
    /* hi-res laptops and desktops */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 50%;
    }

    /*.my_home_banner_image_left {*/
    /*display: none;*/
    /*}*/
    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

    .subscribe_field {
        width: 350px;
    }
}

.center-video {
    margin: 0 auto;
    width: 400px;
}
</code>```

答:
Write this:

```<code>@media (max-width: 480px) {
</code>```

in place of:

```<code>@media (min-width: 320px) and (max-width: 480px) {
</code>```

Body:
I'm using: https://ready.mobi for testing my website for all devices. I'm interested in correctly set the image on the header for the index.
Right now the image is not looking great in all devices. Also the blue and orange buttons are too close to each other, and the
image appears too big (you have to scroll to see it).

Current result:

I've set media queries to handle this. Apparently they are not working well.

https://ready.mobi/#1164495-2wd6 (enter here to check the site on different devices online)

Desired result:

https://ready.mobi/#1164490-t8g2 (enter here to check the site on different devices online)

Codepen: https://codepen.io/anon/pen/EzOONJ

.my_header_bg_color {

    /*background-color: #4FB99F;*/
    /*background-color: #00ADB5;*/
    /*background-color: #6BB983;*/
    background-color: #00AD80;

}

/* Standard media queries breakpoints */

@media (min-width: 320px) and (max-width: 480px) {
    /* smartphones, iPhone, portrait 480x320 phones */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .productos_finales_home img {

        padding-bottom: 15px;
    }

    .my_home_banner_image {

        bottom: 0;
        top: 0;
        position: relative;
        z-index: 0;
        width: 60%;
        display: block;
        margin-right: auto;
        margin-left: 165px;
    }

    /*.my_home_banner_image {*/
    /*display: none;*/
    /*}*/
    .my_home_banner_title {
        color: white;
        font-size: 36px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        text-decoration: none;
        background-color: #969696;
        display: inline-block;
        text-align: center;
        vertical-align: middle;
        cursor: pointer;
        color: #fff;
        font-weight: 700;
        font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
        text-shadow: 0 -1px 0 rgba(0, 0, 0, .25);
        letter-spacing: 0;
        line-height: 1.2;
        -webkit-font-smoothing: antialiased;
        -webkit-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -ms-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -moz-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -o-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        background-image: linear-gradient(to bottom, rgba(255, 255, 255, .09) 0%, rgba(0, 0, 0, .09) 100%);
        font-size: 1.4rem;
        padding: 22px 30px;
        border-radius: 6px;
        border: none;
    }

.my_home_banner_left {
    margin-left: 10px;
    z-index: 100;
}

.stickers_referenciales {
    margin-bottom: 5px;
}

}

@media (min-width: 481px) {
    /* portrait e-readers (Nook/Kindle), smaller tablets @ 600 or @ 640 wide. */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 40%;
        display: block;
        margin-right: auto;
        margin-left: 185px;
    }

    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

}

@media (min-width: 641px) {
    /* portrait tablets, portrait iPad, landscape e-readers, landscape 800x480 or 854x480 phones */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 70%;
    }

    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

    .my_home_banner_lef_text {
        margin-left: 10px;
        z-index: 100;
    }

}

@media (min-width: 961px) {
    /* tablet, landscape iPad, lo-res laptops ands desktops */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 60%;
    }

    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

}

@media (min-width: 1025px) {
    /* big landscape tablets, laptops, and desktops */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 55%;
    }

    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

    .subscribe_field {
        width: 350px;
    }

}

@media (min-width: 1281px) {
    /* hi-res laptops and desktops */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 50%;
    }

    /*.my_home_banner_image_left {*/
    /*display: none;*/
    /*}*/
    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

    .subscribe_field {
        width: 350px;
    }
}

.center-video {
    margin: 0 auto;
    width: 400px;
}

Body:
Write this:

@media (max-width: 480px) {

in place of:

@media (min-width: 320px) and (max-width: 480px) {


问:
Handling asynchronous threads
I (think that I) understand the differences between threads and tasks.

Threads allow us to do multiple things in parallel (they are CPU-bound).

Asynchronous tasks release the processor time while some I/O work is done (they are I/O-bound).

Now, let's say I want to do multiple asynchronous tasks in parallel. For example, I want to download several pages of a paged response at the same time. Or, I want to write new data into two different databases. What is the correct way to handle the threads? Should they be async and awaited? Or can the async operation be just inside the thread? What is the best practice for error handling?

I have tried creating my own utility method to start a new async thread, but I have a feeling that it can go horribly wrong.

```<code>public static Task<Thread> RunInThreadAsync<T>(T actionParam, Func<T, Task> asyncAction)
{
    var thread = new Thread(async () => await asyncAction(actionParam));
    thread.Start();
    return thread;
}
</code>```

Is this ok? Or should the method be public static async Task<Thread>? If yes, what should be awaited? There is no thread.StartAsync(). Or should I use Task.Run instead?

Note: Using await Task.WhenAll or similar approaches without an explicit new thread is not an option for me. The "worker" thread is run in background (to avoid blocking the main thread) and is later processed by other services in the system.

答:
System.Threading.Thread has been in .NET since version 1.1.  It allows you to control multiple worker threads within your application.  This only uses 1 core of your CPU.

The Task Parallel Library (TPL) introduced the ability to leverage multiple cores on your machine with async Tasks or System.Threading.Tasks.Task<T>.

My approach for your "multiple downloader" scenario, would be to create a new CancellationTokenSource which allows me to cancel my Tasks.  The I would start creating my Task<T> and start them.  You can use Task.WaitAll() to sit and wait.

You should be aware that you can chain your tasks together in a sequence by using the ContinueWith<T>() method.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
async class Program
{
    static bool DownloadFile (string path)
    {
        // Do something here. long running task.

        // check for cancellation -> Task.Factory.CancellationToken.IsCancellationRequested

        return true;
    }
    static async void Main(string[] args)
    {
        var paths = new[] { "Somepaths", "to the files youwant", "to download" };
        List<Task<bool>> results = new List<Task<bool>>();
        var cts = new System.Threading.CancellationTokenSource();

        foreach(var path in paths)
        {
            var task = new Task<bool>(_path => DownloadFile((string)_path), path, cts.Token);
            task.Start();
            results.Add(task);
        }

        // use cts.Cancel(); to cancel all associated tasks.

        // Task.WhenAll() to do something when they are all done.
        // Task.WaitAll( results.ToArray() );  // to sit and wait.

        Console.WriteLine("Press <Enter> to quit.");
        var final = Console.ReadLine();
    }
}
</code>```

}

Title: Handling asynchronous threads

Body:
I (think that I) understand the differences between threads and tasks.

Threads allow us to do multiple things in parallel (they are CPU-bound).

Asynchronous tasks release the processor time while some I/O work is done (they are I/O-bound).

Now, let's say I want to do multiple asynchronous tasks in parallel. For example, I want to download several pages of a paged response at the same time. Or, I want to write new data into two different databases. What is the correct way to handle the threads? Should they be async and awaited? Or can the async operation be just inside the thread? What is the best practice for error handling?

I have tried creating my own utility method to start a new async thread, but I have a feeling that it can go horribly wrong.

public static Task<Thread> RunInThreadAsync<T>(T actionParam, Func<T, Task> asyncAction)
{
    var thread = new Thread(async () => await asyncAction(actionParam));
    thread.Start();
    return thread;
}

Is this ok? Or should the method be public static async Task<Thread>? If yes, what should be awaited? There is no thread.StartAsync(). Or should I use Task.Run instead?

Note: Using await Task.WhenAll or similar approaches without an explicit new thread is not an option for me. The "worker" thread is run in background (to avoid blocking the main thread) and is later processed by other services in the system.

Body:
System.Threading.Thread has been in .NET since version 1.1.  It allows you to control multiple worker threads within your application.  This only uses 1 core of your CPU.

The Task Parallel Library (TPL) introduced the ability to leverage multiple cores on your machine with async Tasks or System.Threading.Tasks.Task<T>.

My approach for your "multiple downloader" scenario, would be to create a new CancellationTokenSource which allows me to cancel my Tasks.  The I would start creating my Task<T> and start them.  You can use Task.WaitAll() to sit and wait.

You should be aware that you can chain your tasks together in a sequence by using the ContinueWith<T>() method.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
async class Program
{
    static bool DownloadFile (string path)
    {
        // Do something here. long running task.

        // check for cancellation -> Task.Factory.CancellationToken.IsCancellationRequested

        return true;
    }
    static async void Main(string[] args)
    {
        var paths = new[] { "Somepaths", "to the files youwant", "to download" };
        List<Task<bool>> results = new List<Task<bool>>();
        var cts = new System.Threading.CancellationTokenSource();

        foreach(var path in paths)
        {
            var task = new Task<bool>(_path => DownloadFile((string)_path), path, cts.Token);
            task.Start();
            results.Add(task);
        }

        // use cts.Cancel(); to cancel all associated tasks.

        // Task.WhenAll() to do something when they are all done.
        // Task.WaitAll( results.ToArray() );  // to sit and wait.

        Console.WriteLine("Press <Enter> to quit.");
        var final = Console.ReadLine();
    }
}

}


问:
How to access chrome storage from multiple HTML files in a chrome extension
I already have an options page on my chrome extension, and I am trying to create several other pages in my extension directory which need to make use of the chrome storage data gathered by popup.html.

I have tried adding the new HTML page to the options page attribute in the manifest.json file, but that prevents the extension from loading. When accessing the chrome storage with a "DOMContentLoaded" event on the new non-options HTML page, as follows:

```<code>document.addEventListener("DOMContentLoaded", function () {
    getData();
}, false);

function getData() {
    chrome.storage.local.get(['data'], function (result) {
        console.log(result.data);
        setFormData(result.data[0])
    });
}

function setFormData(data){
    console.log(data)
}
</code>```

I get this error:

Uncaught TypeError: Cannot read property 'local' of undefined

I assume means that newHTML.html is not making use of the manifest file, but I am note sure how I tell the manifest file about newHTML.

Here is the manifest file:

```<code>{
    "name": "ExtensionName!",
    "version": "1.0",
    "description": "A Chrome Extension!",
    "permissions": ["activeTab", "declarativeContent", "storage","<all_urls>"],
    "background": {
      "scripts": ["background.js"],
      "persistent": false
    },
    "options_page": "formMenu.html",
    "page_action": {
      "default_popup": "popup.html",
      "default_icon": {
        "16": "images/get_started16.png"
      }
    },
    "icons": {
      "16": "images/get_started16.png"
    },
    "manifest_version": 2,
    "content_security_policy": "script-src 'self' https://code.jquery.com https://cdnjs.cloudflare.com https://stackpath.bootstrapcdn.com https://use.fontawesome.com; object-src 'self'",
    "externally_connectable": {
      "ids": ["*"]
    }
  }
</code>```

答:
Your code has acces to chrome.storage when it is running in the context of your extension.

If you open file://.../newHTML.html, it's just a normal javascript context.

Use chrome.runtime.getURL("newHTML.html") to get an extension url which looks like this: chrome-extension://[id]/newHTML.html.

Also there is no need to wait for DOMContentLoaded to acces localStorage.

Body:
I already have an options page on my chrome extension, and I am trying to create several other pages in my extension directory which need to make use of the chrome storage data gathered by popup.html.

I have tried adding the new HTML page to the options page attribute in the manifest.json file, but that prevents the extension from loading. When accessing the chrome storage with a "DOMContentLoaded" event on the new non-options HTML page, as follows:

document.addEventListener("DOMContentLoaded", function () {
    getData();
}, false);

function getData() {
    chrome.storage.local.get(['data'], function (result) {
        console.log(result.data);
        setFormData(result.data[0])
    });
}

function setFormData(data){
    console.log(data)
}

I get this error:

Uncaught TypeError: Cannot read property 'local' of undefined

I assume means that newHTML.html is not making use of the manifest file, but I am note sure how I tell the manifest file about newHTML.

Here is the manifest file:

{
    "name": "ExtensionName!",
    "version": "1.0",
    "description": "A Chrome Extension!",
    "permissions": ["activeTab", "declarativeContent", "storage","<all_urls>"],
    "background": {
      "scripts": ["background.js"],
      "persistent": false
    },
    "options_page": "formMenu.html",
    "page_action": {
      "default_popup": "popup.html",
      "default_icon": {
        "16": "images/get_started16.png"
      }
    },
    "icons": {
      "16": "images/get_started16.png"
    },
    "manifest_version": 2,
    "content_security_policy": "script-src 'self' https://code.jquery.com https://cdnjs.cloudflare.com https://stackpath.bootstrapcdn.com https://use.fontawesome.com; object-src 'self'",
    "externally_connectable": {
      "ids": ["*"]
    }
  }


问:
Conditional correlations using an IF statement - Python
I am trying to conduct an IF statement in order to evaluate conditional threshold correlations. The equation is as follows:

I tried doing an IF statement, but it doesn't work. I kind of managed to do it with pandas, but it would be really a bad code.

p = np.arange(0.1,1,0.1)

r1 = log_r['AEX']; r2 = log_r['MBI10']
np.quantile(r1, p[0])

corrcoef = pd.Series()
if r1<np.quantile(r1,p[0]) & r2<np.quantile(r2,p[0]) & p[0]<0.5:
    corrcoef[0] = np.corrcoef(r1,r2)
```

<p>Alternatively, I did the following:</p>

<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame(pd.concat([log_r['AEX'],log_r['MBI10']],axis=1))
df['p0.1 AEX'] = (df['AEX'] < np.quantile(df['AEX'], p[0]))*df['AEX']
df['p0.1 MBI10'] = (df['MBI10'] < np.quantile(df['MBI10'], p[0]))*df['MBI10']
np.corrcoef(df['p0.1 AEX'],df['p0.1 MBI10'])
</code>```

This works, however it would be really messy since I would need to do this for not only p[0] but for the entire np.arange and also AEX and MBI10 are only 2/36 pairs that I have, so I am really looking for a more elegant solution to this. Thanks!

I am trying to get a correlation coefficient populated in the first row of corrcoef. I am getting the following error when I try to do the for loop:

TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]

答:
The bitwise AND operator & takes precedence over < (unlike the boolean operator and, which binds more weakly than <), so this expression doesn't get parsed the way you intend.

```<code>r1<np.quantile(r1,p[0]) & r2<np.quantile(r2,p[0]) & p[0]<0.5
</code>```

is equivalent to

```<code>r1 < (np.quantile(r1,p[0]) & r2) < (np.quantile(r2,p[0]) & p[0]) < 0.5
</code>```

(Note: In Python, a < b < c is a syntactic shorthand for a < b and b < c, which explains why this is still interpreted as a valid expression.)

Body:
I am trying to conduct an IF statement in order to evaluate conditional threshold correlations. The equation is as follows:

I tried doing an IF statement, but it doesn't work. I kind of managed to do it with pandas, but it would be really a bad code.

p = np.arange(0.1,1,0.1)

r1 = log_r['AEX']; r2 = log_r['MBI10']
np.quantile(r1, p[0])

corrcoef = pd.Series()
if r1<np.quantile(r1,p[0]) & r2<np.quantile(r2,p[0]) & p[0]<0.5:
    corrcoef[0] = np.corrcoef(r1,r2)

Alternatively, I did the following:

df = pd.DataFrame(pd.concat([log_r['AEX'],log_r['MBI10']],axis=1))
df['p0.1 AEX'] = (df['AEX'] < np.quantile(df['AEX'], p[0]))*df['AEX']
df['p0.1 MBI10'] = (df['MBI10'] < np.quantile(df['MBI10'], p[0]))*df['MBI10']
np.corrcoef(df['p0.1 AEX'],df['p0.1 MBI10'])

This works, however it would be really messy since I would need to do this for not only p[0] but for the entire np.arange and also AEX and MBI10 are only 2/36 pairs that I have, so I am really looking for a more elegant solution to this. Thanks!

I am trying to get a correlation coefficient populated in the first row of corrcoef. I am getting the following error when I try to do the for loop:

TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]

Body:
The bitwise AND operator & takes precedence over < (unlike the boolean operator and, which binds more weakly than <), so this expression doesn't get parsed the way you intend.

r1<np.quantile(r1,p[0]) & r2<np.quantile(r2,p[0]) & p[0]<0.5

is equivalent to

r1 < (np.quantile(r1,p[0]) & r2) < (np.quantile(r2,p[0]) & p[0]) < 0.5

(Note: In Python, a < b < c is a syntactic shorthand for a < b and b < c, which explains why this is still interpreted as a valid expression.)


问:
Linker Error in VS 2017 community with GLAD
This code is a direct copy of an example.  I have references set, however it appears that GLAD doesn't have a lib file; and I think that is what I am missing.  Does anyone know a way around this issue?</p>

```<code>#include <iostream>

// GLAD
#include <glad/glad.h>

// GLFW
#include <GLFW/glfw3.h>

// This example is taken from https://learnopengl.com/
// https://learnopengl.com/code_viewer.php?code=getting-started/hellowindow2
// The code originally used GLEW, I replaced it with Glad

// Compile:
// g++ example/c++/hellowindow2.cpp -Ibuild/include build/src/glad.c -lglfw -ldl

// Function prototypes
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);

// Window dimensions
const GLuint WIDTH = 800, HEIGHT = 600;

// The MAIN function, from here we start the application and run the game loop
int main()
{
    std::cout << "Starting GLFW context, OpenGL 3.3" << std::endl;
    // Init GLFW
    glfwInit();
    // Set all the required options for GLFW
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    // Create a GLFWwindow object that we can use for GLFW's functions
    GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", NULL, NULL);
    glfwMakeContextCurrent(window);
    if (window == NULL)
    {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }

    // Set the required callback functions
    glfwSetKeyCallback(window, key_callback);

    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    {
        std::cout << "Failed to initialize OpenGL context" << std::endl;
        return -1;
    }

    // Define the viewport dimensions
    glViewport(0, 0, WIDTH, HEIGHT);

    // Game loop
    while (!glfwWindowShouldClose(window))
    {
        // Check if any events have been activated (key pressed, mouse moved etc.) and call corresponding response functions
        glfwPollEvents();

        // Render
        // Clear the colorbuffer
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        // Swap the screen buffers
        glfwSwapBuffers(window);
    }

    // Terminates GLFW, clearing any resources allocated by GLFW.
    glfwTerminate();
    return 0;
}

// Is called whenever a key is pressed/released via GLFW
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
    std::cout << key << std::endl;
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
        glfwSetWindowShouldClose(window, GL_TRUE);
}
</code>```

答:
Add file glad.c to your solution.

Go to Visual Studio > Solution Explorer > Source Files > Add > Existing Item ..

OwnerDisplayName: Beachhouse

Body:
This code is a direct copy of an example.  I have references set, however it appears that GLAD doesn't have a lib file; and I think that is what I am missing.  Does anyone know a way around this issue?

#include <iostream>

// GLAD
#include <glad/glad.h>

// GLFW
#include <GLFW/glfw3.h>

// This example is taken from https://learnopengl.com/
// https://learnopengl.com/code_viewer.php?code=getting-started/hellowindow2
// The code originally used GLEW, I replaced it with Glad

// Compile:
// g++ example/c++/hellowindow2.cpp -Ibuild/include build/src/glad.c -lglfw -ldl

// Function prototypes
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);

// Window dimensions
const GLuint WIDTH = 800, HEIGHT = 600;

// The MAIN function, from here we start the application and run the game loop
int main()
{
    std::cout << "Starting GLFW context, OpenGL 3.3" << std::endl;
    // Init GLFW
    glfwInit();
    // Set all the required options for GLFW
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    // Create a GLFWwindow object that we can use for GLFW's functions
    GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", NULL, NULL);
    glfwMakeContextCurrent(window);
    if (window == NULL)
    {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }

    // Set the required callback functions
    glfwSetKeyCallback(window, key_callback);

    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    {
        std::cout << "Failed to initialize OpenGL context" << std::endl;
        return -1;
    }

    // Define the viewport dimensions
    glViewport(0, 0, WIDTH, HEIGHT);

    // Game loop
    while (!glfwWindowShouldClose(window))
    {
        // Check if any events have been activated (key pressed, mouse moved etc.) and call corresponding response functions
        glfwPollEvents();

        // Render
        // Clear the colorbuffer
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        // Swap the screen buffers
        glfwSwapBuffers(window);
    }

    // Terminates GLFW, clearing any resources allocated by GLFW.
    glfwTerminate();
    return 0;
}

// Is called whenever a key is pressed/released via GLFW
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
    std::cout << key << std::endl;
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
        glfwSetWindowShouldClose(window, GL_TRUE);
}


问:
How to read EXCEL XLSX file with string values in iOS?
I've been searching all over the internet for hours and hours and I've tried so many solutions but I'm never succeeding with this problem. So, basically, I'm a java-student developer and trying to create an app for both android and iOS. In Android, everything just works perfectly, if you ever find a problem, EASY PEASY! No problem to find solutions. But for iOS? Well.. I bet you know the answer! It's so damn hard to get things together and work properly.

Tried multiple libraries from git, all of them gives me an error since there either only can handle integers or there's problem with something else. None of these guides however seems to work well with my brain.

What I wonder is if somebody could give me a code-snippet or somehow a guide on how to just read an xls/xlsx/csv file and save the values into an array. I have two columns and would like to save them into two different arrays. The Excel file contains thousands of coordinates, so one array for latitude and one array for longitude.

Hope somebody have a tip or sort of solution for this!

Thanks

答:
I would go in excel and convert your xslx file into a csv file. Then I’d try this library: https://github.com/yaslab/CSV.swift/blob/master/README.md

From the documentation on this library, it handles strings.

On that github page there are multiple ways to generate this array (either the csv as a Swift string or a file). This is the example for a file from that GitHub repo:

```<code>import CSV

let csvString = "1,foo\n2,bar"
let csv = try! CSVReader(string: csvString)
while let row = csv.next() {
    print("\(row)")
}
// => ["1", "foo"]
// => ["2", "bar"]
</code>```

A 2-d array would be natural for this (if you’re still set on two separate arrays, see the edit at the end) Check out this answer for how it would work (code from top answer below): Swift append to 2d array

```<code>private var cards = [[Int]]()

init() {
     //Fill cards array by adding all cards
     for i in 0...12{
         for x in 0...3{
            cards.append([i+2,x])
        }
     }
 }
</code>```

So basically your code you’d need to mix the first and second code snippets in this answer. Declare the array(s), then use the csv library as in one of the examples on the README page, then use Swift’s append function to add the latitude and longitude coordinates (you’d do this on the line replacing print("(row)") in the first example).

I have not personally tried this GitHub repo but based on the issues that have been raised and stars my guess is it should work.

Best of luck!

Edit: just realized you wanted two different arrays. In that case you’ll just declare two string arrays and instead of the print("(row)") from the first code snippet you’ll append latitude to one array and longitude to another array as seen in the second code snippet.

Body:
I would go in excel and convert your xslx file into a csv file. Then I’d try this library: https://github.com/yaslab/CSV.swift/blob/master/README.md

From the documentation on this library, it handles strings.

On that github page there are multiple ways to generate this array (either the csv as a Swift string or a file). This is the example for a file from that GitHub repo:

import CSV

let csvString = "1,foo\n2,bar"
let csv = try! CSVReader(string: csvString)
while let row = csv.next() {
    print("\(row)")
}
// => ["1", "foo"]
// => ["2", "bar"]

A 2-d array would be natural for this (if you’re still set on two separate arrays, see the edit at the end) Check out this answer for how it would work (code from top answer below): Swift append to 2d array

private var cards = [[Int]]()

init() {
     //Fill cards array by adding all cards
     for i in 0...12{
         for x in 0...3{
            cards.append([i+2,x])
        }
     }
 }

So basically your code you’d need to mix the first and second code snippets in this answer. Declare the array(s), then use the csv library as in one of the examples on the README page, then use Swift’s append function to add the latitude and longitude coordinates (you’d do this on the line replacing print("(row)") in the first example).

I have not personally tried this GitHub repo but based on the issues that have been raised and stars my guess is it should work.

Best of luck!

Edit: just realized you wanted two different arrays. In that case you’ll just declare two string arrays and instead of the print("(row)") from the first code snippet you’ll append latitude to one array and longitude to another array as seen in the second code snippet.


问:
How to pd.fillna(mean()) acccording to a column value which changes?
I have the following dataframe:

```<code>data/hora
2017-08-18 09:22:33   22162          NaN        65.9           NaN          NaN
2017-10-03 11:08:26   22162          NaN        60.5           NaN          NaN
2018-02-17 01:45:24   22162          NaN        69.7           NaN          NaN
2018-02-17 01:45:55   74034          NaN        67.5           NaN          NaN
2018-02-17 01:46:29   74034          NaN        65.4           NaN          NaN
2018-02-17 01:47:20   74034          NaN        63.3           NaN          NaN
2018-02-17 01:48:35   74034          NaN        61.3           NaN          NaN
2018-02-17 01:49:08   17448          NaN        63.4           NaN          NaN
2018-02-17 01:49:31   17448          NaN        65.5           NaN          NaN
2018-02-17 01:49:55   17448          NaN        67.6           NaN          NaN
</code>```

To which I want to fill the NaN as the mean of which column. However, this value change as the 'Machine' changes - there are three machine values.
Therefore, I need I fillna that changes according to Machine column value.

I tried:

```<code>for i in df:
    if i.isin(df.loc[df['Machine'] == '22162']):
        df.fillna(df.loc[df['Machine'] == '22162'].mean)
    elif i.isin(df.loc[df['Machine'] == '17448']):
        df.fillna(df.loc[df['Machine'] == '17448'].mean)
    elif i.isin(df.loc[df['Machine'] == '74034']):
        df.fillna(df.loc[df['Machine'] == '74034'].mean)
</code>```

But it didn't work.

Thanks!

答:
This is how I've solved my problem:

```<code>grupo = df.groupby(df["Machine"])
cada_maquina = list(grupo)

for i in range(3):
    cada_maquina[i][1].fillna(cada_maquina[i][1].mean(), inplace=True)
</code>```

Thank you very much for every comment! :D

Body:
I have the following dataframe:

data/hora
2017-08-18 09:22:33   22162          NaN        65.9           NaN          NaN
2017-10-03 11:08:26   22162          NaN        60.5           NaN          NaN
2018-02-17 01:45:24   22162          NaN        69.7           NaN          NaN
2018-02-17 01:45:55   74034          NaN        67.5           NaN          NaN
2018-02-17 01:46:29   74034          NaN        65.4           NaN          NaN
2018-02-17 01:47:20   74034          NaN        63.3           NaN          NaN
2018-02-17 01:48:35   74034          NaN        61.3           NaN          NaN
2018-02-17 01:49:08   17448          NaN        63.4           NaN          NaN
2018-02-17 01:49:31   17448          NaN        65.5           NaN          NaN
2018-02-17 01:49:55   17448          NaN        67.6           NaN          NaN

To which I want to fill the NaN as the mean of which column. However, this value change as the 'Machine' changes - there are three machine values.
Therefore, I need I fillna that changes according to Machine column value.

I tried:

for i in df:
    if i.isin(df.loc[df['Machine'] == '22162']):
        df.fillna(df.loc[df['Machine'] == '22162'].mean)
    elif i.isin(df.loc[df['Machine'] == '17448']):
        df.fillna(df.loc[df['Machine'] == '17448'].mean)
    elif i.isin(df.loc[df['Machine'] == '74034']):
        df.fillna(df.loc[df['Machine'] == '74034'].mean)

But it didn't work.

Thanks!

Body:
This is how I've solved my problem:

grupo = df.groupby(df["Machine"])
cada_maquina = list(grupo)

for i in range(3):
    cada_maquina[i][1].fillna(cada_maquina[i][1].mean(), inplace=True)

Thank you very much for every comment! :D


问:
Optimizing Fenwick Tree (C++)
I have the following implementation of the Fenwick Tree algorithm.

```<code>#include <bits/stdc++.h>
#define LSOne(S) (S & (-S))
using namespace std;
typedef long long int L;

int rsq(L b, L x[]){
    int sum=0;
    for(; b; b-=LSOne(b)) sum+=x[b];
    return sum;
}

void adjust(int k, L v, L x[], int n){
    for(; k<=n;k+=LSOne(k)) x[k]+=v;
}

int main(){
    int n,q; cin>>n>>q;
    L ft[n+1]; memset(ft,0,sizeof(ft));
    while(q--){
        char x; int i,j; cin>>x;
        if(x=='+'){
            cin>>i>>j;
            adjust(i+1,j,ft,n);
        } else if(x=='?') {
            cin>>i;
            cout<<rsq(i,ft)<<endl;
        }
    }
}
</code>```

This program should be able to run for N<=5000000 and process Q<=5000000. And it should be able to run under 9 sec. But after submitting this problem I was given a verdict of Time Limit Exceeded (TLE). I have tried every measure to optimize this code but to no avail, it still gave me TLE. How could I possibly optimize this code so that it could run under 9 secs. Thank you very much.

答:
The time needed to read 500000 lines from stdin could be the problem.
Did you try to optimize IO buffering:</p>

```<code>int main() {
    cin.tie(nullptr);
    std::ios::sync_with_stdio(false);
    ...
</code>```

ContentLicense: CC BY-SA 3.0

Title: Optimizing Fenwick Tree (C++)

Body:
I have the following implementation of the Fenwick Tree algorithm.

#include <bits/stdc++.h>
#define LSOne(S) (S & (-S))
using namespace std;
typedef long long int L;

int rsq(L b, L x[]){
    int sum=0;
    for(; b; b-=LSOne(b)) sum+=x[b];
    return sum;
}

void adjust(int k, L v, L x[], int n){
    for(; k<=n;k+=LSOne(k)) x[k]+=v;
}

int main(){
    int n,q; cin>>n>>q;
    L ft[n+1]; memset(ft,0,sizeof(ft));
    while(q--){
        char x; int i,j; cin>>x;
        if(x=='+'){
            cin>>i>>j;
            adjust(i+1,j,ft,n);
        } else if(x=='?') {
            cin>>i;
            cout<<rsq(i,ft)<<endl;
        }
    }
}

This program should be able to run for N<=5000000 and process Q<=5000000. And it should be able to run under 9 sec. But after submitting this problem I was given a verdict of Time Limit Exceeded (TLE). I have tried every measure to optimize this code but to no avail, it still gave me TLE. How could I possibly optimize this code so that it could run under 9 secs. Thank you very much.

Body:
The time needed to read 500000 lines from stdin could be the problem.
Did you try to optimize IO buffering:

int main() {
    cin.tie(nullptr);
    std::ios::sync_with_stdio(false);
    ...


问:
I want to read from Properties file and put that value in a string based on a key from file
I am new learning python and I have to deal with the properties file in that file the value will be present in key value pair and some how I think managed to readFile but not able to store or print the value based on a key.

I have tried with the jproperties libraries installed through pip.I have read the values in the object but unable to fetch the records from it.
Have gone through https://pypi.org/project/jproperties/#parsing-a-property-file website for reference

```<code>from jproperties import Properties

class PropertiesReader:
    p = Properties()
    with open("foobar.properties", "rt") as f:
        p.load(f, "utf-8")

    s = p.__getitem__("name","value")
    z = p.__getattribute__("email","mail")
    print(s)
    print(z)
</code>```

and the properties file

```<code>foobar.properties
    name = Harsh
    email = abc.xyz
</code>```

and the output is

```<code>Traceback (most recent call last):
  File "/home/harshk/PycharmProjects/demoPythonPOC/scratch.py", line 4, in <module>
    class PropertiesReader:
  File "/home/harshk/PycharmProjects/demoPythonPOC/scratch.py", line 7, in PropertiesReader
    p.load(f, "utf-8")
  File "/usr/local/lib/python3.7/site-packages/jproperties.py", line 804, in load
    self._parse()
  File "/usr/local/lib/python3.7/site-packages/jproperties.py", line 731, in _parse
    while self._parse_logical_line():
  File "/usr/local/lib/python3.7/site-packages/jproperties.py", line 686, in _parse_logical_line
    self._skip_whitespace()
  File "/usr/local/lib/python3.7/site-packages/jproperties.py", line 438, in _skip_whitespace
    c = self._peek()
  File "/usr/local/lib/python3.7/site-packages/jproperties.py", line 378, in _peek
    c = self._source_file.read(1)
  File "/usr/local/lib/python3.7/codecs.py", line 500, in read
    data = self.bytebuffer + newdata
TypeError: can't concat str to bytes

Process finished with exit code 1
</code>```

I want to print like

```<code>Harsh
abc.xyz
</code>```

答:
Test below code :  https://repl.it/repls/EmptyRowdyCategories</p>

```<code>from jproperties import Properties

p = Properties()
with open("foobar.properties", "rb") as f:
    p.load(f, "utf-8")

print(p["name"].data)
print(p["email"].data)
</code>```

Body:
I am new learning python and I have to deal with the properties file in that file the value will be present in key value pair and some how I think managed to readFile but not able to store or print the value based on a key.

I have tried with the jproperties libraries installed through pip.I have read the values in the object but unable to fetch the records from it.
Have gone through https://pypi.org/project/jproperties/#parsing-a-property-file website for reference

from jproperties import Properties

class PropertiesReader:
    p = Properties()
    with open("foobar.properties", "rt") as f:
        p.load(f, "utf-8")

    s = p.__getitem__("name","value")
    z = p.__getattribute__("email","mail")
    print(s)
    print(z)

and the properties file

foobar.properties
    name = Harsh
    email = abc.xyz

and the output is

Traceback (most recent call last):
  File "/home/harshk/PycharmProjects/demoPythonPOC/scratch.py", line 4, in <module>
    class PropertiesReader:
  File "/home/harshk/PycharmProjects/demoPythonPOC/scratch.py", line 7, in PropertiesReader
    p.load(f, "utf-8")
  File "/usr/local/lib/python3.7/site-packages/jproperties.py", line 804, in load
    self._parse()
  File "/usr/local/lib/python3.7/site-packages/jproperties.py", line 731, in _parse
    while self._parse_logical_line():
  File "/usr/local/lib/python3.7/site-packages/jproperties.py", line 686, in _parse_logical_line
    self._skip_whitespace()
  File "/usr/local/lib/python3.7/site-packages/jproperties.py", line 438, in _skip_whitespace
    c = self._peek()
  File "/usr/local/lib/python3.7/site-packages/jproperties.py", line 378, in _peek
    c = self._source_file.read(1)
  File "/usr/local/lib/python3.7/codecs.py", line 500, in read
    data = self.bytebuffer + newdata
TypeError: can't concat str to bytes

Process finished with exit code 1

I want to print like

Harsh
abc.xyz

Body:
Test below code :  https://repl.it/repls/EmptyRowdyCategories

from jproperties import Properties

p = Properties()
with open("foobar.properties", "rb") as f:
    p.load(f, "utf-8")

print(p["name"].data)
print(p["email"].data)


问:
Can't Pass Resized QLabel Geometry From Class
I’m using PyQt5 and OpenCV.  I want to create a class that reads a frame of the video and performs a rubber band stretch to generate the geometry that will be used in by a different class to crop the video stream (this second class is not included in this example).

In this example, an image is captured from a webcam stream, then displayed.  A rubber band stretch over the image generates a geometry that is printed.  The geometry prints without issue within the ReGeomVid class, but not within main().  I need to get the geometry into main(). Help is appreciated.

```<code>import sys, cv2
from PyQt5.QtWidgets import QRubberBand, QApplication, QLabel
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtCore import QRect, QSize

class ReGeomVid (QLabel):
    def __init__(self, cap, parent=None):
        super(ReGeomVid, self).__init__(parent)
        self.cap = cap
        self.currentQRect = QRect()
        self.initUI()

    def initUI (self):
        ret, frame = self.cap.read() #First frame read is black
        ret, frame = self.cap.read() #Second frame read is normal
        if ret == True:
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            img = QImage(frame,frame.shape[1], frame.shape[0], QImage.Format_RGB888)
            pix = QPixmap.fromImage(img)
            self.setPixmap(QPixmap(pix))

    def mousePressEvent (self, eventQMouseEvent):
        self.originQPoint = eventQMouseEvent.pos()
        print(self.originQPoint)
        self.currentQRubberBand = QRubberBand(QRubberBand.Rectangle, self)
        self.currentQRubberBand.setGeometry(QRect(self.originQPoint, QSize()))
        self.currentQRubberBand.show()

    def mouseMoveEvent (self, eventQMouseEvent):
        self.currentQRubberBand.setGeometry(QRect(self.originQPoint, eventQMouseEvent.pos()).normalized())

    def mouseReleaseEvent (self, eventQMouseEvent):
        self.currentQRubberBand.hide()
        self.currentQRect = self.currentQRubberBand.geometry()
        self.currentQRubberBand.deleteLater()
        self.croppedPixmap = self.pixmap().copy(self.currentQRect)
        print("In mouserelease: Geometry = ", self.currentQRect)

if __name__ == '__main__':
    myQApplication = QApplication(sys.argv)
    stream = cv2.VideoCapture(0)
    x = ReGeomVid(stream)
    x.show()
    pixMainGeom = x.currentQRect
    print("In main: Geometry = ", x.currentQRect)
    sys.exit(myQApplication.exec_())
</code>```

答:
Your variable self.currentQRect is set in mouseReleaseEvent. So, when the print in your main is executed, it's still invalid.

Use a signal to run the code in your main when the self.currentQRect is ready:

```<code>class ReGeomVid (QLabel):
    currentQRectChanged = pyqtSignal(QRect)
...
    def mouseReleaseEvent (self, eventQMouseEvent):
        ...
        self.currentQRectChanged.emit(self.currentQRect)

def printCurrentQRect(rect):
    print("In main: Geometry = ", rect)

if __name__ == '__main__':
    myQApplication = QApplication(sys.argv)
    stream = cv2.VideoCapture(0)
    x = ReGeomVid(stream)
    x.show()
    x.currentQRectChanged.connect(printCurrentQRect)
    sys.exit(myQApplication.exec_())
</code>```

Body:
I’m using PyQt5 and OpenCV.  I want to create a class that reads a frame of the video and performs a rubber band stretch to generate the geometry that will be used in by a different class to crop the video stream (this second class is not included in this example).

In this example, an image is captured from a webcam stream, then displayed.  A rubber band stretch over the image generates a geometry that is printed.  The geometry prints without issue within the ReGeomVid class, but not within main().  I need to get the geometry into main(). Help is appreciated.

import sys, cv2
from PyQt5.QtWidgets import QRubberBand, QApplication, QLabel
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtCore import QRect, QSize

class ReGeomVid (QLabel):
    def __init__(self, cap, parent=None):
        super(ReGeomVid, self).__init__(parent)
        self.cap = cap
        self.currentQRect = QRect()
        self.initUI()

    def initUI (self):
        ret, frame = self.cap.read() #First frame read is black
        ret, frame = self.cap.read() #Second frame read is normal
        if ret == True:
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            img = QImage(frame,frame.shape[1], frame.shape[0], QImage.Format_RGB888)
            pix = QPixmap.fromImage(img)
            self.setPixmap(QPixmap(pix))

    def mousePressEvent (self, eventQMouseEvent):
        self.originQPoint = eventQMouseEvent.pos()
        print(self.originQPoint)
        self.currentQRubberBand = QRubberBand(QRubberBand.Rectangle, self)
        self.currentQRubberBand.setGeometry(QRect(self.originQPoint, QSize()))
        self.currentQRubberBand.show()

    def mouseMoveEvent (self, eventQMouseEvent):
        self.currentQRubberBand.setGeometry(QRect(self.originQPoint, eventQMouseEvent.pos()).normalized())

    def mouseReleaseEvent (self, eventQMouseEvent):
        self.currentQRubberBand.hide()
        self.currentQRect = self.currentQRubberBand.geometry()
        self.currentQRubberBand.deleteLater()
        self.croppedPixmap = self.pixmap().copy(self.currentQRect)
        print("In mouserelease: Geometry = ", self.currentQRect)

if __name__ == '__main__':
    myQApplication = QApplication(sys.argv)
    stream = cv2.VideoCapture(0)
    x = ReGeomVid(stream)
    x.show()
    pixMainGeom = x.currentQRect
    print("In main: Geometry = ", x.currentQRect)
    sys.exit(myQApplication.exec_())

Body:
Your variable self.currentQRect is set in mouseReleaseEvent. So, when the print in your main is executed, it's still invalid.

Use a signal to run the code in your main when the self.currentQRect is ready:

class ReGeomVid (QLabel):
    currentQRectChanged = pyqtSignal(QRect)
...
    def mouseReleaseEvent (self, eventQMouseEvent):
        ...
        self.currentQRectChanged.emit(self.currentQRect)

def printCurrentQRect(rect):
    print("In main: Geometry = ", rect)

if __name__ == '__main__':
    myQApplication = QApplication(sys.argv)
    stream = cv2.VideoCapture(0)
    x = ReGeomVid(stream)
    x.show()
    x.currentQRectChanged.connect(printCurrentQRect)
    sys.exit(myQApplication.exec_())


问:
Using images to style scroll bars?
Can anyone recommend the best solution for using images to style scroll bar?  I guess a decent cross-browser solution would involve a merge of JQuery/javascrip and CSS?

Thanks
Paul

答:
I think this article will get you going.

BTW: There is no such thing as best :)

Title: Using images to style scroll bars?


问:
I cannot receive emails from external domain with virtual users
I cannot receive emails from external domains in my ubuntu 18.04 mail server.
i can send to other domains with my sendgrid relay server since outbound port 25 is blocked by google cloud. i can also receive mails from other virtual users in my domain.

i have unblocked port 110,143,587,993 and 995. i can also telnet on these ports.

i tested my mail server on pingability.com and i got ConnectException: Connection timed out (Connection timed out) for POP3

i got ProtocolException: No login methods supported! for IMAP

答:
it was my ignorance. i learnt that both incoming and outgoing mail requires port 25 to be open. if outgoing port is blocked, you can use a smtp relay service.

my solution was opening incoming connection on port 25 using google cloud firewall rules


问:
Solving Binary Gap using Recursion
I am trying to solve binary gap problem using recursion. It can be easily solved without recursion. But I want to solve this with recursion.The below program takes an integer as input and finds the binary gap.

Example:

```<code>input= 9, Binary form = 1001, Answer = 2

input=37, Binary form = 100101, Answer = 2
</code>```

It finds the maximum number of zeros that occur between two 1's in the binary representation.

I want to solve this in O(logn). Right now, the below program simply counts the total number of zeros and gives output 3 instead of 2. How do I correct this to get the right output?

```<code>class BinaryGap {

    public int solution(int N){

     return solution(N, false, 0);
    }
    public int solution(int N, boolean prevFlag, int memo) {

        if(N<2)
            return 0;

        int remainder = N%2 ;

        if(prevFlag){
            if(remainder == 0){
                memo = 1 + solution(N/2, prevFlag, memo);
            } else {
                int newGap = solution(N/2, prevFlag, memo);

                if(newGap > memo)
                    memo = newGap;
            }
        } else {

            prevFlag = (remainder == 1);
            return solution(N/2, prevFlag, 0);
        }

        return memo;

    }

    public static void main(String args[]){
        BinaryGap obj = new BinaryGap();

        System.out.println(obj.solution(37));
    }

}
</code>```

答:
This is my solution in Kotlin and it got 100% on Codility

```<code>fun solution(N: Int): Int {
    var binaryGap = 0
    val string = Integer.toBinaryString(N).replace("0+$".toRegex(), "")
    val words = string.split("1+".toRegex())
                      .dropLastWhile { it.isEmpty() }
                      .toTypedArray()

    Arrays.sort(words)

    if (words.size.isNotEmpty() {
        binaryGap = words[words.size - 1].length
    }

    return binaryGap
</code>```

}

Title: Solving Binary Gap using Recursion

Body:
I am trying to solve binary gap problem using recursion. It can be easily solved without recursion. But I want to solve this with recursion.The below program takes an integer as input and finds the binary gap.

Example:

input= 9, Binary form = 1001, Answer = 2

input=37, Binary form = 100101, Answer = 2

It finds the maximum number of zeros that occur between two 1's in the binary representation.

I want to solve this in O(logn). Right now, the below program simply counts the total number of zeros and gives output 3 instead of 2. How do I correct this to get the right output?

class BinaryGap {

    public int solution(int N){

     return solution(N, false, 0);
    }
    public int solution(int N, boolean prevFlag, int memo) {

        if(N<2)
            return 0;

        int remainder = N%2 ;

        if(prevFlag){
            if(remainder == 0){
                memo = 1 + solution(N/2, prevFlag, memo);
            } else {
                int newGap = solution(N/2, prevFlag, memo);

                if(newGap > memo)
                    memo = newGap;
            }
        } else {

            prevFlag = (remainder == 1);
            return solution(N/2, prevFlag, 0);
        }

        return memo;

    }

    public static void main(String args[]){
        BinaryGap obj = new BinaryGap();

        System.out.println(obj.solution(37));
    }

}

Body:
This is my solution in Kotlin and it got 100% on Codility

fun solution(N: Int): Int {
    var binaryGap = 0
    val string = Integer.toBinaryString(N).replace("0+$".toRegex(), "")
    val words = string.split("1+".toRegex())
                      .dropLastWhile { it.isEmpty() }
                      .toTypedArray()

    Arrays.sort(words)

    if (words.size.isNotEmpty() {
        binaryGap = words[words.size - 1].length
    }

    return binaryGap

}


问:
Function to check a row in database with session variable not working
I'm working on a web app, in PHP and AngularJS.

I want to restrict a part of my navbar for users that has a special row. (Like admins)

I made an angularJS function in my controller, which calls a function in my PHP Controller. (I'm working on with MVC and no PHP framework)

The problem is that I pass a variable session in parameter, which the one I can identify my user in my database, and it's not working.

The function is not working. No erros in the logs, no errors in the console, nothing. The "Admin" part of my navbar won't go back if I got the good right to see it.

PHP Function

```<code>function verifierHabilitation ( $req, $api ){
    if(droitsModificationAdmin( $_SESSION['nni'] ) == "administration") {
        return 1;
    }
}
</code>```

I'm calling my function droitsModificationAdmin() to verify the row, and I'm using a variable session in parameter.

AngularJS Function Call in my navbar

```<code><li class="nav-item" ng-if="droitsAdmin() == 1" >
    <h2 ng-class="{ 'grdf-ss-title' : isActive('/admin') }" >
       <a class="nav-link" href="#/admin">Admin</a>
    </h2>
</li>
</code>```

Here I'm using ng-if to verify the return of my previous function.

I don't know where the problem is. Do you have any idea ?

EDIT :

Here is all the code I used :

AJS :
In my controller.js

```<code>$scope.droitsAdmin = function() { factoryDossier.verifierHabilitation(); };
</code>```

In my factory.js

```<code>verifierHabilitation : function(){

    return $http({
        url: 'controleurs/Controleur-Admin.php'
        ,method: "POST"
        ,data: $.param({
            fonction : 'verifierHabilitation'
        })
        ,headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    });
},

</code>```

PHP:
Controller.php

```<code>function verifierHabilitation ( $req, $api ){
    if(droitsModificationAdmin( $_SESSION['nni'] ) == "administration") {
        echo "ceci est un test";
        return 1;
    }
}
</code>```

Here I am calling the function which is in the global controller.

Global Controller

```<code>function droitsModificationAdmin( $nni ){
    $bdd = new Model_Habilitation( PDO_bdd_app() );
    $utilisateur = $bdd->habilitation( $nni );
    return ( $utilisateur[0]['h_habilitation'] );
}
</code>```

Model.php

```<code>public function habilitation( $nni ){
        $sql = $this->grea_ouest->prepare('SELECT h_habilitation FROM '.$this->table_habilitation.' h WHERE h.h_nni = :nni');
        $sql->execute( array( ':nni' => $nni ) );
        return $sql->fetchAll(PDO::FETCH_ASSOC);
    }
</code>```

Controleur-Configuration.php

(Sorry the code is in french)

```<code><?php

require_once('Controleur-Configuration.php');
require_once('api_rest.php');
require_once(dirname(__FILE__).'/../class/ClassAdmin.php');
require_once(model_url('Model_Admin'));
require_once('Helpers.php');

#############################################################
gestion_session();//Gestion à partir du fichier configuration
#############################################################

$api = new Rest;

try {
    $req = $api->get_request();
    if( function_exists( $req['fonction'] ) ){ $req['fonction']( $req, $api ); } else { throw new Exception('Fonction inexistante'); }
} catch(Exception $e){
    $api->response(array(), 501);
}

/**
 * Retourne les informations d'un admin
 * @param $req array : les données passées en parametres
 * @param $api Rest : l'objet Rest permettant l'interaction avec le client.
 * @return array : les informations du dossier.
 */
function getAdmins( $req, $api ){
    $bdd = new Model_Admin( PDO_bdd_app() );
    try{
        $Admins = $bdd->getAdmins();
        foreach($Admins as $key=>$Admin){ $Admins[$key] = $Admin->json_encode(); }
        $api->response( $Admins, 200);
    } catch(Exception $e){ error_log( $e ); $api->response( "", 500); }
}

/**
 * Retourne les habilitations
 * @param $req array : les données passées en parametres
 * @param $api Rest : l'objet Rest permettant l'interaction avec le client.
 * @return array : les informations du dossier.
 */
function getHabilitations( $req, $api ){
    $bdd = new Model_Admin( PDO_bdd_app() );
    try{
        $Habilitations = $bdd->getHabilitations();
        foreach($Habilitations as $key=>$Habilitation){ $Habilitations[$key] = $Habilitation->json_encode(); }
        $api->response( $Habilitations, 200);
    } catch(Exception $e){ error_log( $e ); $api->response( "", 500); }
}

/**
* Met a jour un habilité
* @param $req array : les données passées en parametres
* @param $api Rest : l'objet Rest permettant l'interaction avec le client.
* @return array : les informations du CA.
* @throws Exception : retourne une erreur 500.
*/
function updateAdmin( $req, $api ){
    $bdd = new Model_Admin( PDO_bdd_app() );
    try {
        if( isset($req['NewAdmin']) ){
            $admin = cast( $req['NewAdmin'], 'Admin' );
        } else { $api->response( array( "erreur" => array(array("Aucunes informations saisies"))), 409); }

            try
            {
                $bdd = new Model_Admin( PDO_bdd_app() );
                $newAdmin = $bdd->updateAdmin( $admin );
                $api->response( array( "dev"=>$newAdmin->json_encode(), "info"=>array("Le développeur a été modifié")), 200);
    } catch( Exception $e ){ error_log( $e ); $api->response( "", 500); }
    } catch( Exception $e ){ error_log( $e ); $api->response( "", 500); }
}

/**
* Change l'habilitation d'un utilisateur
* @param $req array : les données passées en parametres
* @param $api Rest : l'objet Rest permettant l'interaction avec le client.
* @return array : les informations du CA.
* @throws Exception : retourne une erreur 500.
*/
function changerHabilitation ($req, $api){
    $bdd = new Model_Admin( PDO_bdd_app() );
    try{
        $habilitation = $bdd->changerHabilitation( $req['nni'], $req['habilitation'] );
    } catch(Exception $e){
        error_log( $e );
        $api->response( $e, 500);
    }
}

function verifierHabilitation ( $req, $api ){
    if(droitsModificationAdmin( $_SESSION['nni'] ) == "administration") {
        echo "ceci est un test";
        return 1;
    }
}

/**
* Approuve un utilisateur
* @param $req array : les données passées en parametres
* @param $api Rest : l'objet Rest permettant l'interaction avec le client.
* @return array : les informations du CA.
* @throws Exception : retourne une erreur 500.
*/
function approuverUtilisateur ($req, $api){
    $bdd = new Model_Admin( PDO_bdd_app() );
    try{
        $utilisateur = $bdd->approuverUtilisateur( $req['nni'] );
    } catch(Exception $e){
        error_log( $e );
        $api->response( $e, 500);
    }
}

/**
* Refuse un utilisateur
* @param $req array : les données passées en parametres
* @param $api Rest : l'objet Rest permettant l'interaction avec le client.
* @return array : les informations du CA.
* @throws Exception : retourne une erreur 500.
*/
function refuserUtilisateur ($req, $api){
    $bdd = new Model_Admin( PDO_bdd_app() );
    try{
        $utilisateur = $bdd->refuserUtilisateur( $req['nni'] );
    } catch(Exception $e){
        error_log( $e );
        $api->response( $e, 500);
    }
}

?>

</code>```

答:
The $http service does not return a value, it returns a promise from which a value needs to be extracted:

```<code>$scope.droitsAdmin = function() {
    var promise = factoryDossier.verifierHabilitation();
    return promise.then(function (response) {
        var data = response.data;
        $scope.droitsAdminData = data;
        console.log(data);
        return data;
    }).catch(function(error) {
        console.log(error);
        throw error;
    });
};
</code>```

There are other problems with your code, but this should give you console messages that will show the problems.

Body:
I'm working on a web app, in PHP and AngularJS.

I want to restrict a part of my navbar for users that has a special row. (Like admins)

I made an angularJS function in my controller, which calls a function in my PHP Controller. (I'm working on with MVC and no PHP framework)

The problem is that I pass a variable session in parameter, which the one I can identify my user in my database, and it's not working.

The function is not working. No erros in the logs, no errors in the console, nothing. The "Admin" part of my navbar won't go back if I got the good right to see it.

PHP Function

function verifierHabilitation ( $req, $api ){
    if(droitsModificationAdmin( $_SESSION['nni'] ) == "administration") {
        return 1;
    }
}

I'm calling my function droitsModificationAdmin() to verify the row, and I'm using a variable session in parameter.

AngularJS Function Call in my navbar

       Admin

Here I'm using ng-if to verify the return of my previous function.

I don't know where the problem is. Do you have any idea ?

EDIT :

Here is all the code I used :

AJS :
In my controller.js

$scope.droitsAdmin = function() { factoryDossier.verifierHabilitation(); };

In my factory.js

verifierHabilitation : function(){

    return $http({
        url: 'controleurs/Controleur-Admin.php'
        ,method: "POST"
        ,data: $.param({
            fonction : 'verifierHabilitation'
        })
        ,headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    });
},

PHP:
Controller.php

function verifierHabilitation ( $req, $api ){
    if(droitsModificationAdmin( $_SESSION['nni'] ) == "administration") {
        echo "ceci est un test";
        return 1;
    }
}

Here I am calling the function which is in the global controller.

Global Controller

function droitsModificationAdmin( $nni ){
    $bdd = new Model_Habilitation( PDO_bdd_app() );
    $utilisateur = $bdd->habilitation( $nni );
    return ( $utilisateur[0]['h_habilitation'] );
}

Model.php

public function habilitation( $nni ){
        $sql = $this->grea_ouest->prepare('SELECT h_habilitation FROM '.$this->table_habilitation.' h WHERE h.h_nni = :nni');
        $sql->execute( array( ':nni' => $nni ) );
        return $sql->fetchAll(PDO::FETCH_ASSOC);
    }

Controleur-Configuration.php

(Sorry the code is in french)

<?php

require_once('Controleur-Configuration.php');
require_once('api_rest.php');
require_once(dirname(__FILE__).'/../class/ClassAdmin.php');
require_once(model_url('Model_Admin'));
require_once('Helpers.php');

#############################################################
gestion_session();//Gestion à partir du fichier configuration
#############################################################

$api = new Rest;

try {
    $req = $api->get_request();
    if( function_exists( $req['fonction'] ) ){ $req['fonction']( $req, $api ); } else { throw new Exception('Fonction inexistante'); }
} catch(Exception $e){
    $api->response(array(), 501);
}

/**
 * Retourne les informations d'un admin
 * @param $req array : les données passées en parametres
 * @param $api Rest : l'objet Rest permettant l'interaction avec le client.
 * @return array : les informations du dossier.
 */
function getAdmins( $req, $api ){
    $bdd = new Model_Admin( PDO_bdd_app() );
    try{
        $Admins = $bdd->getAdmins();
        foreach($Admins as $key=>$Admin){ $Admins[$key] = $Admin->json_encode(); }
        $api->response( $Admins, 200);
    } catch(Exception $e){ error_log( $e ); $api->response( "", 500); }
}

/**
 * Retourne les habilitations
 * @param $req array : les données passées en parametres
 * @param $api Rest : l'objet Rest permettant l'interaction avec le client.
 * @return array : les informations du dossier.
 */
function getHabilitations( $req, $api ){
    $bdd = new Model_Admin( PDO_bdd_app() );
    try{
        $Habilitations = $bdd->getHabilitations();
        foreach($Habilitations as $key=>$Habilitation){ $Habilitations[$key] = $Habilitation->json_encode(); }
        $api->response( $Habilitations, 200);
    } catch(Exception $e){ error_log( $e ); $api->response( "", 500); }
}

/**
* Met a jour un habilité
* @param $req array : les données passées en parametres
* @param $api Rest : l'objet Rest permettant l'interaction avec le client.
* @return array : les informations du CA.
* @throws Exception : retourne une erreur 500.
*/
function updateAdmin( $req, $api ){
    $bdd = new Model_Admin( PDO_bdd_app() );
    try {
        if( isset($req['NewAdmin']) ){
            $admin = cast( $req['NewAdmin'], 'Admin' );
        } else { $api->response( array( "erreur" => array(array("Aucunes informations saisies"))), 409); }

            try
            {
                $bdd = new Model_Admin( PDO_bdd_app() );
                $newAdmin = $bdd->updateAdmin( $admin );
                $api->response( array( "dev"=>$newAdmin->json_encode(), "info"=>array("Le développeur a été modifié")), 200);
    } catch( Exception $e ){ error_log( $e ); $api->response( "", 500); }
    } catch( Exception $e ){ error_log( $e ); $api->response( "", 500); }
}

/**
* Change l'habilitation d'un utilisateur
* @param $req array : les données passées en parametres
* @param $api Rest : l'objet Rest permettant l'interaction avec le client.
* @return array : les informations du CA.
* @throws Exception : retourne une erreur 500.
*/
function changerHabilitation ($req, $api){
    $bdd = new Model_Admin( PDO_bdd_app() );
    try{
        $habilitation = $bdd->changerHabilitation( $req['nni'], $req['habilitation'] );
    } catch(Exception $e){
        error_log( $e );
        $api->response( $e, 500);
    }
}

function verifierHabilitation ( $req, $api ){
    if(droitsModificationAdmin( $_SESSION['nni'] ) == "administration") {
        echo "ceci est un test";
        return 1;
    }
}

/**
* Approuve un utilisateur
* @param $req array : les données passées en parametres
* @param $api Rest : l'objet Rest permettant l'interaction avec le client.
* @return array : les informations du CA.
* @throws Exception : retourne une erreur 500.
*/
function approuverUtilisateur ($req, $api){
    $bdd = new Model_Admin( PDO_bdd_app() );
    try{
        $utilisateur = $bdd->approuverUtilisateur( $req['nni'] );
    } catch(Exception $e){
        error_log( $e );
        $api->response( $e, 500);
    }
}

/**
* Refuse un utilisateur
* @param $req array : les données passées en parametres
* @param $api Rest : l'objet Rest permettant l'interaction avec le client.
* @return array : les informations du CA.
* @throws Exception : retourne une erreur 500.
*/
function refuserUtilisateur ($req, $api){
    $bdd = new Model_Admin( PDO_bdd_app() );
    try{
        $utilisateur = $bdd->refuserUtilisateur( $req['nni'] );
    } catch(Exception $e){
        error_log( $e );
        $api->response( $e, 500);
    }
}

?>

Body:
The $http service does not return a value, it returns a promise from which a value needs to be extracted:

$scope.droitsAdmin = function() {
    var promise = factoryDossier.verifierHabilitation();
    return promise.then(function (response) {
        var data = response.data;
        $scope.droitsAdminData = data;
        console.log(data);
        return data;
    }).catch(function(error) {
        console.log(error);
        throw error;
    });
};

There are other problems with your code, but this should give you console messages that will show the problems.


问:
Center align li with equal height and fixed width
Under an ul, there are 5 li's. wanted to have all the li with same height with fixed width(20% for each li is 100%). i have achieved that with the below code.But my problem is, if i have only 3 or 4 li's i want to display the li's with same height and width but in center. Right now if i have 3 or 4, the width is adjusting and occupying the whole ul container.

Even if its 3 li or 4 li, the li should have fixed width with aligned in the center.

.box-outer {
  text-align: center;
  display: table;
  table-layout: fixed;
  background-color: #333;
}

.boxes {
  vertical-align: middle;
  width: 10% !important;
  margin-right: 1% !important;
  background: #fff;
  border-radius: 6px;
  text-align: center;
  padding: 32px 29px;
  display: table-cell;
}

.field-number {
  color: #de008d;
  font-size: 48px;
  font-family: sans-serif;
}

.field-text {
  padding-top: 10px;
  color: #333;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box-outer">
  <div class="boxes">
    <h4 class="field-number">83</h4>
    <span class="field-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit,</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">7,800</h4><span class="field-text">mod tempor incididunt ut labor</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">65k</h4><span class="field-text">ut aliquip</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">37k</h4><span class="field-text">Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">£250m</h4><span class="field-text">veniam, quis nostrud exercitation ullamco</span>
  </div>
</div></code>```

JS Fiddle Link

答:
You can use the flex box to achieve the same. Here is a sample code having 5 li's

li {
  list-style-type: none;
  border: 1px solid black;
  width: 20%;
}

ul {
  padding: 0;
  display: flex;
  justify-content: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>Li 1</li>
  <li>Li 2</li>
  <li>Li 3</li>
  <li>Li 4</li>
  <li>Li 5</li>
</ul></code>```

Here is another sample code having 3 li's:

li {
  list-style-type: none;
  border: 1px solid black;
  width: 20%;
}

ul {
  padding: 0;
  display: flex;
  justify-content: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>Li 1</li>
  <li>Li 2</li>
  <li>Li 5</li>
</ul></code>```

The CSS is same, only the number of li's are different.

Body:
Under an ul, there are 5 li's. wanted to have all the li with same height with fixed width(20% for each li is 100%). i have achieved that with the below code.But my problem is, if i have only 3 or 4 li's i want to display the li's with same height and width but in center. Right now if i have 3 or 4, the width is adjusting and occupying the whole ul container.

Even if its 3 li or 4 li, the li should have fixed width with aligned in the center.

.box-outer {
  text-align: center;
  display: table;
  table-layout: fixed;
  background-color: #333;
}

.boxes {
  vertical-align: middle;
  width: 10% !important;
  margin-right: 1% !important;
  background: #fff;
  border-radius: 6px;
  text-align: center;
  padding: 32px 29px;
  display: table-cell;
}

.field-number {
  color: #de008d;
  font-size: 48px;
  font-family: sans-serif;
}

.field-text {
  padding-top: 10px;
  color: #333;
}

83

    Lorem ipsum dolor sit amet, consectetur adipiscing elit,

7,800
mod tempor incididunt ut labor

65k
ut aliquip

37k
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

£250m
veniam, quis nostrud exercitation ullamco

JS Fiddle Link

Body:
You can use the flex box to achieve the same. Here is a sample code having 5 li's

li {
  list-style-type: none;
  border: 1px solid black;
  width: 20%;
}

ul {
  padding: 0;
  display: flex;
  justify-content: center;
}

<ul>
  <li>Li 1</li>
  <li>Li 2</li>
  <li>Li 3</li>
  <li>Li 4</li>
  <li>Li 5</li>
</ul>

Here is another sample code having 3 li's:

li {
  list-style-type: none;
  border: 1px solid black;
  width: 20%;
}

ul {
  padding: 0;
  display: flex;
  justify-content: center;
}

<ul>
  <li>Li 1</li>
  <li>Li 2</li>
  <li>Li 5</li>
</ul>

The CSS is same, only the number of li's are different.