问:
How to utilise both CSS and XSLT together on XML?
I am trying to utilise my CSS stylesheet with my XML that also has a XSLT stylesheet attached, this causes it to go completely out of its formatting once the CSS is attached into a massive clump.

Linking the CSS stylesheet and playing around with its styles in the chat to get it to format.

XML

```<code>       <?xml version="1.0" encoding="UTF-8"?>
       <?xml-stylesheet type="text/xsl" href="cuisinexsl.xsl"?>
       <?xml-stylesheet type="text/css" href="ofd.css"?>

   <cuisines>
       <cuisinetype>
        <cuisine>Greek</cuisine>
            <name>Food from Zeus</name>
            <address>96 Almighty Road</address>
            <phone>02 2321 5592</phone>
            <deliveryfee>Delivery fee is $7</deliveryfee>
            <URL>https://zeusfoods.com.au/</URL>
            <takeaway>Yes</takeaway>
            <dinein>Yes</dinein>
            <openhours>9-5 Mon-Sat,Sunday Closed</openhours>
            <description>Food created by us, that even the almighty would
            die for.</description>
      </cuisinetype>
    </cuisines>
</code>```

XSLT

```<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="html"/>
   <xsl:stylesheet type="text/css" href="ofd.css">

   <xsl:template match="/">
   <html>
   <body>
   <h1>Cuisine Restaurants</h1>
   <xsl:apply-templates/>
   </body>
   </html>
   </xsl:template>

   <xsl:template match="cuisinetype">
   <xsl:for-each select="cuisines/cuisinetype">
       <xsl:sort select="name"/>
   </xsl:for-each>
        <p>
        <xsl:apply-templates select="cuisine"/>
            <xsl:apply-templates select="name"/>
            <xsl:apply-templates select="address"/>
            <xsl:apply-templates select="phone"/>
            <xsl:apply-templates select="deliveryfee"/>
            <xsl:apply-templates select="URL"/>
            <xsl:apply-templates select="takeaway"/>
            <xsl:apply-templates select="dinein"/>
            <xsl:apply-templates select="openhours"/>
            <xsl:apply-templates select="description"/>
        </p>
     </xsl:template>

    <xsl:template match="cuisine">
    Cuisine type: <span style="">
    <xsl:value-of select="."/></span>
    <br />
  </xsl:template>

 </xsl:stylesheet>

CSS
</code>```

here is the css, this is what is like overriding the xslt,

```<code>  body {
    background-color: lightpink;
}

h1 {
    color: black;
    text-shadow: 3px 2px grey;
    font-size: 60px;
    text-align: center;
}

h2 {
    color: black;
    margin-left: 20px;
    text-decoration: underline;
    text-transform: uppercase;
    text-align: center;
    font-size: 35px;
    text-shadow: 2px 1px grey;
}

h3 {
    color: black;
    font-size: 25px
}

h4 {
    color: black;
    margin-left: 20px;
    margin-right: 20px;
    font-family: "Times New Roman", Times, serif;
    text-align: center;
}

body {
    background-image: url("Graphics/background2.jpg");
}

#para1 {
    text-align: center;
    color: red;
}

.lightgrey {
    background-color: lightgrey;
}

.padding {
    border: 3px solid black;
    padding: 1px 125px 1px 125px;
    background-color: grey;
}

.footer {
    border: 3px solid black;
    padding: 1px 125px 1px 125px;
    background-color: grey;
}

div.picture {
    border: 2px solid #000000;
    width: 600px;
    height: 4oopx
}

div.picture:hover {
    border: 2px solid #000000;
}

div.picture img {
    width: 100%;
    height: auto;
}

div.imagedescription {
    padding: 2px;
    text-align: centre;
    background-color: lightgrey;
}

.site-info::after {
    content: "Copyright Hisham Echafaki 2017 - All Rights Reserved ";
}

.parastyle1 {
    font-family: Arial, Helvetica, sans-serif;
    color: black;
    font-size: 28px;
    font-weight: bold;
}

.parastyle2 {
    font-family: Arial, Helvetica, sans-serif;
    color: black;
    font-size: 20px;
    font-weight: bold;
}

.box {
    position: relative;
}

.yeet_time {
    position: absolute;
    bottom: 0;
    right: 0;
}

p {
    margin-left: 150px;
    margin-right: 150px;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 20px;
    color: black;
    font-weight: bold;
}

pw {
    margin-left: 20px;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 40px;
    color: white;
    font-weight: bold;
}

pw2 {
    margin-left: 20px;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 18px;
    color: white;
    font-weight: bold;
}

pw3 {
    font-family: Arial;
    color: black;
    font-size: 20px;
    font-weight: bold;
    margin-left: 40px;
    margin-right: 40px;
}

pw4 {
    font-family: Arial;
    color: black;
    font-size: 20px;
    font-weight: bold;
    margin-left: 150px;
    margin-right: 0px;
}

pw5 {
    margin-left: 880px;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 18px;
    color: black;
    font-weight: bold;
}

pw6 {
    font-family: Arial;
    color: black;
    font-size: 20px;
    font-weight: bold;
    margin-left: 275px;
    margin-right: 0px;
}

a:link {
    color: blue;
    background-color: transparent;
    text-decoration: none;
}

a:visited {
    color: aqua;
    background-color: transparent;
    text-decoration: none;
}

a:hover {
    color: navy;
    background-color: transparent;
    font-size: 23px;
}

a:active {
    color: fuchsia;
    background-color: transparent;
    text-decoration: underline;
}

h5 {
    color: black;
    margin-left: 40px;
    text-decoration: underline;
    text-transform: uppercase;
    text-align: left;
    font-size: 35px;
    text-shadow: 2px 1px grey;
}

a.zoom:hover {
    transform: scale(1.5);
    /* (150% zoom - Note: if the zoom is too large, it will go outside of the viewport) */
}

</style> <div class="a"></div> margin1 {
    margin-left: 1cm;
}
</code>```

答:
This was a bit too long to write in comments, but it does not make sense to link an XML to both a XSLT stylesheet and a CSS stylesheet, like you have done

```<code><?xml-stylesheet type="text/xsl" href="cuisinexsl.xsl"?>
<?xml-stylesheet type="text/css" href="ofd.css"?>
</code>```

However, in your case, you are not trying to style the XML with CSS, but the HTML you are creating with the XSLT.

In this case, you need to do the following

Remove the <?xml-stylesheet type="text/css" href="ofd.css"?> from the XML

Remove the rogue <xsl:stylesheet type="text/css" href="ofd.css"> from the XSLT (as your XSLT would not be well-formed otherwise).

Add the line <link rel="stylesheet" type="text/css" href="ofd.css" /> to the  section of the HTML

For example:

```<code><xsl:template match="/">
  <html>
    <head>
      <link rel="stylesheet" type="text/css" href="ofd.css" />
    </head>
    <body>
      <h1>Cuisine Restaurants</h1>
      <xsl:apply-templates/>
    </body>
  </html>
</xsl:template>
</code>```

Body:
I am trying to utilise my CSS stylesheet with my XML that also has a XSLT stylesheet attached, this causes it to go completely out of its formatting once the CSS is attached into a massive clump.

Linking the CSS stylesheet and playing around with its styles in the chat to get it to format.

XML

       <?xml version="1.0" encoding="UTF-8"?>
       <?xml-stylesheet type="text/xsl" href="cuisinexsl.xsl"?>
       <?xml-stylesheet type="text/css" href="ofd.css"?>

   <cuisines>
       <cuisinetype>
        <cuisine>Greek</cuisine>
            <name>Food from Zeus</name>
            <address>96 Almighty Road</address>
            <phone>02 2321 5592</phone>
            <deliveryfee>Delivery fee is $7</deliveryfee>
            <URL>https://zeusfoods.com.au/</URL>
            <takeaway>Yes</takeaway>
            <dinein>Yes</dinein>
            <openhours>9-5 Mon-Sat,Sunday Closed</openhours>
            <description>Food created by us, that even the almighty would
            die for.</description>
      </cuisinetype>
    </cuisines>

XSLT

   <?xml version="1.0" encoding="UTF-8"?>
   <xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output method="html"/>
   <xsl:stylesheet type="text/css" href="ofd.css">

   <xsl:template match="/">

Cuisine Restaurants

   <xsl:apply-templates/>

   </xsl:template>

   <xsl:template match="cuisinetype">
   <xsl:for-each select="cuisines/cuisinetype">
       <xsl:sort select="name"/>
   </xsl:for-each>

        <xsl:apply-templates select="cuisine"/>
            <xsl:apply-templates select="name"/>
            <xsl:apply-templates select="address"/>
            <xsl:apply-templates select="phone"/>
            <xsl:apply-templates select="deliveryfee"/>
            <xsl:apply-templates select="URL"/>
            <xsl:apply-templates select="takeaway"/>
            <xsl:apply-templates select="dinein"/>
            <xsl:apply-templates select="openhours"/>
            <xsl:apply-templates select="description"/>

     </xsl:template>

    <xsl:template match="cuisine">
    Cuisine type:
    <xsl:value-of select="."/>

  </xsl:template>

 </xsl:stylesheet>

CSS

here is the css, this is what is like overriding the xslt,

  body {
    background-color: lightpink;
}

h1 {
    color: black;
    text-shadow: 3px 2px grey;
    font-size: 60px;
    text-align: center;
}

h2 {
    color: black;
    margin-left: 20px;
    text-decoration: underline;
    text-transform: uppercase;
    text-align: center;
    font-size: 35px;
    text-shadow: 2px 1px grey;
}

h3 {
    color: black;
    font-size: 25px
}

h4 {
    color: black;
    margin-left: 20px;
    margin-right: 20px;
    font-family: "Times New Roman", Times, serif;
    text-align: center;
}

body {
    background-image: url("Graphics/background2.jpg");
}

#para1 {
    text-align: center;
    color: red;
}

.lightgrey {
    background-color: lightgrey;
}

.padding {
    border: 3px solid black;
    padding: 1px 125px 1px 125px;
    background-color: grey;
}

.footer {
    border: 3px solid black;
    padding: 1px 125px 1px 125px;
    background-color: grey;
}

div.picture {
    border: 2px solid #000000;
    width: 600px;
    height: 4oopx
}

div.picture:hover {
    border: 2px solid #000000;
}

div.picture img {
    width: 100%;
    height: auto;
}

div.imagedescription {
    padding: 2px;
    text-align: centre;
    background-color: lightgrey;
}

.site-info::after {
    content: "Copyright Hisham Echafaki 2017 - All Rights Reserved ";
}

.parastyle1 {
    font-family: Arial, Helvetica, sans-serif;
    color: black;
    font-size: 28px;
    font-weight: bold;
}

.parastyle2 {
    font-family: Arial, Helvetica, sans-serif;
    color: black;
    font-size: 20px;
    font-weight: bold;
}

.box {
    position: relative;
}

.yeet_time {
    position: absolute;
    bottom: 0;
    right: 0;
}

p {
    margin-left: 150px;
    margin-right: 150px;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 20px;
    color: black;
    font-weight: bold;
}

pw {
    margin-left: 20px;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 40px;
    color: white;
    font-weight: bold;
}

pw2 {
    margin-left: 20px;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 18px;
    color: white;
    font-weight: bold;
}

pw3 {
    font-family: Arial;
    color: black;
    font-size: 20px;
    font-weight: bold;
    margin-left: 40px;
    margin-right: 40px;
}

pw4 {
    font-family: Arial;
    color: black;
    font-size: 20px;
    font-weight: bold;
    margin-left: 150px;
    margin-right: 0px;
}

pw5 {
    margin-left: 880px;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 18px;
    color: black;
    font-weight: bold;
}

pw6 {
    font-family: Arial;
    color: black;
    font-size: 20px;
    font-weight: bold;
    margin-left: 275px;
    margin-right: 0px;
}

a:link {
    color: blue;
    background-color: transparent;
    text-decoration: none;
}

a:visited {
    color: aqua;
    background-color: transparent;
    text-decoration: none;
}

a:hover {
    color: navy;
    background-color: transparent;
    font-size: 23px;
}

a:active {
    color: fuchsia;
    background-color: transparent;
    text-decoration: underline;
}

h5 {
    color: black;
    margin-left: 40px;
    text-decoration: underline;
    text-transform: uppercase;
    text-align: left;
    font-size: 35px;
    text-shadow: 2px 1px grey;
}

a.zoom:hover {
    transform: scale(1.5);
    /* (150% zoom - Note: if the zoom is too large, it will go outside of the viewport) */
}

</style>

 margin1 {
    margin-left: 1cm;
}

Body:
This was a bit too long to write in comments, but it does not make sense to link an XML to both a XSLT stylesheet and a CSS stylesheet, like you have done

<?xml-stylesheet type="text/xsl" href="cuisinexsl.xsl"?>
<?xml-stylesheet type="text/css" href="ofd.css"?>

However, in your case, you are not trying to style the XML with CSS, but the HTML you are creating with the XSLT.

In this case, you need to do the following

Remove the <?xml-stylesheet type="text/css" href="ofd.css"?> from the XML

Remove the rogue <xsl:stylesheet type="text/css" href="ofd.css"> from the XSLT (as your XSLT would not be well-formed otherwise).

Add the line <link rel="stylesheet" type="text/css" href="ofd.css" /> to the <head> section of the HTML

For example:

<xsl:template match="/">
  <html>
    <head>
      <link rel="stylesheet" type="text/css" href="ofd.css" />
    </head>
    <body>
      <h1>Cuisine Restaurants</h1>
      <xsl:apply-templates/>
    </body>
  </html>
</xsl:template>


来源: stackexchange

问:
Adding razor views to NET Core Api
I am building an app .NET Core Api + Angular app that requires send emails to their users. The feature is working okay using html templates  and an ugly code to replace the conent in these files (there are at least 4 html templates). Now I want to do the thing better and I want to use razor views as my "mail templates" and I am following the article here

Basically the code is using  3 projects: razor pages / standard libray /Razor class library but in my case I only want add these "cshtml" files all inside of my api project. So that I did was create a folder Views and inside of it all the required razor views. After that I published these razor views to test if the project this kind of project understand that it must move the folder and files to the final destination BUT nothing happen.

Also I did some litle changes in my StartUp class in order to inform to VS that this project is also supporting MVC

ConfigureServices method:

```<code>   services.AddMvc(config => {
            var policy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .Build();
            config.Filters.Add(new AuthorizeFilter(policy));
        });
</code>```

Configure Method:

```<code>        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
</code>```

After these change nothing happen. What is missing?
Update 1: I found this useful link about razor pages and as far I understand Razor files are compiled at both build and publish time and there isn't a way to check that razor files were copied correctly to output folder.

答:
try this startup class</p>

```<code>public class Startup

{   public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services){
        services.AddMvc(config => {
        var policy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build();
        config.Filters.Add(new AuthorizeFilter(policy));
       });
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseStaticFiles(); //this middleware also should be added to the pipeline if your template has images,css etc.
        app.UseMvcWithDefaultRoute();
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Adding razor views to NET Core Api

Body:
I am building an app .NET Core Api + Angular app that requires send emails to their users. The feature is working okay using html templates  and an ugly code to replace the conent in these files (there are at least 4 html templates). Now I want to do the thing better and I want to use razor views as my "mail templates" and I am following the article here

Basically the code is using  3 projects: razor pages / standard libray /Razor class library but in my case I only want add these "cshtml" files all inside of my api project. So that I did was create a folder Views and inside of it all the required razor views. After that I published these razor views to test if the project this kind of project understand that it must move the folder and files to the final destination BUT nothing happen.

Also I did some litle changes in my StartUp class in order to inform to VS that this project is also supporting MVC

ConfigureServices method:

   services.AddMvc(config => {
            var policy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .Build();
            config.Filters.Add(new AuthorizeFilter(policy));
        });

Configure Method:

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

After these change nothing happen. What is missing?
Update 1: I found this useful link about razor pages and as far I understand Razor files are compiled at both build and publish time and there isn't a way to check that razor files were copied correctly to output folder.

Body:
try this startup class

public class Startup

{   public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services){
        services.AddMvc(config => {
        var policy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build();
        config.Filters.Add(new AuthorizeFilter(policy));
       });
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseStaticFiles(); //this middleware also should be added to the pipeline if your template has images,css etc.
        app.UseMvcWithDefaultRoute();
    }
}


问:
Problem with understanding a vector initialization
This might be a dumb question but there is something I can't quite understand. When using a vector, whenever I want to 'push_back' an element to a certain position I can do that only if I initialize the vector in a certain way.

For example when I use this initialization:

```<code>std::vector<int> Myvec;
int size = 0;
int x = 0;
std::cin >> size;

for(int i = 0; i < size; i++)
{
    std::cin >> x;
    Myvec[i].push_back(x);
}
</code>```

I receive the following error:
request for member 'push_back' in 'Myvec.std::vector<_Tp, _Alloc>::operator[] >(((std::vector::size_type)i))', which is of non-class type '__gnu_cxx::__alloc_traits >::value_type {aka int}'|

But when I use the following initialization it works:

```<code>int size = 0;
int x = 0;
std::cin >> size;
std::vector<int> Myvec[size];

for(int i = 0; i < size; i++)
{
    std::cin >> x;
    Myvec[i].push_back(x);
}
</code>```

I don't have any problem using it and can implement it in all sorts of tasks, but it's bugging me because I'm not sure why it is actually working. Thank you for your help in advance.

答:
In the first block you should use:

```<code>std::vector<int> Myvec;
int size = 0;
int x = 0;
std::cin >> size;

for(int i = 0; i < size; i++)
{
    std::cin >> x;
    Myvec.push_back(x);
}
</code>```

Or you can use:

```<code>int size = 0;
int x = 0;
std::cin >> size;
std::vector<int> Myvec(size);
for(int i = 0; i < size; i++)
{
    cin>>Myvec[i];
}
</code>```

And print the vector using:

```<code>for(int i = 0; i < size; i++) {
     std::cout<< Myvec[i]<<" ";
}
</code>```

When you initialise it using vector Myvec[size], it becomes vector of vectors with size "size", means each Myvec[i] is a vector in which you can push elements.

Read more here: https://www.geeksforgeeks.org/2d-vector-in-cpp-with-user-defined-size/

Body:
This might be a dumb question but there is something I can't quite understand. When using a vector, whenever I want to 'push_back' an element to a certain position I can do that only if I initialize the vector in a certain way.

For example when I use this initialization:

std::vector<int> Myvec;
int size = 0;
int x = 0;
std::cin >> size;

for(int i = 0; i < size; i++)
{
    std::cin >> x;
    Myvec[i].push_back(x);
}

I receive the following error:
request for member 'push_back' in 'Myvec.std::vector<_Tp, _Alloc>::operator[] >(((std::vector::size_type)i))', which is of non-class type '__gnu_cxx::__alloc_traits >::value_type {aka int}'|

But when I use the following initialization it works:

int size = 0;
int x = 0;
std::cin >> size;
std::vector<int> Myvec[size];

for(int i = 0; i < size; i++)
{
    std::cin >> x;
    Myvec[i].push_back(x);
}

I don't have any problem using it and can implement it in all sorts of tasks, but it's bugging me because I'm not sure why it is actually working. Thank you for your help in advance.

Body:
In the first block you should use:

std::vector<int> Myvec;
int size = 0;
int x = 0;
std::cin >> size;

for(int i = 0; i < size; i++)
{
    std::cin >> x;
    Myvec.push_back(x);
}

Or you can use:

int size = 0;
int x = 0;
std::cin >> size;
std::vector<int> Myvec(size);
for(int i = 0; i < size; i++)
{
    cin>>Myvec[i];
}

And print the vector using:

for(int i = 0; i < size; i++) {
     std::cout<< Myvec[i]<<" ";
}

When you initialise it using vector Myvec[size], it becomes vector of vectors with size "size", means each Myvec[i] is a vector in which you can push elements.

Read more here: https://www.geeksforgeeks.org/2d-vector-in-cpp-with-user-defined-size/


问:
How to get many attributes data from a single tag?
I'm unable to get data from a single tag. Single tag have many data attributes like name, phone, company and url. i need to get data from many tags and all tags similar to this one.

HTML Code:

```<code> <div class="ListingDetails">
        <div class="ListingDisplayName">
            <a href="/members/jeremy.counter1/default.aspx">
                Jeremy Counter
            </a>
        </div>
                                        Mortgage Officer  -
        American Pacific Mortgage<br>

       Anchorage, Alaska  99503<br>
                                        phone: (907) 519-
       6656 | (907) 250-0766

      <div class="listingurl">
          <a rel="nofollow" href="http://www.jeremycounter.com" target="_blank">
            jeremycounter.com
          </a>
      </div>
 </div>
</code>```

Python Code:

```<code>data=requests.get(url)
soup=bs4.BeautifulSoup(data.text,'html.parser')

page = soup.find('div', class_="CommonContentBox DirectoryListings")

listing_box = page.find('div', class_="BusinessListingUser")
name  = listing_box.find('div', class_="ListingDisplayName").text
#print(name)

details  = listing_box.find('div',
class_="ListingDetails").text.strip('\n\t\r')
print(details)
</code>```

Output:

```<code>Tyler Tullis
                                          -
                                        Montgomery, Alabama  36117
                                         | (334) 322-3707
</code>```

Anyone tell me the best possible solution to get data.

Expected result:

```<code>name: Jeremy Counter

phone: (907) 519-6656

company: American Pacific Mortgage

url: jeremycounter.com
</code>```

答:
No need for Selenium here. Just pull the data and iterate through it to clean it and print it:

```<code>import requests
import bs4

url = "http://www.mortgagenewsdaily.com/directory/mortgage/alabama"
data=requests.get(url)
soup=bs4.BeautifulSoup(data.text,'html.parser')

page = soup.find_all('div', class_="BusinessListingUser")

for each in page:
    content = each.find('div', class_='ListingDetails').text.split('\n')
    content = [ text.strip() for text in content if text.strip() != '' ]
    for strings in content:
        print (strings)
    print ('\n')
</code>```

Output:

```<code>Tyler Tullis
-
Montgomery, Alabama  36117
| (334) 322-3707

Nathan Stotlar
Mortgage Production Manager  -  PrimeLending, a PlainsCapital Company
Fitchburg, Wisconsin  53717
phone: (608) 467-4249
nathanstotlar.com

Anna  Mendonca
Mortgage Loan Originator   -  CrossCountry Mortgage, Inc
Wakefield , Massachusetts  01880
phone: (781) 618-3154 | (781) 290-6383
myccmhomeloan.com/Default.aspx

Pouyan Broukhim
Owner  -  Probate Funding, Inc.
Los Angeles, California  90048
phone: (323) 935-5577
probatefunding.com

...
</code>```

ADDITIONAL:

```<code>import requests
import bs4
import pandas as pd

url = "http://www.mortgagenewsdaily.com/directory/mortgage/alabama"
data=requests.get(url)
soup=bs4.BeautifulSoup(data.text,'html.parser')

page = soup.find_all('div', class_="BusinessListingUser")

results = pd.DataFrame()
for each in page:
    content = each.find('div', class_='ListingDetails').text.split('\n')
    content = [ text.strip() for text in content if text.strip() != '' ]

    try:
        name = content[0]
    except:
        name = 'N/A'

    try:
        company = content[1]
    except:
        company = 'N/A'

    try:
        location = content[2]
    except:
        location = 'N/A'

    try:
        phone = content[3]
    except:
        phone = 'N/A'

    try:
        website = content[4]
    except:
        website = 'N/A'

    temp_df = pd.DataFrame([[name,company,location,phone,website]], columns = ['name','company','location','phone','website'])
    results = results.append(temp_df).reset_index(drop=True)

results.to_excel('C:/file.xlsx', index=False)
</code>```

Body:
I'm unable to get data from a single tag. Single tag have many data attributes like name, phone, company and url. i need to get data from many tags and all tags similar to this one.

HTML Code:

                Jeremy Counter

                                        Mortgage Officer  -
        American Pacific Mortgage

       Anchorage, Alaska  99503

                                        phone: (907) 519-
       6656 | (907) 250-0766

            jeremycounter.com

Python Code:

data=requests.get(url)
soup=bs4.BeautifulSoup(data.text,'html.parser')

page = soup.find('div', class_="CommonContentBox DirectoryListings")

listing_box = page.find('div', class_="BusinessListingUser")
name  = listing_box.find('div', class_="ListingDisplayName").text
#print(name)

details  = listing_box.find('div',
class_="ListingDetails").text.strip('\n\t\r')
print(details)

Output:

Tyler Tullis
                                          -
                                        Montgomery, Alabama  36117
                                         | (334) 322-3707

Anyone tell me the best possible solution to get data.

Expected result:

name: Jeremy Counter

phone: (907) 519-6656

company: American Pacific Mortgage

url: jeremycounter.com

Body:
No need for Selenium here. Just pull the data and iterate through it to clean it and print it:

import requests
import bs4

url = "http://www.mortgagenewsdaily.com/directory/mortgage/alabama"
data=requests.get(url)
soup=bs4.BeautifulSoup(data.text,'html.parser')

page = soup.find_all('div', class_="BusinessListingUser")

for each in page:
    content = each.find('div', class_='ListingDetails').text.split('\n')
    content = [ text.strip() for text in content if text.strip() != '' ]
    for strings in content:
        print (strings)
    print ('\n')

Output:

Tyler Tullis
-
Montgomery, Alabama  36117
| (334) 322-3707

Nathan Stotlar
Mortgage Production Manager  -  PrimeLending, a PlainsCapital Company
Fitchburg, Wisconsin  53717
phone: (608) 467-4249
nathanstotlar.com

Anna  Mendonca
Mortgage Loan Originator   -  CrossCountry Mortgage, Inc
Wakefield , Massachusetts  01880
phone: (781) 618-3154 | (781) 290-6383
myccmhomeloan.com/Default.aspx

Pouyan Broukhim
Owner  -  Probate Funding, Inc.
Los Angeles, California  90048
phone: (323) 935-5577
probatefunding.com

...

ADDITIONAL:

import requests
import bs4
import pandas as pd

url = "http://www.mortgagenewsdaily.com/directory/mortgage/alabama"
data=requests.get(url)
soup=bs4.BeautifulSoup(data.text,'html.parser')

page = soup.find_all('div', class_="BusinessListingUser")

results = pd.DataFrame()
for each in page:
    content = each.find('div', class_='ListingDetails').text.split('\n')
    content = [ text.strip() for text in content if text.strip() != '' ]

    try:
        name = content[0]
    except:
        name = 'N/A'

    try:
        company = content[1]
    except:
        company = 'N/A'

    try:
        location = content[2]
    except:
        location = 'N/A'

    try:
        phone = content[3]
    except:
        phone = 'N/A'

    try:
        website = content[4]
    except:
        website = 'N/A'

    temp_df = pd.DataFrame([[name,company,location,phone,website]], columns = ['name','company','location','phone','website'])
    results = results.append(temp_df).reset_index(drop=True)

results.to_excel('C:/file.xlsx', index=False)


问:
Recyclerview notifyDataSetChanged not called when again go to same activity
In my Requirement having wizard step.So If I am in Second Step.And pressing back.And Now I m in first wizard.And pressing next so it recreate activity.that's why I have put it into OnCreate.

When I go to that activity for first time then My Adapter notifydatasetchange work properly but when I'm go back and again goes to same activity
Notifydatasetchange() not working means onbindviewholder not called.

Even I have Tried to set adapter again but it's not still called.This is my code.What I have missing? Any help is appreciated!

```<code>    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.ProposalInviteOwnersView);
       _lstviewNearByPeople = FindViewById<RecyclerView>(Resource.Id.lstviewNearByPeople);
        _layoutmanager = new LinearLayoutManager(this, LinearLayoutManager.Horizontal, false);
        _lstviewNearByPeople.HasFixedSize = true;
        _lstviewNearByPeople.SetLayoutManager(_layoutmanager);
        BindtoNearByAdapter();
    }

    public void BindtoNearByAdapter()
    {
        try
        {
            if (GlobalConst.LstNearByPeople.Count > 0)
            {
                _lstNearByPeople = new List<Owners>();
                _lstNearByPeople.AddRange(GlobalConst.LstNearByPeople);

                if(_nearByCollaboratorAdapter==null)
                {
                    _lstviewNearByPeople.Visibility = ViewStates.Visible;

                    _nearByCollaboratorAdapter = new NearByCollaboratorAdapter(this, _lstNearByPeople, this, mlastPosition);
                    _lstviewNearByPeople.SetAdapter(_nearByCollaboratorAdapter);

                }
                else
                {
                    _nearByCollaboratorAdapter.updateItems(_lstNearByPeople);

                }

            }
            else
            {
                _noNearByDevicelayout.Visibility = ViewStates.Visible;
                _lstviewNearByPeople.Visibility = ViewStates.Gone;
            }

        }
        catch (System.Exception ex)
        {
            Core.Helpers.GlobalLogic.createCrashReport(ex);
            Toast.MakeText(this, ex.Message.ToString(), ToastLength.Short).Show();
        }
    }

    public class NearByCollaboratorAdapter : RecyclerView.Adapter
{
    public List<Owners> _lstNearByPeople;
    readonly ISelectCollaborator _listner;
    readonly Activity _context;
    protected int mLastPosition;

    public NearByCollaboratorAdapter(Activity context, List<Owners> lstNearByPeople, ISelectCollaborator listner, int _mLastPosition)
    {
        _lstNearByPeople = lstNearByPeople;
        _context = context;
        _listner = listner;
        mLastPosition = _mLastPosition;

    }
    public override int ItemCount => _lstNearByPeople.Count;

    public void updateItems(List<Owners> lstNearByPeople)
    {
        _lstNearByPeople.Clear();
        _lstNearByPeople.AddRange(lstNearByPeople);
        this.NotifyDataSetChanged();
    }

}
</code>```

答:
OnCreate is called only once, when you first launch the activity.
If you move to next activity and come back to older activity, OnCreate is not called again. So you need to shift your BindtoNearByAdapter() to OnStart or OnResume as posted by @COYG. I will recommend OnStart.

You can also check this link for better life-cycle understanding link

Body:
In my Requirement having wizard step.So If I am in Second Step.And pressing back.And Now I m in first wizard.And pressing next so it recreate activity.that's why I have put it into OnCreate.

When I go to that activity for first time then My Adapter notifydatasetchange work properly but when I'm go back and again goes to same activity
Notifydatasetchange() not working means onbindviewholder not called.

Even I have Tried to set adapter again but it's not still called.This is my code.What I have missing? Any help is appreciated!

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.ProposalInviteOwnersView);
       _lstviewNearByPeople = FindViewById<RecyclerView>(Resource.Id.lstviewNearByPeople);
        _layoutmanager = new LinearLayoutManager(this, LinearLayoutManager.Horizontal, false);
        _lstviewNearByPeople.HasFixedSize = true;
        _lstviewNearByPeople.SetLayoutManager(_layoutmanager);
        BindtoNearByAdapter();
    }

    public void BindtoNearByAdapter()
    {
        try
        {
            if (GlobalConst.LstNearByPeople.Count > 0)
            {
                _lstNearByPeople = new List<Owners>();
                _lstNearByPeople.AddRange(GlobalConst.LstNearByPeople);

                if(_nearByCollaboratorAdapter==null)
                {
                    _lstviewNearByPeople.Visibility = ViewStates.Visible;

                    _nearByCollaboratorAdapter = new NearByCollaboratorAdapter(this, _lstNearByPeople, this, mlastPosition);
                    _lstviewNearByPeople.SetAdapter(_nearByCollaboratorAdapter);

                }
                else
                {
                    _nearByCollaboratorAdapter.updateItems(_lstNearByPeople);

                }

            }
            else
            {
                _noNearByDevicelayout.Visibility = ViewStates.Visible;
                _lstviewNearByPeople.Visibility = ViewStates.Gone;
            }

        }
        catch (System.Exception ex)
        {
            Core.Helpers.GlobalLogic.createCrashReport(ex);
            Toast.MakeText(this, ex.Message.ToString(), ToastLength.Short).Show();
        }
    }

    public class NearByCollaboratorAdapter : RecyclerView.Adapter
{
    public List<Owners> _lstNearByPeople;
    readonly ISelectCollaborator _listner;
    readonly Activity _context;
    protected int mLastPosition;

    public NearByCollaboratorAdapter(Activity context, List<Owners> lstNearByPeople, ISelectCollaborator listner, int _mLastPosition)
    {
        _lstNearByPeople = lstNearByPeople;
        _context = context;
        _listner = listner;
        mLastPosition = _mLastPosition;

    }
    public override int ItemCount => _lstNearByPeople.Count;

    public void updateItems(List<Owners> lstNearByPeople)
    {
        _lstNearByPeople.Clear();
        _lstNearByPeople.AddRange(lstNearByPeople);
        this.NotifyDataSetChanged();
    }

}


问:
How to call multiple function with @click scrolling vuetify
How to call a multiple

```<code><tr @click="$vuetify.goTo('#detail');testclick();">
</code>```

```<code> methods: {
      testclick: function(data) {
        console.log('clicked')
      }
</code>```

How to do it right?

Help me please

答:
You can have a handler method which can call as multiple methods as you want:

```<code> methods: {
      handlerMethod() {
        this.$vuetify.goTo('#detail');
        this.testClick()
      },

      testClick () {
        console.log('clicked')
      }
}
</code>```

Body:
How to call a multiple

 methods: {
      testclick: function(data) {
        console.log('clicked')
      }

How to do it right?

Help me please

Body:
You can have a handler method which can call as multiple methods as you want:

<tr @click="handlerMethod">

 methods: {
      handlerMethod() {
        this.$vuetify.goTo('#detail');
        this.testClick()
      },

      testClick () {
        console.log('clicked')
      }
}


问:
C#, calling an instance of a class from a string
I've been struggling for a while to find a way of calling an instance of a class from a user defined input.

Essentially I want to call an instance from my StandardVehicle class that has already been defined, however the problem is that the name of the instance that I'm calling is defined by a users selection on a combo box on a form.

This is how I assumed it would be formatted, however I get an error when I try calling the instance saying that I cannot complicitly convert from string to StandardVehicle.

```<code>        StandardVehicle VauxhallB = new StandardVehicle();
        VauxhallB.Model = "B";
        VauxhallB.Manufacturer = "Vauxhall";
        VauxhallB.Doors = 5;
        VauxhallB.HorsePower = 200;
        VauxhallB.Transmission = "Manual";
        VauxhallB.Year = 2009;
        VauxhallB.Cylinders = 6;
        VauxhallB.Seats = 7;
        VauxhallB.Price = 17000;
        VauxhallB.Registration = "abc1243";

        StandardVehicle objname = comboBox1.Text;
</code>```

I'm assuming it's just a case of formatting the string, but I've been searching for hours and can't figure out what format it needs to be in to define it as an instance.

Any help would be appreciated.

Regards,
S.

答:
No, it's definitely not a case of just formatting the string. It sounds like you want a

```<code>Dictionary<string, StandardVehicle>
</code>```

Populate that to map from strings to objects, then look up the object corresponding to the name given by the user.

ContentLicense: CC BY-SA 3.0

Body:
I've been struggling for a while to find a way of calling an instance of a class from a user defined input.

Essentially I want to call an instance from my StandardVehicle class that has already been defined, however the problem is that the name of the instance that I'm calling is defined by a users selection on a combo box on a form.

This is how I assumed it would be formatted, however I get an error when I try calling the instance saying that I cannot complicitly convert from string to StandardVehicle.

        StandardVehicle VauxhallB = new StandardVehicle();
        VauxhallB.Model = "B";
        VauxhallB.Manufacturer = "Vauxhall";
        VauxhallB.Doors = 5;
        VauxhallB.HorsePower = 200;
        VauxhallB.Transmission = "Manual";
        VauxhallB.Year = 2009;
        VauxhallB.Cylinders = 6;
        VauxhallB.Seats = 7;
        VauxhallB.Price = 17000;
        VauxhallB.Registration = "abc1243";

        StandardVehicle objname = comboBox1.Text;

I'm assuming it's just a case of formatting the string, but I've been searching for hours and can't figure out what format it needs to be in to define it as an instance.

Any help would be appreciated.

Regards,
S.

Body:
No, it's definitely not a case of just formatting the string. It sounds like you want a

Dictionary<string, StandardVehicle>

Populate that to map from strings to objects, then look up the object corresponding to the name given by the user.


问:
convert date into format 2019-05-31T12:08:04Z momentjs
How to convert date into format 2019-05-31T12:08:04Z using momentjs? And which format it is?

答:
This is the iso format, explanation

As pindev said in comment you can do : moment().toDate().toISOString()


问:
IllegalAccessError only on Android 9 inside AsyncTask
IllegalAccessError happen only on Android 9 during an AsyncTask function

Is there something to do on Android 9 ? All others version are OK.

The error is seen on production app.

I have already try to make everything public, and in same package. This error is still there on version 9.

```<code>    new TestTask(this, "test", true).execute(value);

public class TestTask extends AsyncTask<String, Void, String> {

    private String param1;
    private boolean param2;
    private String number;
    private WeakReference<Context> appReference;

    TestTask(Context context, String param1, boolean param2) {
        this.appReference = new WeakReference<>(context);
        this.param1 = param1;
        this.param2 = param2;
    }

    @Override
    public String doInBackground(String... values) {
        try {
            number = values[0];

            if(param2)
                performVib();

            ResponseEvent response = new TestSnmp(param1).set(number);

        if( appReference.get()!=null && m_debugMode) {
            Toast.makeText(appReference.get(), "Response: " + response, Toast.LENGTH_SHORT).show();
        }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void onPostExecute(String result) {
        super.onPostExecute(result);
        try {
            if( appReference.get()!=null ) {
                Toast.makeText(appReference.get(), "Some text", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

Here is the stack:

```<code>java.lang.RuntimeException:
  at android.os.AsyncTask$3.done (AsyncTask.java:354)
  at java.util.concurrent.FutureTask.finishCompletion (FutureTask.java:383)
  at java.util.concurrent.FutureTask.setException (FutureTask.java:252)
  at java.util.concurrent.FutureTask.run (FutureTask.java:271)
  at android.os.AsyncTask$SerialExecutor$1.run (AsyncTask.java:245)
  at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1167)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:641)
  at java.lang.Thread.run (Thread.java:764)
Caused by: java.lang.IllegalAccessError:
  at xxx.TestTask.doInBackground (TestTask.java)
  at xxx.TestTask.doInBackground (TestTask.java)
  at android.os.AsyncTask$2.call (AsyncTask.java:333)
  at java.util.concurrent.FutureTask.run (FutureTask.java:266)
  at android.os.AsyncTask$SerialExecutor$1.run (AsyncTask.java:245)
  at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1167)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:641)
  at java.lang.Thread.run (Thread.java:764)
</code>```

答: I changed the constuctor from BboxSend to TestTask and run the code on Android 9. It's working.</p>

Body:
IllegalAccessError happen only on Android 9 during an AsyncTask function

Is there something to do on Android 9 ? All others version are OK.

The error is seen on production app.

I have already try to make everything public, and in same package. This error is still there on version 9.

    new TestTask(this, "test", true).execute(value);

public class TestTask extends AsyncTask<String, Void, String> {

    private String param1;
    private boolean param2;
    private String number;
    private WeakReference<Context> appReference;

    TestTask(Context context, String param1, boolean param2) {
        this.appReference = new WeakReference<>(context);
        this.param1 = param1;
        this.param2 = param2;
    }

    @Override
    public String doInBackground(String... values) {
        try {
            number = values[0];

            if(param2)
                performVib();

            ResponseEvent response = new TestSnmp(param1).set(number);

        if( appReference.get()!=null && m_debugMode) {
            Toast.makeText(appReference.get(), "Response: " + response, Toast.LENGTH_SHORT).show();
        }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void onPostExecute(String result) {
        super.onPostExecute(result);
        try {
            if( appReference.get()!=null ) {
                Toast.makeText(appReference.get(), "Some text", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Here is the stack:

java.lang.RuntimeException:
  at android.os.AsyncTask$3.done (AsyncTask.java:354)
  at java.util.concurrent.FutureTask.finishCompletion (FutureTask.java:383)
  at java.util.concurrent.FutureTask.setException (FutureTask.java:252)
  at java.util.concurrent.FutureTask.run (FutureTask.java:271)
  at android.os.AsyncTask$SerialExecutor$1.run (AsyncTask.java:245)
  at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1167)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:641)
  at java.lang.Thread.run (Thread.java:764)
Caused by: java.lang.IllegalAccessError:
  at xxx.TestTask.doInBackground (TestTask.java)
  at xxx.TestTask.doInBackground (TestTask.java)
  at android.os.AsyncTask$2.call (AsyncTask.java:333)
  at java.util.concurrent.FutureTask.run (FutureTask.java:266)
  at android.os.AsyncTask$SerialExecutor$1.run (AsyncTask.java:245)
  at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1167)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:641)
  at java.lang.Thread.run (Thread.java:764)


问:
How can we control error pages in Jetty Websocket with Camel
We are using Apache Camel Jetty Websocket 2.17.1 with jetty 8.

We went through PCI scan and in this we found it is returning 404 pages with resources like

```<code>       <html>
         <head>
             <meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1"/>
             <title>Error 404 Not Found</title>
         </head>
         <body>
             <h2>HTTP ERROR: 404</h2>
             <p>Problem accessing /TOKENIZE.. Reason:

                 ```    Not Found```
             </p>
             <hr />
             <i>
                 <small>Powered by Jetty://</small>
             </i>
         </body>
     </html>
</code>```

I changed this for Jetty Apache Camel component with errorHandler. But not able to change or trace the error page content returned on response with HTTP /GET.

PCI guys tried sending /GET  for websocket port and app is returning above 404 content.

FYI. I also set Error Handler in ServletContextHandler.But Still my error handler is not pickedup.

答:
Jetty 8 (now EOL/End of Life) did not have the ErrorHandler wired up correctly for odd behaviors like HTTP Upgrade only paths (which websocket in jetty 8 is).

Jetty 9.x has overhauled the ErrorHandler to work for all request errors that reach the same context path as the ErrorHandler.

Which means that the only kinds of errors that currently do not go through the ErrorHandler in Jetty 9.x+ are ones that do not reach a context.  Such as bad HTTP requests resulting in a 400 status code or proxy requests.

Body:
We are using Apache Camel Jetty Websocket 2.17.1 with jetty 8.

We went through PCI scan and in this we found it is returning 404 pages with resources like

             <meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1"/>
             <title>Error 404 Not Found</title>

HTTP ERROR: 404

Problem accessing /TOKENIZE.. Reason:

    Not Found

                 Powered by Jetty://

I changed this for Jetty Apache Camel component with errorHandler. But not able to change or trace the error page content returned on response with HTTP /GET.

PCI guys tried sending /GET  for websocket port and app is returning above 404 content.

FYI. I also set Error Handler in ServletContextHandler.But Still my error handler is not pickedup.


问:
How to make bot send Direct Message To Someone that the bot don't have it in mutal servers and have his id
I want to know the code that I can get the user that the bot isn't in his mutual servers and I have his id I want the bot to send him Direct Message what is the code?

I didn't try anything I'm a noob at this in learning

答:
Use the Client.fetchUser() method.

Example 1:

let ID = '123456789012345678';

client.fetchUser(ID)
  .then(user => user.send('hello'))
  .catch(console.error);
```

<p>Example 2 <em>(must be within an async function)</em>:</p>

<pre class="lang-js prettyprint-override"><code>let ID = '123456789012345678';

try {
  let user = await client.fetchUser(ID);
  await user.send('hello');
} catch(err) {
  console.error(err);
}
</code>```

Body:
Use the Client.fetchUser() method.

Example 1:

let ID = '123456789012345678';

client.fetchUser(ID)
  .then(user => user.send('hello'))
  .catch(console.error);

Example 2 (must be within an async function):

let ID = '123456789012345678';

try {
  let user = await client.fetchUser(ID);
  await user.send('hello');
} catch(err) {
  console.error(err);
}


问:
Awk: generating icalendar file. How to print some consecutive lines?

Thanks to Ed Morton's answer, I could do some testing with Thunderbird and icalendar validator. I edited my question adding entries without description and the expected result with precise requirements.

I'm writing a script to generate an icalendar file from a planing text file. I'd like to get the description content with the lines coming after the date. Say I've got a planning file:

```<code>lun 06 05 2019 08 15 09 00 F206
    A descritpion text.
ven 10 05 2019 11 00 11 45 G202
    Another description text
    - on multiple;
    - lines.
lun 13 05 2019 08 15 09 00 F206
ven 17 05 2019 11 00 11 45 G202
    A long description with more than 75 characters.
    This happen often when multiple lines are
    joined in one. So the program shoud split every lines
    To 75 characters including the word description.
lun 20 05 2019 08 15 09 00 F206
    A description text.
</code>```

My script looks like this, I'm a newbie with awk:

```<code>#!/bin/bash
awk ' BEGIN { print "BEGIN:VCALENDAR\r\n\
... some entries here ...\r\n\
END:VTIMEZONE\r" ;}
$1~/^(lun|mar|mer|jeu|ven)$/ { print "BEGIN:VEVENT\r\n\
... some entries here ...\r\n\
DTSTART;TZID=Europe/Zurich:"$4""$3""$2"T"$5""$6"00\r\n\
DTEND;TZID=Europe/Zurich:"$4""$3""$2"T"$7""$8"00\r\n\
TRANSP:OPAQUE\r\n\
DESCRIPTION: >>>HERE I NEED THE DESCRIPTIVE LINES<<<< \r\n\
END:VEVENT\r"}
END { print "END:VCALENDAR" } ' < $1 > $1.ics
</code>```

expected result:

```<code>BEGIN:VCALENDAR
BEGIN:VEVENT
DTSTART;TZID=Europe/Zurich:20190506T081500
DTEND;TZID=Europe/Zurich:20190506T090000
DESCRIPTION:A descritpion text.
END:VEVENT
BEGIN:VEVENT
DTSTART;TZID=Europe/Zurich:20190510T110000
DTEND;TZID=Europe/Zurich:20190510T114500
DESCRIPTION:Another description text\n- on multiple;\n- lines.
END:VEVENT
BEGIN:VEVENT
DTSTART;TZID=Europe/Zurich:20190513T081500
DTEND;TZID=Europe/Zurich:20190513T090000
END:VEVENT
BEGIN:VEVENT
DTSTART;TZID=Europe/Zurich:20190517T110000
DTEND;TZID=Europe/Zurich:20190517T114500
DESCRIPTION:A long description with more than 75 characters.\nThis happen
 often when multiple lines are\njoined in one. So the program shoud split
 every lines\nTo 75 characters including the word description.
END:VEVENT
BEGIN:VEVENT
DTSTART;TZID=Europe/Zurich:20190520T081500
DTEND;TZID=Europe/Zurich:20190520T090000
DESCRIPTION: A description text.
END:VEVENT
END:VCALENDAR
</code>```

So the exact requirements are:

Lines without description should not print DESCRIPTION:.

Multiline description should be joined an separated with a literal \n. This is working with a printf "%s%s", $0, "\\n"

The lines should be splited to fewer than 75 characters, ending with a \r\n

The additional description lines should begin with a space.

答:
You really are on the right track. Here's your script integrated with the flag logic:

```<code>#!/bin/bash
awk 'BEGIN {print "BEGIN:VCALENDAR\r\n\
... some entries here ...\r\n\
END:VTIMEZONE\r" ;}
$1~/^(lun|mar|mer|jeu|ven)$/ && flag {flag = !flag; print "END:VEVENT\r"}
$1~/^(lun|mar|mer|jeu|ven)$/ && !flag {flag = !flag; print "BEGIN:VEVENT\r\n\
... some entries here ...\r\n\
DTSTART;TZID=Europe/Zurich:"$4""$3""$2"T"$5""$6"00\r\n\
DTEND;TZID=Europe/Zurich:"$4""$3""$2"T"$7""$8"00\r\n\
TRANSP:OPAQUE\r\n\
DESCRIPTION: "; next}
flag {print $0}
END { print "END:VCALENDAR" } ' < $1
</code>```

Output:

```<code>BEGIN:VCALENDAR
... some entries here ...
END:VTIMEZONE
BEGIN:VEVENT
... some entries here ...
DTSTART;TZID=Europe/Zurich:20190506T081500
DTEND;TZID=Europe/Zurich:20190506T090000
TRANSP:OPAQUE
DESCRIPTION:
    Some descriptive lines here.
    Lorem ipsumi dolor sit amet, consectetur adipiscing elitr.
END:VEVENT
BEGIN:VEVENT
... some entries here ...
DTSTART;TZID=Europe/Zurich:20190510T110000
DTEND;TZID=Europe/Zurich:20190510T114500
TRANSP:OPAQUE
DESCRIPTION:
    sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
    - enim
    - ad minim veniam.
END:VEVENT
BEGIN:VEVENT
... some entries here ...
DTSTART;TZID=Europe/Zurich:20190513T081500
DTEND;TZID=Europe/Zurich:20190513T090000
TRANSP:OPAQUE
DESCRIPTION:
    exercitation ullamco
END:VEVENT
BEGIN:VEVENT
... some entries here ...
DTSTART;TZID=Europe/Zurich:20190517T110000
DTEND;TZID=Europe/Zurich:20190517T114500
TRANSP:OPAQUE
DESCRIPTION:
    quis nostrud
END:VCALENDAR
</code>```

Body:
Thanks to Ed Morton's answer, I could do some testing with Thunderbird and icalendar validator. I edited my question adding entries without description and the expected result with precise requirements.

I'm writing a script to generate an icalendar file from a planing text file. I'd like to get the description content with the lines coming after the date. Say I've got a planning file:

lun 06 05 2019 08 15 09 00 F206
    A descritpion text.
ven 10 05 2019 11 00 11 45 G202
    Another description text
    - on multiple;
    - lines.
lun 13 05 2019 08 15 09 00 F206
ven 17 05 2019 11 00 11 45 G202
    A long description with more than 75 characters.
    This happen often when multiple lines are
    joined in one. So the program shoud split every lines
    To 75 characters including the word description.
lun 20 05 2019 08 15 09 00 F206
    A description text.

My script looks like this, I'm a newbie with awk:

#!/bin/bash
awk ' BEGIN { print "BEGIN:VCALENDAR\r\n\
... some entries here ...\r\n\
END:VTIMEZONE\r" ;}
$1~/^(lun|mar|mer|jeu|ven)$/ { print "BEGIN:VEVENT\r\n\
... some entries here ...\r\n\
DTSTART;TZID=Europe/Zurich:"$4""$3""$2"T"$5""$6"00\r\n\
DTEND;TZID=Europe/Zurich:"$4""$3""$2"T"$7""$8"00\r\n\
TRANSP:OPAQUE\r\n\
DESCRIPTION: >>>HERE I NEED THE DESCRIPTIVE LINES<<<< \r\n\
END:VEVENT\r"}
END { print "END:VCALENDAR" } ' < $1 > $1.ics

expected result:

BEGIN:VCALENDAR
BEGIN:VEVENT
DTSTART;TZID=Europe/Zurich:20190506T081500
DTEND;TZID=Europe/Zurich:20190506T090000
DESCRIPTION:A descritpion text.
END:VEVENT
BEGIN:VEVENT
DTSTART;TZID=Europe/Zurich:20190510T110000
DTEND;TZID=Europe/Zurich:20190510T114500
DESCRIPTION:Another description text\n- on multiple;\n- lines.
END:VEVENT
BEGIN:VEVENT
DTSTART;TZID=Europe/Zurich:20190513T081500
DTEND;TZID=Europe/Zurich:20190513T090000
END:VEVENT
BEGIN:VEVENT
DTSTART;TZID=Europe/Zurich:20190517T110000
DTEND;TZID=Europe/Zurich:20190517T114500
DESCRIPTION:A long description with more than 75 characters.\nThis happen
 often when multiple lines are\njoined in one. So the program shoud split
 every lines\nTo 75 characters including the word description.
END:VEVENT
BEGIN:VEVENT
DTSTART;TZID=Europe/Zurich:20190520T081500
DTEND;TZID=Europe/Zurich:20190520T090000
DESCRIPTION: A description text.
END:VEVENT
END:VCALENDAR

So the exact requirements are:

Lines without description should not print DESCRIPTION:.

Multiline description should be joined an separated with a literal \n. This is working with a printf "%s%s", $0, "\\n"

The lines should be splited to fewer than 75 characters, ending with a \r\n

The additional description lines should begin with a space.

Body:
You really are on the right track. Here's your script integrated with the flag logic:

#!/bin/bash
awk 'BEGIN {print "BEGIN:VCALENDAR\r\n\
... some entries here ...\r\n\
END:VTIMEZONE\r" ;}
$1~/^(lun|mar|mer|jeu|ven)$/ && flag {flag = !flag; print "END:VEVENT\r"}
$1~/^(lun|mar|mer|jeu|ven)$/ && !flag {flag = !flag; print "BEGIN:VEVENT\r\n\
... some entries here ...\r\n\
DTSTART;TZID=Europe/Zurich:"$4""$3""$2"T"$5""$6"00\r\n\
DTEND;TZID=Europe/Zurich:"$4""$3""$2"T"$7""$8"00\r\n\
TRANSP:OPAQUE\r\n\
DESCRIPTION: "; next}
flag {print $0}
END { print "END:VCALENDAR" } ' < $1

Output:

BEGIN:VCALENDAR
... some entries here ...
END:VTIMEZONE
BEGIN:VEVENT
... some entries here ...
DTSTART;TZID=Europe/Zurich:20190506T081500
DTEND;TZID=Europe/Zurich:20190506T090000
TRANSP:OPAQUE
DESCRIPTION:
    Some descriptive lines here.
    Lorem ipsumi dolor sit amet, consectetur adipiscing elitr.
END:VEVENT
BEGIN:VEVENT
... some entries here ...
DTSTART;TZID=Europe/Zurich:20190510T110000
DTEND;TZID=Europe/Zurich:20190510T114500
TRANSP:OPAQUE
DESCRIPTION:
    sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
    - enim
    - ad minim veniam.
END:VEVENT
BEGIN:VEVENT
... some entries here ...
DTSTART;TZID=Europe/Zurich:20190513T081500
DTEND;TZID=Europe/Zurich:20190513T090000
TRANSP:OPAQUE
DESCRIPTION:
    exercitation ullamco
END:VEVENT
BEGIN:VEVENT
... some entries here ...
DTSTART;TZID=Europe/Zurich:20190517T110000
DTEND;TZID=Europe/Zurich:20190517T114500
TRANSP:OPAQUE
DESCRIPTION:
    quis nostrud
END:VCALENDAR


问:
Text manipulation of a file
I'm rather noob on bash (or perl).  Looking a way to modify some lines in a file, (basically removing the first 2 characters of each line, and add a "," at the end of each line)

```<code>###element
##.element
###test-element-00
</code>```

becomes the following,

```<code>#element,
.element,
#test-element-00,
</code>```

Thanks

答: Bash can handle this just fine: line="##element"; echo "${line#??},"

ContentLicense: CC BY-SA 2.5

Title: Text manipulation of a file

Body:
I'm rather noob on bash (or perl).  Looking a way to modify some lines in a file, (basically removing the first 2 characters of each line, and add a "," at the end of each line)

###element
##.element
###test-element-00

becomes the following,

#element,
.element,
#test-element-00,

Thanks


问:
Export Charts from Excel as images using Python
I have been trying to export the charts from Excel as an image file (JPG or ING) in Python. I am looking at the WIn32com. Here is what I have till now.

```<code>import win32com.client as win32
excel = win32.gencache.EnsureDispatch("Excel.Application")
wb = excel.Workbooks.Open("<WORKSHEET NAME>")
r = wb.Sheets("<SHEET NAME>").Range("A1:J50")
# Here A1:J50 is the area over which cart is
r.CopyPicture()
</code>```

This is where I am stuck. I need to copy the selected range to a file now. Any help or pointers towards the doc can help me a lot.

I have modelled the above code based on the following VBA script:

```<code>Sub Export_Range_Images()
    ' =========================================
    ' Code to save selected Excel Range as Image
    ' =========================================
    Dim oRange As Range
    Dim oCht As Chart
    Dim oImg As Picture

    Set oRange = Range("A1:B2")
    Set oCht = Charts.Add
    oRange.CopyPicture xlScreen, xlPicture
    oCht.Paste
    oCht.Export FileName:="C:\temp\SavedRange.jpg", Filtername:="JPG"
End Sub
</code>```

Code Snippet from : http://vbadud.blogspot.com/2010/06/how-to-save-excel-range-as-image-using.html

答:
Nowadays I would recommend excel2img library, served me well. Make sure you have it installed (pip install excel2img)

```<code>import excel2img

excel2img.export_img("test.xlsx", "test.gif", "Sheet1", "MyNamedRange")
</code>```

If you don't need gridlines - just hide it on excel.

git rep: excel2img to learn more.

Body:
I have been trying to export the charts from Excel as an image file (JPG or ING) in Python. I am looking at the WIn32com. Here is what I have till now.

import win32com.client as win32
excel = win32.gencache.EnsureDispatch("Excel.Application")
wb = excel.Workbooks.Open("<WORKSHEET NAME>")
r = wb.Sheets("<SHEET NAME>").Range("A1:J50")
# Here A1:J50 is the area over which cart is
r.CopyPicture()

This is where I am stuck. I need to copy the selected range to a file now. Any help or pointers towards the doc can help me a lot.

I have modelled the above code based on the following VBA script:

Sub Export_Range_Images()
    ' =========================================
    ' Code to save selected Excel Range as Image
    ' =========================================
    Dim oRange As Range
    Dim oCht As Chart
    Dim oImg As Picture

    Set oRange = Range("A1:B2")
    Set oCht = Charts.Add
    oRange.CopyPicture xlScreen, xlPicture
    oCht.Paste
    oCht.Export FileName:="C:\temp\SavedRange.jpg", Filtername:="JPG"
End Sub

Code Snippet from : http://vbadud.blogspot.com/2010/06/how-to-save-excel-range-as-image-using.html

Body:
Nowadays I would recommend excel2img library, served me well. Make sure you have it installed (pip install excel2img)

import excel2img

excel2img.export_img("test.xlsx", "test.gif", "Sheet1", "MyNamedRange")

If you don't need gridlines - just hide it on excel.

git rep: excel2img to learn more.


问:
Can't read any response with HTTPS GET request in Java
I have a problem with HTTPS requests, i want to make a very simple Java program for reading the response of a GET request.
The problem is that i can't read any response, and the program prints nothing on screen.

This is the code:

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

import javax.net.ssl.*;

public class Test
{
  public static void main(String args[])
  {
    SSLSocket sock;
    String host = "www.example.com";

    try{
      SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
      sock = (SSLSocket) factory.createSocket(host, 443);

    }
    catch(IOException e)
    {
      e.printStackTrace();
      return;
    }

    try {

      BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
      bw.write("GET / HTTP/1.1\r\n");
      bw.write("Accept: text/html\r\n");
      bw.write("User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36\r\n");
      bw.write("\r\n");
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }

    try{
      BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
      StringBuffer buffer = new StringBuffer();
      String temp;
      while((temp = br.readLine()) != null)
      {
        buffer.append(temp);
      }
      br.close();
      System.out.println(buffer);
    }
    catch(IOException e)
    {
      e.printStackTrace();
      return;
    }

  }
}
</code>```

I'm using SSLSocket with SSLSocketFactory, is there any procedure that i have to do in order to get the response from the server?

答:
First, you need to call flush() to make sure the buffered data is actually written to the socket when you're ready.

```<code>  bw.write("GET / HTTP/1.1\r\n");
  bw.write("Accept: text/html\r\n");
  bw.write("User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36\r\n");
  bw.write("\r\n");
  bw.flush();   // ADD THIS LINE
</code>```

Secondly, you need to send valid HTTP 1.1 headers. The RFCs are quite complicated, which is another reason to rely on well-regarded existing HTTP client libraries, but there is information here and elsewhere that should help, for example this. You are missing at least a Host: header for example.

Body:
I have a problem with HTTPS requests, i want to make a very simple Java program for reading the response of a GET request.
The problem is that i can't read any response, and the program prints nothing on screen.

This is the code:

import java.io.*;
import java.net.*;
import java.util.*;

import javax.net.ssl.*;

public class Test
{
  public static void main(String args[])
  {
    SSLSocket sock;
    String host = "www.example.com";

    try{
      SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
      sock = (SSLSocket) factory.createSocket(host, 443);

    }
    catch(IOException e)
    {
      e.printStackTrace();
      return;
    }

    try {

      BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
      bw.write("GET / HTTP/1.1\r\n");
      bw.write("Accept: text/html\r\n");
      bw.write("User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36\r\n");
      bw.write("\r\n");
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }

    try{
      BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
      StringBuffer buffer = new StringBuffer();
      String temp;
      while((temp = br.readLine()) != null)
      {
        buffer.append(temp);
      }
      br.close();
      System.out.println(buffer);
    }
    catch(IOException e)
    {
      e.printStackTrace();
      return;
    }

  }
}

I'm using SSLSocket with SSLSocketFactory, is there any procedure that i have to do in order to get the response from the server?

Body:
First, you need to call flush() to make sure the buffered data is actually written to the socket when you're ready.

  bw.write("GET / HTTP/1.1\r\n");
  bw.write("Accept: text/html\r\n");
  bw.write("User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36\r\n");
  bw.write("\r\n");
  bw.flush();   // ADD THIS LINE

Secondly, you need to send valid HTTP 1.1 headers. The RFCs are quite complicated, which is another reason to rely on well-regarded existing HTTP client libraries, but there is information here and elsewhere that should help, for example this. You are missing at least a Host: header for example.


问:
How to deselect "https://mail.google.com/ scope" in Credentials
I am lost in the user interface of Google developer console.
Created two scopes for google mail:

https://mail.google.com/

https://www.googleapis.com/auth/gmail.send

Now I need to get rid of nr. 1 but cannot find anywhere in the developer console any user interface to allow me to deselect the "https://mail.google.com/ scope".

Below is the email From Google with what I am supposed to do:

Begin Quote

Dear Developer,

Thank you for your response.

To proceed with the verification process, please deselect the https://mail.google.com/ scope and update the request for scopes in the codebase of your app so that the scopes requested by your app match the scopes in your Console.

End Quote

In "Credentials > Oauth consent screen" I clicked on the "trash" icon to delete it. After refreshing the page was still there.
In the "Add New Scope" list, is grayed out, so cannot deselect. What can I do?

Screenshot https://filebin.net/yg4g37xjmcu5bcxv/scope.png?t=v9jjj7g6

Thanks!

答:
In the end, after deleting "https://mail.google.com/ scope", I submitted again for verification.
Now the scope I wanted to delete is gone and will go again through the verification process. What a mess!</p>


问:
Is there any event like itemEditEnding or any other way to stop event before itemEditEnd event in datagrids of Flex 4?
I have editable grids which are 2-way binded to my model. What I want is to validate my data when user edits any cell before it get updated in model. I have applied my validation at ItemEditEnd handler, but, I want to apply validation in between itemEditBegin and itemEditEnd events.

any ideas how to achieve this?

答:
For this level of validation I would create a Validator for the type of data you're editing (string, number, etc.) and set the Validator's trigger to the change event of your itemEditor component.

Check out Adobe's example on using validators in an itemEditor for more info.

Update:

You may also want to check out this related question.

"In your event listener, you can
  examine the data entered into the item
  editor. If the data is incorrect, you
  can call the preventDefault() method
  to stop Flex from passing the new data
  back to the list-based control and
  from closing the editor."


问:
Vector to array within a loop not working
When I try to convert a vector of integers to a array of integers inside a loop although within the loop the conversion appears to have worked, once the loop terminates the value within the array is incorrect.

I tried the std::copy instead of &vector[0] and the same problem arises. And I am aware that converting the vector to a array is not necessary. I assume the problem is due because the array is assigned a pointer to a variable which is destroyed after the loop, but i'm fairly new to c++ so even if I am correct I don't know how to fix it.

```<code>#include "pch.h"
#include <iostream>
#include <vector>

int main()
{
    int* arr;
    for (int i = 0; i < 1; i++)
    {
        std::vector<int> vec{ 1 };
        arr = &vec[0];
        std::cout << "Inside the loop in the vector: " << vec[0] << std::endl;
        std::cout << "Inside the loop in the array: " << arr[0] << std::endl;
    }
    std::cout << "Outside the loop in the array: " << arr[0];
}
</code>```

I would expect the output to look like this:

Inside the loop in the vector: 1

Inside the loop in the array: 1

Outside the loop in the array: 1

But it actually turns out like this:

Inside the loop in the vector: 1

Inside the loop in the array: 1

Outside the loop in the array: -572662307

答:
The storage for vec[0] is freed when vec falls out of scope.  You wouldn't expect a pointer to it to be valid outside the scope in which the vec variable lives.

I suggest you read this answer.

Body:
When I try to convert a vector of integers to a array of integers inside a loop although within the loop the conversion appears to have worked, once the loop terminates the value within the array is incorrect.

I tried the std::copy instead of &vector[0] and the same problem arises. And I am aware that converting the vector to a array is not necessary. I assume the problem is due because the array is assigned a pointer to a variable which is destroyed after the loop, but i'm fairly new to c++ so even if I am correct I don't know how to fix it.

#include "pch.h"
#include <iostream>
#include <vector>

int main()
{
    int* arr;
    for (int i = 0; i < 1; i++)
    {
        std::vector<int> vec{ 1 };
        arr = &vec[0];
        std::cout << "Inside the loop in the vector: " << vec[0] << std::endl;
        std::cout << "Inside the loop in the array: " << arr[0] << std::endl;
    }
    std::cout << "Outside the loop in the array: " << arr[0];
}

I would expect the output to look like this:

Inside the loop in the vector: 1

Inside the loop in the array: 1

Outside the loop in the array: 1

But it actually turns out like this:

Inside the loop in the vector: 1

Inside the loop in the array: 1

Outside the loop in the array: -572662307


答:
int* arr; <- This is a pointer, not an array.

std::vector<int> vec{ 1 }; <- This vector only exists within the body of your loop. That means, every iteration a new vector is created, and at the end of the iteration it is destroyed, freeing the memory it allocated.

arr = &vec[0]; <- This line doesn't copy anything, it simply sets the address that arr points to, to the first element in the vector's allocated memory.

Since your vector is destroyed after the loop, the address arr points to is invalid. As long as you are inside the loop, the address it points to is valid and you can safely access that memory.

You were right to try std::copy, however if you want to copy anything, you need to have memory allocated first that you can copy into. int arr[1]; would create an array of int with size 1, which can be used as the destination in std::copy. int* arr = new int[1]; would also work, but requires that you also free the memory later yourself (delete[] arr;). I wouldn't recommend managing memory yourself except for learning purposes.

Title: Vector to array within a loop not working


问:
Import Paramiko in Jython
I am trying to import python paramiko module from java program. So for that i used jython. When i try to import paramiko from jython it gives below error,

Exception in thread "main" Traceback (most recent call last):
  File "", line 1, in
ImportError: No module named paramiko

Please advice me to import paramiko from jython.

public class jythonTest {
    public static void main(String[] args) throws PyException {

```<code>    PythonInterpreter interp = new PythonInterpreter();

    interp.exec("import sys");
    interp.exec("import paramiko");
    interp.exec("import time");
   }
</code>```

}

答:
This might be because Jython doesn't read the Python packages from the place where you might have installed them in Python through CLI.

One way to solve your problem is to install Paramiko in during the execution of the code:

```<code>PythonInterpreter interp = new PythonInterpreter();

interp.exec("from pip._internal import main as pip_main");
interp.exec("pip_main(['install', 'paramiko'])")
interp.exec("import paramiko");
</code>```

Or

```<code>PythonInterpreter interp = new PythonInterpreter();

interp.exec("from pip import main as pip_main");
interp.exec("pip_main(['install', 'paramiko'])")
interp.exec("import paramiko");
</code>```

Refer to Installing python module within code for more ways to install packages in code depending on your python version. The above should hold good for Python 2.7, which is what I believe Jython is based on.

Title: Import Paramiko in Jython

Body:
I am trying to import python paramiko module from java program. So for that i used jython. When i try to import paramiko from jython it gives below error,

Exception in thread "main" Traceback (most recent call last):
  File "", line 1, in
ImportError: No module named paramiko

Please advice me to import paramiko from jython.

public class jythonTest {
    public static void main(String[] args) throws PyException {

    PythonInterpreter interp = new PythonInterpreter();

    interp.exec("import sys");
    interp.exec("import paramiko");
    interp.exec("import time");
   }

}

Body:
This might be because Jython doesn't read the Python packages from the place where you might have installed them in Python through CLI.

One way to solve your problem is to install Paramiko in during the execution of the code:

PythonInterpreter interp = new PythonInterpreter();

interp.exec("from pip._internal import main as pip_main");
interp.exec("pip_main(['install', 'paramiko'])")
interp.exec("import paramiko");

Or

PythonInterpreter interp = new PythonInterpreter();

interp.exec("from pip import main as pip_main");
interp.exec("pip_main(['install', 'paramiko'])")
interp.exec("import paramiko");

Refer to Installing python module within code for more ways to install packages in code depending on your python version. The above should hold good for Python 2.7, which is what I believe Jython is based on.


问:
MySQL UNION does not work consistently. If I switch the posision of two clause, the results are different each other
According to the position of clauses, mysql results differently.

```<code>SELECT sum(if(bos = 'B', txn_qty*-1, txn_qty)) as qty
FROM tstock_txn
WHERE date_format(txn_date, '%Y%m') >= '201905' and company_id='003490'
union all
SELECT qty as qty FROM tstock_txn_temp WHERE company_id='003490'
</code>```

result: correct

```<code>-290
290
</code>```

changed query

```<code>SELECT qty as qty
FROM tstock_txn_temp
WHERE company_id='003490'
union ALL
SELECT sum(if(bos = 'B', txn_qty*-1, txn_qty)) as qty
FROM tstock_txn
WHERE date_format(txn_date, '%Y%m') >= '201905' and company_id='003490'
</code>```

result: not correct

```<code>290
0
</code>```

the result should be

```<code>290
-290
</code>```

答:
Now I found the reason of the problem.
The attribute of qty column of tstock_txn_temp is unsigned int.
So the below clause's value is changed to zero.

My dev table attribues and product table atributes are a little diffetent.
So I counldn't find the root cause in the shell.

Anyway I think this is kind of ridiculous.

You can reproduce as follow:
alter table tstock_txn_temp change qty qty int unsigned ;

Thank you everybody.

Body:
According to the position of clauses, mysql results differently.

SELECT sum(if(bos = 'B', txn_qty*-1, txn_qty)) as qty
FROM tstock_txn
WHERE date_format(txn_date, '%Y%m') >= '201905' and company_id='003490'
union all
SELECT qty as qty FROM tstock_txn_temp WHERE company_id='003490'

result: correct

-290
290

changed query

SELECT qty as qty
FROM tstock_txn_temp
WHERE company_id='003490'
union ALL
SELECT sum(if(bos = 'B', txn_qty*-1, txn_qty)) as qty
FROM tstock_txn
WHERE date_format(txn_date, '%Y%m') >= '201905' and company_id='003490'

result: not correct

290
0

the result should be

290
-290


问:
Unable to execute shell script through php shell_exec
I have a binary file whose path is mentioned in the .bashrc file, I am able to execute it through command line. I copied the command to run the binary file into a bash(test.sh) file.
I am trying to execute this test.sh file through Php using the command

```<code><php
    shell_exec("test.sh")
?>
</code>```

This says that command not found.

答:
Maybe, your webserver configuration forbid execution of system commands.
Check your php.ini "disable_functions" section. If you see there something like below, this is the reason.

```<code>disable_functions=exec,passthru,shell_exec,system
</code>```

I'm trying to execute docker command in that runApp.sh file

Remember, you script executes INSIDE docker container. It doesn't have access to the mother system.
If you want to execute docker commands inside docker container, your need docker in docker

Body:
I have a binary file whose path is mentioned in the .bashrc file, I am able to execute it through command line. I copied the command to run the binary file into a bash(test.sh) file.
I am trying to execute this test.sh file through Php using the command

<php
    shell_exec("test.sh")
?>

This says that command not found.

Body:
Maybe, your webserver configuration forbid execution of system commands.
Check your php.ini "disable_functions" section. If you see there something like below, this is the reason.

disable_functions=exec,passthru,shell_exec,system

I'm trying to execute docker command in that runApp.sh file

Remember, you script executes INSIDE docker container. It doesn't have access to the mother system.
If you want to execute docker commands inside docker container, your need docker in docker


问:
Chrome extension change border-radius and position
How can I add border-radius on chrome extension popup?
Also, can I add something like margin-top to the popup?

答:
Chrome simply doesn't allow that.

Alternatives are, instead of the popup, opening a new window or injecting a content script in the active tab to display a modal.


问:
How do I change a Stripe Subscription's billing cycle date?
When a client subscribes to my service, their billing date is the date they subscribed on and every month on that date going forward. Sometimes, a client will ask if their billing date can be changed.

I've followed Stripe's Billing Cycle documentation but it doesn't work as I need it to (or maybe as expected?). Here's what I'm seeing...

If I update a subscription and set prorate to false and trial_end to a date that is earlier than their next subscription renewal, the subscription date does change, but since the new date is earlier the client is effectively getting charged again for the difference in those days. So if today's the 5th, the current subscription renews on the 15th, and I set the new renewal date to the 10th, the client has already paid for the days between the 10th and the 15th but they get another subscription payment starting on the 10th. Hopefully that makes sense; there's basically an overlap.

The inverse is true too. If the date is changed to a date after their next subscription renewal date, the customer effectively gets free days.

I've tried setting prorate to true but that seems to just completely refund whatever is left on their current subscription entirely, then sets them up with a free trial until the next date - again free days.

答:
I think the only way to do it, is adding a trial period to the subscription. You will need to calculate the days between now and the date the customer wants the payment to come out and add that many days as the trial period.

As part of the change date process, you could force them to pay the prorated amount that they are missing before adding the trial, this will make sure they don't keep doing it to constantly push the payment into the future.


问:
Unpacking index for Central Repository on Netbeans
I'm having a problem using Netbeans 8.2 on my High Sierra Macbook Air. When it opens it does a few startup things that seem to proceed normally, then it pauses for a minute or so, then it says "unpacking index for central repository." And that's where it gets stuck. It never completes that process, even after a few hours of sitting.

Here are some things that may or may not matter, but in case they're important:

At the bottom of Netbeans, to the right of where the updating index message displays, there's a red word bubble with the number 1. The word bubble is there even before unpacking starts. When I click on it, it bring up a notification, but all the notification says is "left button."

I originally downloaded Netbeans a year or two ago for a Java class I was taking. At the time we were using Apache Tomcat for the server. I haven't tried to do anything with Apache recently.

I downloaded Glassfish about 4 months ago. Can't remember whether I was installing a new JDK or not. I had not used Netbeans since the first Java class, but I was taking a new Java class that had me update things. Don't know if I tried connecting to the Glassfish server (is that right?) or not. I didn't use Netbeans after that, though, because I was able to do my assignments on another computer that had Netbeans installed. I think Netbeans had worked at that point, though. I recall being able to bring up some code. Now, however, when I try to open a project, nothing happens.

答:
I recently ran into this problem on CentOS. The root of the problem was that I was running out of disk space on my main drive (default tmp dir location).

To fix, I modified the netbeans/etc/netbeans.conf to specify a new tmp dir location in the netbeans_default_options setting, adding:

-J-Djava.io.tmpdir=/my/new/tmpdir
```

When opening a Maven POM for the first time, NetBeans will pull a file from Maven Central and index it, using the tmp dir. On my machine, this indexing operation used almost 6GB of space, which was larger than I had available at the default java.io.tmpdir location. Specifying a new location on a larger disk resolved the problem.

The error message I received from NetBeans was misleading, because it claimed I did not have enough space in my ~/.cache/netbeans dir to perform the cacheing. Changing the netbeans_default_cachedir in netbeans.conf did not resolve the issue. I had to manually watch for files being written to disk to find the problem and deduce it was the tmp dir running out of space, not the cache dir.

Body:
I recently ran into this problem on CentOS. The root of the problem was that I was running out of disk space on my main drive (default tmp dir location).

To fix, I modified the netbeans/etc/netbeans.conf to specify a new tmp dir location in the netbeans_default_options setting, adding:

-J-Djava.io.tmpdir=/my/new/tmpdir

When opening a Maven POM for the first time, NetBeans will pull a file from Maven Central and index it, using the tmp dir. On my machine, this indexing operation used almost 6GB of space, which was larger than I had available at the default java.io.tmpdir location. Specifying a new location on a larger disk resolved the problem.

The error message I received from NetBeans was misleading, because it claimed I did not have enough space in my ~/.cache/netbeans dir to perform the cacheing. Changing the netbeans_default_cachedir in netbeans.conf did not resolve the issue. I had to manually watch for files being written to disk to find the problem and deduce it was the tmp dir running out of space, not the cache dir.


问:
Custom Route Provider when is not a function
This is an updated version of a question from this morning.

I have two separate modules, 'admin' and 'authorization'. In the provider block of authorization, I extend $routeProvider in order to attach an identical route to all of the route definitions.

First, here is admin.js:

```<code>angular.module('authorization', [])
    .provider('$appRoute', function () {
        this.$get = function($routeProvider) {
            var universalResolves = {authorize: function($authorization) {
                    return $authorization.authorize();
                }};

            var extendedRouter = angular.extend({}, $routeProvider, {
                when: function(path, route) {
                    route.resolve = (route.resolve) ? route.resolve : {};
                    angular.extend(route.resolve, universalResolves);
                    $routeProvider.when(path, route);
                    return this;
                }
            });

            return new extendedRouter();
        }
    })
    .factory('$authorization', ['$http', '$location', function($http, $location) {

        var $authorization = {};

        $authorization.authorize = function() {

            var path = $location.path();

            return promise = $http.get('/svc/authorize/view?urlPath=' + path).then(function(response) {
                var data = response.data;
                if (response.data.result === 'NOT_AUTHORIZED') {
                    throw "NOT_AUTHORIZED";
                }

                return data;
            });

        };

        return $authorization;
    }]);
</code>```

Next, my admin module:

```<code>angular.module('admin', ['ngRoute', 'ngSanitize', 'ngCsv'
        , 'authorization'
    ])

    .controller('mainCtrl', function() {

    })
    .config(['$routeProvider', '$appRouteProvider', function($routeProvider, $appRouteProvider) {

        // old definition that needs to be changed to $appRouteProvider
        $routeProvider.when('/login', {
            templateUrl: '/login/auth.html',
            controller: 'loginCtrl'
        });

        $appRouteProvider.when('/page', {
            templateUrl: 'page.tmpl.html',
            controller: 'pageCtrl'
        });
</code>```

Unfortunately, I get the following error:

```<code>Error: [$injector:modulerr] Failed to instantiate module app due to:
$appRouteProvider.when is not a function
@https://localhost:8443/admin.js:87:9
invoke@https://localhost:8443/js/angular/angular.js:4718:16
runInvokeQueue@https://localhost:8443/js/angular/angular.js:4611:11
loadModules/<@https://localhost:8443/js/angular/angular.js:4620:11
forEach@https://localhost:8443/js/angular/angular.js:321:11
loadModules@https://localhost:8443/js/angular/angular.js:4601:5
loadModules/<@https://localhost:8443/js/angular/angular.js:4618:40
forEach@https://localhost:8443/js/angular/angular.js:321:11
loadModules@https://localhost:8443/js/angular/angular.js:4601:5
createInjector@https://localhost:8443/js/angular/angular.js:4523:19
doBootstrap@https://localhost:8443/js/angular/angular.js:1758:20
bootstrap@https://localhost:8443/js/angular/angular.js:1779:12
angularInit@https://localhost:8443/js/angular/angular.js:1664:5
@https://localhost:8443/js/angular/angular.js:31763:5
j@https://localhost:8443/js/jquery/jquery.min.js:2:29566
g/</k<@https://localhost:8443/js/jquery/jquery.min.js:2:29882
</code>```

So it sees the $appRouteProvider, but only the this.$get() method. Can anyone help?

答:
I ended up going with a simpler solution than extending the route provider.

In my "top-level" module, I modified all routes with the following code:

```<code>angular.module('app'[])
    .run(function($route) {
        var keys = Object.keys($route.routes);
        keys.forEach(function(key) {
            var modifiedRoute = $route.routes[key];

            // if there's already a resolve function defined, don't overwrite it, just add a new one
            modifiedRoute.resolve = key.resolve?key.resolve:{};
            modifiedRoute.resolve.authorize = function($authorization) {
                return $authorization.authorize();
            }

            $route[key] = modifiedRoute;
        });
     });
</code>```

This works because the routes were already defined in the other modules .config() blocks, which executed before the run() block. It's slightly ugly, but it works.

Body:
This is an updated version of a question from this morning.

I have two separate modules, 'admin' and 'authorization'. In the provider block of authorization, I extend $routeProvider in order to attach an identical route to all of the route definitions.

First, here is admin.js:

angular.module('authorization', [])
    .provider('$appRoute', function () {
        this.$get = function($routeProvider) {
            var universalResolves = {authorize: function($authorization) {
                    return $authorization.authorize();
                }};

            var extendedRouter = angular.extend({}, $routeProvider, {
                when: function(path, route) {
                    route.resolve = (route.resolve) ? route.resolve : {};
                    angular.extend(route.resolve, universalResolves);
                    $routeProvider.when(path, route);
                    return this;
                }
            });

            return new extendedRouter();
        }
    })
    .factory('$authorization', ['$http', '$location', function($http, $location) {

        var $authorization = {};

        $authorization.authorize = function() {

            var path = $location.path();

            return promise = $http.get('/svc/authorize/view?urlPath=' + path).then(function(response) {
                var data = response.data;
                if (response.data.result === 'NOT_AUTHORIZED') {
                    throw "NOT_AUTHORIZED";
                }

                return data;
            });

        };

        return $authorization;
    }]);

Next, my admin module:

angular.module('admin', ['ngRoute', 'ngSanitize', 'ngCsv'
        , 'authorization'
    ])

    .controller('mainCtrl', function() {

    })
    .config(['$routeProvider', '$appRouteProvider', function($routeProvider, $appRouteProvider) {

        // old definition that needs to be changed to $appRouteProvider
        $routeProvider.when('/login', {
            templateUrl: '/login/auth.html',
            controller: 'loginCtrl'
        });

        $appRouteProvider.when('/page', {
            templateUrl: 'page.tmpl.html',
            controller: 'pageCtrl'
        });

Unfortunately, I get the following error:

Error: [$injector:modulerr] Failed to instantiate module app due to:
$appRouteProvider.when is not a function
@https://localhost:8443/admin.js:87:9
invoke@https://localhost:8443/js/angular/angular.js:4718:16
runInvokeQueue@https://localhost:8443/js/angular/angular.js:4611:11
loadModules/<@https://localhost:8443/js/angular/angular.js:4620:11
forEach@https://localhost:8443/js/angular/angular.js:321:11
loadModules@https://localhost:8443/js/angular/angular.js:4601:5
loadModules/<@https://localhost:8443/js/angular/angular.js:4618:40
forEach@https://localhost:8443/js/angular/angular.js:321:11
loadModules@https://localhost:8443/js/angular/angular.js:4601:5
createInjector@https://localhost:8443/js/angular/angular.js:4523:19
doBootstrap@https://localhost:8443/js/angular/angular.js:1758:20
bootstrap@https://localhost:8443/js/angular/angular.js:1779:12
angularInit@https://localhost:8443/js/angular/angular.js:1664:5
@https://localhost:8443/js/angular/angular.js:31763:5
j@https://localhost:8443/js/jquery/jquery.min.js:2:29566
g/</k<@https://localhost:8443/js/jquery/jquery.min.js:2:29882

So it sees the $appRouteProvider, but only the this.$get() method. Can anyone help?

Body:
I ended up going with a simpler solution than extending the route provider.

In my "top-level" module, I modified all routes with the following code:

angular.module('app'[])
    .run(function($route) {
        var keys = Object.keys($route.routes);
        keys.forEach(function(key) {
            var modifiedRoute = $route.routes[key];

            // if there's already a resolve function defined, don't overwrite it, just add a new one
            modifiedRoute.resolve = key.resolve?key.resolve:{};
            modifiedRoute.resolve.authorize = function($authorization) {
                return $authorization.authorize();
            }

            $route[key] = modifiedRoute;
        });
     });

This works because the routes were already defined in the other modules .config() blocks, which executed before the run() block. It's slightly ugly, but it works.


问:
How to disable left menu in master detail page in xamarin forms?
I have masterdetail page and there is left menu in it. Its working fine during user is on masterdetail page. But When user move from master detail page to simple content page(that is not part of master detail page), on this content page if he swipe from left to right left menu opens.
How I can disable the left menu on this content page? and why left menu is showing on simple content page while it is not part of the master detail page?</p>

答:
You can only disable the gesture from master details page.

It can be solve by notifying that the current page is not master page:

1)When we are setting the Master details page by

```<code> Detail = new NavigationPage((Page)Activator.CreateInstance(page));
 IsGestureEnabled = true;// always set it true when setting a page to master page
</code>```

2)Use MessagingCenter from MasterDetails Page for notifying that the current page is not a master page:(inside the master page constructor)

```<code>MessagingCenter.Subscribe<string>(this, "DisableGesture", (sender) =>
            {
                if(sender == "0")
                {
                    IsGestureEnabled = false;
                }
                else
                {
                    IsGestureEnabled = true;
                }
            });
</code>```

3)when you navigate from a nornal content page,and you dont want to open the master menu from here then notify the master page IsGestureEnabled = false;

```<code>//content page OnAppearing method
 protected override void OnAppearing()
        {
            MessagingCenter.Send<string>("0", "DisableGesture");
        }
</code>```

do this for all your content page,where you dont want to open master menu.
****and remember that which pages you are setting as master page,for those pages onappearing method send messaging center with value "1"

```<code> protected override void OnAppearing()
        {
            MessagingCenter.Send<string>("1", "DisableGesture");
        }
</code>```

Thanks

Body:
You can only disable the gesture from master details page.

It can be solve by notifying that the current page is not master page:

1)When we are setting the Master details page by

 Detail = new NavigationPage((Page)Activator.CreateInstance(page));
 IsGestureEnabled = true;// always set it true when setting a page to master page

2)Use MessagingCenter from MasterDetails Page for notifying that the current page is not a master page:(inside the master page constructor)

MessagingCenter.Subscribe<string>(this, "DisableGesture", (sender) =>
            {
                if(sender == "0")
                {
                    IsGestureEnabled = false;
                }
                else
                {
                    IsGestureEnabled = true;
                }
            });

3)when you navigate from a nornal content page,and you dont want to open the master menu from here then notify the master page IsGestureEnabled = false;

//content page OnAppearing method
 protected override void OnAppearing()
        {
            MessagingCenter.Send<string>("0", "DisableGesture");
        }

do this for all your content page,where you dont want to open master menu.
****and remember that which pages you are setting as master page,for those pages onappearing method send messaging center with value "1"

 protected override void OnAppearing()
        {
            MessagingCenter.Send<string>("1", "DisableGesture");
        }

Thanks