问:
mysqli_stmt_bind_result(): Number of bind variables doesn't match number of fields in prepared statement in
/the cart table has 4 fields; id, username, product id, image. I am trying show all the data in a table.  </p>

```<code><?php

$query = "SELECT * FROM cart WHERE user_name='$username'";

if ($stmt = mysqli_prepare($mysqli, $query)) {

    /* execute statement */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt,$username);

    /* fetch values */
    while ($row=mysqli_stmt_fetch($stmt))

{
</code>```

答:
I think your call to mysqli_stmt_bind_result() is incorrect. I recommend two things:

enumerate your columns in the text of your SQL statement

pass one PHP variable for each column that you specify.

The way your mysqli_stmt_bind_result() is written, the code will only work if the table has one column, user_name.

Body:
/the cart table has 4 fields; id, username, product id, image. I am trying show all the data in a table.

<?php

$query = "SELECT * FROM cart WHERE user_name='$username'";

if ($stmt = mysqli_prepare($mysqli, $query)) {

    /* execute statement */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt,$username);

    /* fetch values */
    while ($row=mysqli_stmt_fetch($stmt))

{


来源: stackexchange

问:
Insert Multiple Bitmap Image into Multiple Worksheet
In my folder, there is AA.bmp, AA.txt, BB.bmp and BB.txt

I am able to extract the data for AA.txt and BB.txt in a separate worksheet.

Am I also able to insert AA.bmp in the same sheet as AA.txt, and BB.bmp in the same sheet as BB.txt?

```<code>Sub ExtractData()
iPath = "C:\Users\NHWD78\Desktop\Report\Radiated Immunity\"
ifile = Dir(iPath & "*.txt")

Do While Len(ifile)
Sheets.Add , Sheets(Sheets.Count), , iPath & ifile
ifile = Dir
Range("A10:B10, A16:B19").Copy Destination:=Sheets(Sheets.Count).Range("A1")

Application.CutCopyMode = False
Range("A6:K600").Clear
Columns.AutoFit

Loop
End Sub
</code>```

I have search throughout the website but only found a way to insert a fixed image with image name.

答:
Worksheet.Shapes.AddPicture will do it. Example below: -

```<code>Public Sub Sample()
Dim WkBk    As Workbook
Dim WkSht   As Worksheet
Dim Ole     As Object

Set WkBk = ThisWorkbook
    Set WkSht = WkBk.Worksheets(1)
        WkSht.Shapes.AddPicture "C:\Users\garye\Desktop\AA.bmp", msoFalse, msoCTrue, 0, 0, -1, -1
    Set WkSht = Nothing
Set WkBk = Nothing

End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In my folder, there is AA.bmp, AA.txt, BB.bmp and BB.txt

I am able to extract the data for AA.txt and BB.txt in a separate worksheet.

Am I also able to insert AA.bmp in the same sheet as AA.txt, and BB.bmp in the same sheet as BB.txt?

Sub ExtractData()
iPath = "C:\Users\NHWD78\Desktop\Report\Radiated Immunity\"
ifile = Dir(iPath & "*.txt")

Do While Len(ifile)
Sheets.Add , Sheets(Sheets.Count), , iPath & ifile
ifile = Dir
Range("A10:B10, A16:B19").Copy Destination:=Sheets(Sheets.Count).Range("A1")

Application.CutCopyMode = False
Range("A6:K600").Clear
Columns.AutoFit

Loop
End Sub

I have search throughout the website but only found a way to insert a fixed image with image name.

Body:
Worksheet.Shapes.AddPicture will do it. Example below: -

Public Sub Sample()
Dim WkBk    As Workbook
Dim WkSht   As Worksheet
Dim Ole     As Object

Set WkBk = ThisWorkbook
    Set WkSht = WkBk.Worksheets(1)
        WkSht.Shapes.AddPicture "C:\Users\garye\Desktop\AA.bmp", msoFalse, msoCTrue, 0, 0, -1, -1
    Set WkSht = Nothing
Set WkBk = Nothing

End Sub


问:
How can I cover a div with a semi-transparent image?
I want to cover a
 so it looks like it has a semi-transparent block over it.

I am using jQuery but I do not know how to do it.

Any help thanks...

答:
You could use CSS3 to do this. Position a
 absolutely on top of it and give the
 a background of: rgba(255,255,255,.3).

ContentLicense: CC BY-SA 2.5

Body: You could use CSS3 to do this. Position a <div> absolutely on top of it and give the <div> a background of: rgba(255,255,255,.3).


问:
How can i make an auto changing photo?
I'm a real beginner "coder", and I have work, to make an autochanging photo
with a textbox (write xy sec, it will be the time between 2 image)

```<code>        string path = @"C:\Teszt\";
        string[] Files = Directory.GetFiles(path, "*.jpg");
        List<string> fileList = new List<string>();
        foreach (var item in Files)
        {
            fileList.Add(item);
        }
        for (int i = 0; i < fileList.Count; i++)
        {

            string year= "";
            year += DateTime.Now.Year;
            string month = "";
            month += DateTime.Now.Month;
            string day = "";
            day += DateTime.Now.Day;
            //update textbox
            Date.Content = year + "." + month + "." + day + ".";

            string filepath = fileList[i];
            var urii = new Uri(filepath);
            var bitmaap = new BitmapImage(urii);
            image.Source = new BitmapImage(new Uri(fileList[i]));
            Thread.Sleep(TimeSpan.FromSeconds(10));
            if (i == fileList.Count)
                i = 0;
        }
    }
    private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        Thread.Sleep(TimeSpan.FromSeconds(int.Parse(this.TextBox.Text)));
    }
</code>```

答:
One thing you will want to do is split up your code in methods that have a clear, single responsibility. this makes your programs easier to understand

The Date-in-a-textbox code has no business inside that loop

You will need a way to do the waiting until the next picture in the
background, so it will not block your UI thread, still allowing you
to enter text in the textbox.
The dispatcherTimer is a good way to go.

you need to make sure the text in the textbox can be parsed to a number before doing anything

```<code>private List<string> kepek = new List<string>();
private int képnévIndex = 0;
private DispatcherTimer timer;

//this is my stand-in for your constructor. you didn't put it in the example, so i'm using "myClass"
public myClass()
{
    // you will still need InitializeComponent();
    InitializeComponent();

    LoadImages();
    setupTimer(10);
    displayCurrentDate();
}

private void setupTimer(int timeoutInSeconds)
{
    if(timer != null)
    {
        timer.Stop();
    }
    timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(timeoutInSeconds) };

    timer.Tick += (sender, args) =>
    {
         showNextPicture();
    };

    timer.Start();
}

private void LoadImages()
{
    string path = @"C:\Teszt\";
    string[] Files = Directory.GetFiles(path, "*.jpg");

    foreach (var item in Files)
    {
        kepek.Add(item);
    }
}

private void displayCurrentDate()
{
    string év = "";
    év += DateTime.Now.Year;
    string hónap = "";
    hónap += DateTime.Now.Month;
    string nap = "";
    nap += DateTime.Now.Day;
    Date.Content = év + "." + hónap + "." + nap + ".";
}

private void showNextPicture()
{
    string képnév = kepek[képnévIndex];
    image.Source = new BitmapImage(new Uri(képnév));

    képnévIndex++;

    if (képnévIndex == kepek.Count)
        képnévIndex = 0;

}

private void Szövegdoboz_TextChanged(object sender, TextChangedEventArgs e)
{
    int parsedNumberOfSeconds;
    //if we entered something that can not be parsed to a number, exit.
    if(!int.tryParse(Szövegdoboz.Text, out parsedNumberOfSeconds))
        return;

    setupTimer(parsedNumberOfSeconds);
}
</code>```

Title: How can i make an auto changing photo?

Body:
I'm a real beginner "coder", and I have work, to make an autochanging photo
with a textbox (write xy sec, it will be the time between 2 image)

        string path = @"C:\Teszt\";
        string[] Files = Directory.GetFiles(path, "*.jpg");
        List<string> fileList = new List<string>();
        foreach (var item in Files)
        {
            fileList.Add(item);
        }
        for (int i = 0; i < fileList.Count; i++)
        {

            string year= "";
            year += DateTime.Now.Year;
            string month = "";
            month += DateTime.Now.Month;
            string day = "";
            day += DateTime.Now.Day;
            //update textbox
            Date.Content = year + "." + month + "." + day + ".";

            string filepath = fileList[i];
            var urii = new Uri(filepath);
            var bitmaap = new BitmapImage(urii);
            image.Source = new BitmapImage(new Uri(fileList[i]));
            Thread.Sleep(TimeSpan.FromSeconds(10));
            if (i == fileList.Count)
                i = 0;
        }
    }
    private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        Thread.Sleep(TimeSpan.FromSeconds(int.Parse(this.TextBox.Text)));
    }

Body:
One thing you will want to do is split up your code in methods that have a clear, single responsibility. this makes your programs easier to understand

The Date-in-a-textbox code has no business inside that loop

You will need a way to do the waiting until the next picture in the
background, so it will not block your UI thread, still allowing you
to enter text in the textbox.
The dispatcherTimer is a good way to go.

you need to make sure the text in the textbox can be parsed to a number before doing anything

private List<string> kepek = new List<string>();
private int képnévIndex = 0;
private DispatcherTimer timer;

//this is my stand-in for your constructor. you didn't put it in the example, so i'm using "myClass"
public myClass()
{
    // you will still need InitializeComponent();
    InitializeComponent();

    LoadImages();
    setupTimer(10);
    displayCurrentDate();
}

private void setupTimer(int timeoutInSeconds)
{
    if(timer != null)
    {
        timer.Stop();
    }
    timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(timeoutInSeconds) };

    timer.Tick += (sender, args) =>
    {
         showNextPicture();
    };

    timer.Start();
}

private void LoadImages()
{
    string path = @"C:\Teszt\";
    string[] Files = Directory.GetFiles(path, "*.jpg");

    foreach (var item in Files)
    {
        kepek.Add(item);
    }
}

private void displayCurrentDate()
{
    string év = "";
    év += DateTime.Now.Year;
    string hónap = "";
    hónap += DateTime.Now.Month;
    string nap = "";
    nap += DateTime.Now.Day;
    Date.Content = év + "." + hónap + "." + nap + ".";
}

private void showNextPicture()
{
    string képnév = kepek[képnévIndex];
    image.Source = new BitmapImage(new Uri(képnév));

    képnévIndex++;

    if (képnévIndex == kepek.Count)
        képnévIndex = 0;

}

private void Szövegdoboz_TextChanged(object sender, TextChangedEventArgs e)
{
    int parsedNumberOfSeconds;
    //if we entered something that can not be parsed to a number, exit.
    if(!int.tryParse(Szövegdoboz.Text, out parsedNumberOfSeconds))
        return;

    setupTimer(parsedNumberOfSeconds);
}


问:
Fetching content from html and write fetched content in a specific format in CSV
I have HTML Code like:

```<code><!-- Snippet snippets/search_result_text.html end -->
</h2>

      <p class="filter-list">

          <span class="facet">Organisations:</span>

            <span class="filtered pill">**Reserve Bank of Australia**
              <a href="/dataset?groups=business" class="remove" title="Remove"><i class="icon-remove"></i></a>
            </span>

          <span class="facet">Groups:</span>

            <span class="filtered pill">**Business Support and Regulation**
              <a href="/dataset?organization=reservebankofaustralia" class="remove" title="Remove"><i class="icon-remove"></i></a>
            </span>

      </p>

</form>

<!-- Snippet snippets/search_form.html end -->

<!-- Snippet snippets/search_package_list.html start -->

        <ul class="dataset-list unstyled">

<!-- Snippet snippets/package_item.html start -->

<li class="dataset-item">

    <div class="dataset-content">
      <h3 class="dataset-heading">

        <a href="/dataset/banks-assets">**Banks – Assets**</a>

      </h3>

        <div>These data are derived from returns submitted to the Australian Prudential Regulation Authority (APRA) by banks authorised under the Banking Act 1959. APRA assumed...</div>

    </div>

      <ul class="dataset-resources unstyled">

          <li>

            <a href="/dataset/banks-assets" class="label" data-format="xls">XLS</a>

          </li>

      </ul>

</li>
<!-- Snippet snippets/package_item.html end -->

<!-- Snippet snippets/package_item.html start -->

<li class="dataset-item">

    <div class="dataset-content">
      <h3 class="dataset-heading">

        <a href="/dataset/consolidated-exposures-immediate-and-ultimate-risk-basis">**Consolidated Exposures – Immediate and Ultimate Risk Basis**</a>

      </h3>

        <div>In March 2003, banks and selected Registered Financial Corporations (RFCs) began reporting their international assets, liabilities and country exposures to APRA in ARF/RRF 231...</div>

    </div>

      <ul class="dataset-resources unstyled">

          <li>

            <a href="/dataset/consolidated-exposures-immediate-and-ultimate-risk-basis" class="label" data-format="xls">XLS</a>

          </li>

      </ul>

</li>
<!-- Snippet snippets/package_item.html end -->
</code>```

I want to extract data which is in bold letters above and the want to write in csv specific format like:

```<code>Group                               Organisation              Title
Business Support and Regulation    Reserve Bank of Australia   Banks-Assets
Business Support and Regulation    Reserve Bank of Australia   Consolidated Exposures – Immediate and Ultimate Risk Basis
</code>```

and so on....
I have my python code which gives two different files.

```<code>webpage_urls = ["https://data.gov.au/dataset?q=&groups=business&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&organization=reservebankofaustralia&_groups_limit=0",
                "https://data.gov.au/dataset?q=&groups=business&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&organization=department-of-finance&_groups_limit=0",
                "https://data.gov.au/dataset?q=&groups=business&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&organization=departmentofagriculturefisheriesandforestry&_groups_limit=0",
                "https://data.gov.au/dataset?organization=department-of-communications&q=&groups=business&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&_groups_limit=0",
                "https://data.gov.au/dataset?organization=ip-australia&q=&groups=business&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&_groups_limit=0",
                "https://data.gov.au/dataset?q=&organization=australiancommunicationsandmediaauthority&groups=business&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&_groups_limit=0",
                "https://data.gov.au/dataset?q=&organization=www-mitchellshirecouncil-vic-gov-au&groups=business&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&_groups_limit=0",
                "https://data.gov.au/dataset?q=&groups=business&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&organization=digital-transformation-agency&_groups_limit=0"]
# fetching data from all urls
data = []
dfs = []

for i in webpage_urls:
    wiki2 = i
    page= urllib.request.urlopen(wiki2)
    soup = BeautifulSoup(page)

    lobbying = {}
    data2 = soup.find_all('h3', class_="dataset-heading")
    for element in data2:
        lobbying[element.a.get_text()] = {}
    data2[0].a["href"]
    prefix = "https://data.gov.au"
    for element in data2:
        print()
        lobbying[element.a.get_text()]["link"] = prefix + element.a["href"]
        #print(lobbying)
        df = pd.DataFrame.from_dict(lobbying, orient='index').rename_axis('Titles').reset_index()
        dfs.append(df)
df = pd.concat(dfs, ignore_index=True)
df1 = df.drop_duplicates(subset = 'Titles')
print (df1)
df1.to_csv('D:/output2.csv')

for i in webpage_urls:
    wiki2 = i
    page= urllib.request.urlopen(wiki2)
    soup = BeautifulSoup(page)

    # fetching organisations
    data3 = soup.find_all('li', class_="nav-item active")
    lobbying1 = []
    for element in data3:
        lobbying1.append(element.span.get_text())
        data.append(lobbying1)

df_ = pd.DataFrame(data, columns = ['Organisations', 'Groups'])
df2 = df_.drop_duplicates(subset = 'Organisations')
with pd.option_context('display.max_rows', 999):
    print (df2)
df2.to_csv('D:/output_new.csv')
</code>```

above one is giving link also. Please help in in getting desired format in single csv with three columns.

答:
I try a bit modify original solution - best is loop only once and create one big DataFrame with all data. then only select columns with subset [['col1','col2'] for new DataFrames.

Also for remove numbers with () is possible use str.replace:

```<code>for i in webpage_urls:
    wiki2 = i
    page= urllib.request.urlopen(wiki2)
    soup = BeautifulSoup(page, "lxml")

    lobbying = {}
    #always only 2 active li, so select first by [0]  and second by [1]
    org = soup.find_all('li', class_="nav-item active")[0].span.get_text()
    groups = soup.find_all('li', class_="nav-item active")[1].span.get_text()

    data2 = soup.find_all('h3', class_="dataset-heading")
    for element in data2:
        lobbying[element.a.get_text()] = {}
    data2[0].a["href"]
    prefix = "https://data.gov.au"
    for element in data2:
        lobbying[element.a.get_text()]["link"] = prefix + element.a["href"]
        lobbying[element.a.get_text()]["Organisation"] = org
        lobbying[element.a.get_text()]["Group"] = groups
        #print(lobbying)
        df = pd.DataFrame.from_dict(lobbying, orient='index') \
               .rename_axis('Titles').reset_index()
        dfs.append(df)
df = pd.concat(dfs, ignore_index=True)
df1 = df.drop_duplicates(subset = 'Titles').reset_index(drop=True)

df1['Organisation'] = df1['Organisation'].str.replace('\(\d+\)', '')
df1['Group'] = df1['Group'].str.replace('\(\d+\)', '')
</code>```

```<code>print (df1.head())
                                              Titles             Organisation  \
0                                     Banks – Assets  Reserve Bank of Aus...
1  Consolidated Exposures – Immediate and Ultimat...  Reserve Bank of Aus...
2  Foreign Exchange Transactions and Holdings of ...  Reserve Bank of Aus...
3  Finance Companies and General Financiers – Sel...  Reserve Bank of Aus...
4                   Liabilities and Assets – Monthly  Reserve Bank of Aus...

                                                link                    Group
0           https://data.gov.au/dataset/banks-assets  Business Support an...
1  https://data.gov.au/dataset/consolidated-expos...  Business Support an...
2  https://data.gov.au/dataset/foreign-exchange-t...  Business Support an...
3  https://data.gov.au/dataset/finance-companies-...  Business Support an...
4  https://data.gov.au/dataset/liabilities-and-as...  Business Support an...
</code>```

```<code>df2 = df1[['Titles', 'link']]
print (df2.head())
                                              Titles  \
0                                     Banks – Assets
1  Consolidated Exposures – Immediate and Ultimat...
2  Foreign Exchange Transactions and Holdings of ...
3  Finance Companies and General Financiers – Sel...
4                   Liabilities and Assets – Monthly

                                                link
0           https://data.gov.au/dataset/banks-assets
1  https://data.gov.au/dataset/consolidated-expos...
2  https://data.gov.au/dataset/foreign-exchange-t...
3  https://data.gov.au/dataset/finance-companies-...
4  https://data.gov.au/dataset/liabilities-and-as...
</code>```

```<code>df3 = df1[['Group','Organisation','Titles']]
print (df3.head())
                     Group             Organisation  \
0  Business Support an...   Reserve Bank of Aus...
1  Business Support an...   Reserve Bank of Aus...
2  Business Support an...   Reserve Bank of Aus...
3  Business Support an...   Reserve Bank of Aus...
4  Business Support an...   Reserve Bank of Aus...

                                              Titles
0                                     Banks – Assets
1  Consolidated Exposures – Immediate and Ultimat...
2  Foreign Exchange Transactions and Holdings of ...
3  Finance Companies and General Financiers – Sel...
4                   Liabilities and Assets – Monthly
</code>```

Body:
I have HTML Code like:

          Organisations:

            **Reserve Bank of Australia**

          Groups:

            **Business Support and Regulation**

</form>

        **Banks – Assets**

These data are derived from returns submitted to the Australian Prudential Regulation Authority (APRA) by banks authorised under the Banking Act 1959. APRA assumed...

            XLS

        **Consolidated Exposures – Immediate and Ultimate Risk Basis**

In March 2003, banks and selected Registered Financial Corporations (RFCs) began reporting their international assets, liabilities and country exposures to APRA in ARF/RRF 231...

            XLS

I want to extract data which is in bold letters above and the want to write in csv specific format like:

Group                               Organisation              Title
Business Support and Regulation    Reserve Bank of Australia   Banks-Assets
Business Support and Regulation    Reserve Bank of Australia   Consolidated Exposures – Immediate and Ultimate Risk Basis

and so on....
I have my python code which gives two different files.

webpage_urls = ["https://data.gov.au/dataset?q=&groups=business&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&organization=reservebankofaustralia&_groups_limit=0",
                "https://data.gov.au/dataset?q=&groups=business&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&organization=department-of-finance&_groups_limit=0",
                "https://data.gov.au/dataset?q=&groups=business&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&organization=departmentofagriculturefisheriesandforestry&_groups_limit=0",
                "https://data.gov.au/dataset?organization=department-of-communications&q=&groups=business&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&_groups_limit=0",
                "https://data.gov.au/dataset?organization=ip-australia&q=&groups=business&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&_groups_limit=0",
                "https://data.gov.au/dataset?q=&organization=australiancommunicationsandmediaauthority&groups=business&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&_groups_limit=0",
                "https://data.gov.au/dataset?q=&organization=www-mitchellshirecouncil-vic-gov-au&groups=business&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&_groups_limit=0",
                "https://data.gov.au/dataset?q=&groups=business&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&organization=digital-transformation-agency&_groups_limit=0"]
# fetching data from all urls
data = []
dfs = []

for i in webpage_urls:
    wiki2 = i
    page= urllib.request.urlopen(wiki2)
    soup = BeautifulSoup(page)

    lobbying = {}
    data2 = soup.find_all('h3', class_="dataset-heading")
    for element in data2:
        lobbying[element.a.get_text()] = {}
    data2[0].a["href"]
    prefix = "https://data.gov.au"
    for element in data2:
        print()
        lobbying[element.a.get_text()]["link"] = prefix + element.a["href"]
        #print(lobbying)
        df = pd.DataFrame.from_dict(lobbying, orient='index').rename_axis('Titles').reset_index()
        dfs.append(df)
df = pd.concat(dfs, ignore_index=True)
df1 = df.drop_duplicates(subset = 'Titles')
print (df1)
df1.to_csv('D:/output2.csv')

for i in webpage_urls:
    wiki2 = i
    page= urllib.request.urlopen(wiki2)
    soup = BeautifulSoup(page)

    # fetching organisations
    data3 = soup.find_all('li', class_="nav-item active")
    lobbying1 = []
    for element in data3:
        lobbying1.append(element.span.get_text())
        data.append(lobbying1)

df_ = pd.DataFrame(data, columns = ['Organisations', 'Groups'])
df2 = df_.drop_duplicates(subset = 'Organisations')
with pd.option_context('display.max_rows', 999):
    print (df2)
df2.to_csv('D:/output_new.csv')

above one is giving link also. Please help in in getting desired format in single csv with three columns.

Body:
I try a bit modify original solution - best is loop only once and create one big DataFrame with all data. then only select columns with subset [['col1','col2'] for new DataFrames.

Also for remove numbers with () is possible use str.replace:

for i in webpage_urls:
    wiki2 = i
    page= urllib.request.urlopen(wiki2)
    soup = BeautifulSoup(page, "lxml")

    lobbying = {}
    #always only 2 active li, so select first by [0]  and second by [1]
    org = soup.find_all('li', class_="nav-item active")[0].span.get_text()
    groups = soup.find_all('li', class_="nav-item active")[1].span.get_text()

    data2 = soup.find_all('h3', class_="dataset-heading")
    for element in data2:
        lobbying[element.a.get_text()] = {}
    data2[0].a["href"]
    prefix = "https://data.gov.au"
    for element in data2:
        lobbying[element.a.get_text()]["link"] = prefix + element.a["href"]
        lobbying[element.a.get_text()]["Organisation"] = org
        lobbying[element.a.get_text()]["Group"] = groups
        #print(lobbying)
        df = pd.DataFrame.from_dict(lobbying, orient='index') \
               .rename_axis('Titles').reset_index()
        dfs.append(df)
df = pd.concat(dfs, ignore_index=True)
df1 = df.drop_duplicates(subset = 'Titles').reset_index(drop=True)

df1['Organisation'] = df1['Organisation'].str.replace('\(\d+\)', '')
df1['Group'] = df1['Group'].str.replace('\(\d+\)', '')

print (df1.head())
                                              Titles             Organisation  \
0                                     Banks – Assets  Reserve Bank of Aus...
1  Consolidated Exposures – Immediate and Ultimat...  Reserve Bank of Aus...
2  Foreign Exchange Transactions and Holdings of ...  Reserve Bank of Aus...
3  Finance Companies and General Financiers – Sel...  Reserve Bank of Aus...
4                   Liabilities and Assets – Monthly  Reserve Bank of Aus...

                                                link                    Group
0           https://data.gov.au/dataset/banks-assets  Business Support an...
1  https://data.gov.au/dataset/consolidated-expos...  Business Support an...
2  https://data.gov.au/dataset/foreign-exchange-t...  Business Support an...
3  https://data.gov.au/dataset/finance-companies-...  Business Support an...
4  https://data.gov.au/dataset/liabilities-and-as...  Business Support an...

df2 = df1[['Titles', 'link']]
print (df2.head())
                                              Titles  \
0                                     Banks – Assets
1  Consolidated Exposures – Immediate and Ultimat...
2  Foreign Exchange Transactions and Holdings of ...
3  Finance Companies and General Financiers – Sel...
4                   Liabilities and Assets – Monthly

                                                link
0           https://data.gov.au/dataset/banks-assets
1  https://data.gov.au/dataset/consolidated-expos...
2  https://data.gov.au/dataset/foreign-exchange-t...
3  https://data.gov.au/dataset/finance-companies-...
4  https://data.gov.au/dataset/liabilities-and-as...

df3 = df1[['Group','Organisation','Titles']]
print (df3.head())
                     Group             Organisation  \
0  Business Support an...   Reserve Bank of Aus...
1  Business Support an...   Reserve Bank of Aus...
2  Business Support an...   Reserve Bank of Aus...
3  Business Support an...   Reserve Bank of Aus...
4  Business Support an...   Reserve Bank of Aus...

                                              Titles
0                                     Banks – Assets
1  Consolidated Exposures – Immediate and Ultimat...
2  Foreign Exchange Transactions and Holdings of ...
3  Finance Companies and General Financiers – Sel...
4                   Liabilities and Assets – Monthly


问:
Youtube video with hyphen not working in IOS
I am using Cordova YoutubeVideoPlayer Plugin in my ionic project. It works well in android.But in IOS, it is not working with video id having a hyphen(-) in it(eg: "6L-ZHjUhcQY"). It works fine with all other urls. How can I solve this. </p>

```<code>.controller('menuController', function () {
    var id = "6L-ZHjUhcQY";
    YoutubeVideoPlayer.openVideo(id);
});
</code>```

答:
android issue also fixed by editing code in YoutubeVideoPlayer.java file in plugin</p>

```<code>private Intent createYoutubeIntent(String videoId) {
//  if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){
        Intent intent;
        Context cordovaContext = cordova.getActivity();
        String version = YouTubeIntents.getInstalledYouTubeVersionName(cordovaContext);
        if(version != null && version.startsWith("11.16") && YouTubeIntents.canResolvePlayVideoIntent(cordovaContext)) {
            intent = YouTubeIntents.createPlayVideoIntent(cordovaContext, videoId);
        } else {
            if(YouTubeIntents.canResolvePlayVideoIntentWithOptions(cordovaContext)){
                intent = YouTubeIntents.createPlayVideoIntentWithOptions(cordovaContext, videoId, true, true);
            } else {
                intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=" + videoId), cordovaContext, YouTubeActivity.class);
                intent.putExtra("videoId", videoId);
                ConfigXmlParser parser = new ConfigXmlParser();
                parser.parse(cordovaContext);
                CordovaPreferences prefs = parser.getPreferences();
                intent.putExtra("YouTubeApiId", prefs.getString("YouTubeDataApiKey","YOUTUBE_API_KEY"));
            }
        }
        return intent;
//  }

    //return new Intent(null, Uri.parse("ytv://" + videoId), cordova.getActivity(), OpenYouTubePlayerActivity.class);
}
</code>```

Body:
I am using Cordova YoutubeVideoPlayer Plugin in my ionic project. It works well in android.But in IOS, it is not working with video id having a hyphen(-) in it(eg: "6L-ZHjUhcQY"). It works fine with all other urls. How can I solve this.

.controller('menuController', function () {
    var id = "6L-ZHjUhcQY";
    YoutubeVideoPlayer.openVideo(id);
});

Body:
android issue also fixed by editing code in YoutubeVideoPlayer.java file in plugin

private Intent createYoutubeIntent(String videoId) {
//  if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){
        Intent intent;
        Context cordovaContext = cordova.getActivity();
        String version = YouTubeIntents.getInstalledYouTubeVersionName(cordovaContext);
        if(version != null && version.startsWith("11.16") && YouTubeIntents.canResolvePlayVideoIntent(cordovaContext)) {
            intent = YouTubeIntents.createPlayVideoIntent(cordovaContext, videoId);
        } else {
            if(YouTubeIntents.canResolvePlayVideoIntentWithOptions(cordovaContext)){
                intent = YouTubeIntents.createPlayVideoIntentWithOptions(cordovaContext, videoId, true, true);
            } else {
                intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=" + videoId), cordovaContext, YouTubeActivity.class);
                intent.putExtra("videoId", videoId);
                ConfigXmlParser parser = new ConfigXmlParser();
                parser.parse(cordovaContext);
                CordovaPreferences prefs = parser.getPreferences();
                intent.putExtra("YouTubeApiId", prefs.getString("YouTubeDataApiKey","YOUTUBE_API_KEY"));
            }
        }
        return intent;
//  }

    //return new Intent(null, Uri.parse("ytv://" + videoId), cordova.getActivity(), OpenYouTubePlayerActivity.class);
}


问:
Is using __cplusplus undefined behaviour in C?
Modern C++ compilers are required by the standard to #define the macro __cplusplus.

This is often used in files that can be used by both C and C++ but the implementation differs slightly.

But in C (and C++ for that matter), the behaviour on using any double underscore in an identifier is undefined!

So therefore, if a C compiler sees something like

#ifdef __cplusplus

then is the behaviour undefined?

答:
No, there's no undefined behaviour in this case.  Undefined behaviour means the compiler makers are free of doing whatever they want with the affected resources.  This means you are free (in this context) to define new non clashing underscored identifiers to be accepted in the two languages the compiler is able to implement.  Think that the internals of the standard libraries implementations of compiler libraries can be full of such undefined behaviours as far as the compiler behaves correctly in the defined behaviour part.  In the case commented, the macro __cplusplus is defined ONLY in C++ (by the compiler itself), and it is as a preprocessor flag to indicate that you are compiling a c++ source.  Putting it between the #ifndef __cplusplus and the following #endif statements, makes it to exclude for compilation the in between code (normally, because it would lead to a syntactic error or an unsupported feature).  Normally, you will find the following construct in some/many C/C++ standard headers in your system (so they can be used in both C and C++):

```<code>#ifndef __cplusplus
extern "C" {
#endif
...
#ifndef __cplusplus
}
#endif
</code>```

to avoid the extern "C" {} construct, which is C++ specific, and would raise a compiler error in plain C.

NOTE

of course, if you #define __cplusplus before including any of these files, you'll get your C compiler shouting at you about bad syntax on including such a header file.  You can try this yourself to see how it happens:

pru.c

```<code>#define __cplusplus 20170301
#include <stdio.h>
int main()
{
    printf("Hello, world!\n");
} /* main */
</code>```

and then compilation of this gives:

```<code>$ make pru
cc -O -pipe  pru.c  -o pru
In file included from pru.c:2:
/usr/include/stdio.h:159:1: error: expected identifier or '('
__BEGIN_DECLS
^
/usr/include/sys/cdefs.h:59:30: note: expanded from macro '__BEGIN_DECLS'
#define __BEGIN_DECLS   extern "C" {
                               ^
In file included from pru.c:2:
/usr/include/stdio.h:235:1: error: expected identifier or '('
__BEGIN_DECLS
^
/usr/include/sys/cdefs.h:59:30: note: expanded from macro '__BEGIN_DECLS'
#define __BEGIN_DECLS   extern "C" {
                               ^
pru.c:6:2: warning: implicitly declaring library function 'printf' with type 'int (const char *, ...)' [-Wimplicit-function-declaration]
        printf("Hello, world!\n");
        ^
pru.c:6:2: note: include the header <stdio.h> or explicitly provide a declaration for 'printf'
1 warning and 3 errors generated.
*** Error code 1

Stop.
make: stopped in /home/user
</code>```

Think that you are never going to move the standard header files to another computer to compile your source code.  Should you try this, then you would have undefined behaviour, but never while respecting the compiler implementation.  This means, you have to accept the compiler makers to use those undefined behaviour things that result in compiler implementation details, but you cannot do that in your code (at least if you don't want to fail into your program doing nasty things)

Body:
No, there's no undefined behaviour in this case.  Undefined behaviour means the compiler makers are free of doing whatever they want with the affected resources.  This means you are free (in this context) to define new non clashing underscored identifiers to be accepted in the two languages the compiler is able to implement.  Think that the internals of the standard libraries implementations of compiler libraries can be full of such undefined behaviours as far as the compiler behaves correctly in the defined behaviour part.  In the case commented, the macro __cplusplus is defined ONLY in C++ (by the compiler itself), and it is as a preprocessor flag to indicate that you are compiling a c++ source.  Putting it between the #ifndef __cplusplus and the following #endif statements, makes it to exclude for compilation the in between code (normally, because it would lead to a syntactic error or an unsupported feature).  Normally, you will find the following construct in some/many C/C++ standard headers in your system (so they can be used in both C and C++):

#ifndef __cplusplus
extern "C" {
#endif
...
#ifndef __cplusplus
}
#endif

to avoid the extern "C" {} construct, which is C++ specific, and would raise a compiler error in plain C.

NOTE

of course, if you #define __cplusplus before including any of these files, you'll get your C compiler shouting at you about bad syntax on including such a header file.  You can try this yourself to see how it happens:

pru.c

#define __cplusplus 20170301
#include <stdio.h>
int main()
{
    printf("Hello, world!\n");
} /* main */

and then compilation of this gives:

$ make pru
cc -O -pipe  pru.c  -o pru
In file included from pru.c:2:
/usr/include/stdio.h:159:1: error: expected identifier or '('
__BEGIN_DECLS
^
/usr/include/sys/cdefs.h:59:30: note: expanded from macro '__BEGIN_DECLS'
#define __BEGIN_DECLS   extern "C" {
                               ^
In file included from pru.c:2:
/usr/include/stdio.h:235:1: error: expected identifier or '('
__BEGIN_DECLS
^
/usr/include/sys/cdefs.h:59:30: note: expanded from macro '__BEGIN_DECLS'
#define __BEGIN_DECLS   extern "C" {
                               ^
pru.c:6:2: warning: implicitly declaring library function 'printf' with type 'int (const char *, ...)' [-Wimplicit-function-declaration]
        printf("Hello, world!\n");
        ^
pru.c:6:2: note: include the header <stdio.h> or explicitly provide a declaration for 'printf'
1 warning and 3 errors generated.
*** Error code 1

Stop.
make: stopped in /home/user

Think that you are never going to move the standard header files to another computer to compile your source code.  Should you try this, then you would have undefined behaviour, but never while respecting the compiler implementation.  This means, you have to accept the compiler makers to use those undefined behaviour things that result in compiler implementation details, but you cannot do that in your code (at least if you don't want to fail into your program doing nasty things)


问:
How to take a sample in R such that the original proportion remains the same
i want a sample from a data such that the original proportion of the variables remains the same. For example if in my original data, there were 1000 values of which there were 100 values of a, 800 values of b, and 100 values of c. if i am to take a sample of say 100 values from this original data, it should have 10 values of a, 80 values of b and 10 values of c. Please help!</p>

答:
The tidyverse package(s) have some nice functions that help with this.

```<code>library(tidyverse)

data <- tibble(Group = c(rep("a", 100), rep ("b", 800), rep("c", 100)),
               Value = runif(1000))

sampledData <- data %>%
  group_by(Group) %>%
  sample_frac(0.1)
</code>```

We create a very simple example of your dataset, with random uniform values and 3 groups, 100 from a, 800 from b and 100 from c.

Using the function group_by we group the data on that group variable, so that when we use the function sample_frac, the function is executed on all groups separately.

We can check this with table:

```<code>> table(sampledData$Group)

 a  b  c
10 80 10
</code>```

Note:

This answer uses the tidyverse pipe operator %>%, this is equivalent to:

```<code>sampledData <- sample_frac(group_by(data, Group), 0.1)
</code>```

Body:
The tidyverse package(s) have some nice functions that help with this.

library(tidyverse)

data <- tibble(Group = c(rep("a", 100), rep ("b", 800), rep("c", 100)),
               Value = runif(1000))

sampledData <- data %>%
  group_by(Group) %>%
  sample_frac(0.1)

We create a very simple example of your dataset, with random uniform values and 3 groups, 100 from a, 800 from b and 100 from c.

Using the function group_by we group the data on that group variable, so that when we use the function sample_frac, the function is executed on all groups separately.

We can check this with table:

> table(sampledData$Group)

 a  b  c
10 80 10

Note:

This answer uses the tidyverse pipe operator %>%, this is equivalent to:

sampledData <- sample_frac(group_by(data, Group), 0.1)


问:
Is it possible to extend (Override) git command?
Is it possible to override git command or run another git commands before calling its alias. Like so: git checkout . -> git stash && git stash apply && git checkout .. After accidental checkout i think about it

答:
I added a shortcut for checkout : alias.co = checkout, and am now so used to type it that I get surprised when I use a machine without the shortcut.

You could plug your command on such a shortcut.

A word on git stash : another way to create such a stash :

```<code>git stash store $(git stash create)
</code>```

This has the advantage of not modifying the files on disk (and possibly triggering some actions watching for files modification ...)

(store and create are mentionned in git help stash)

Body:
I added a shortcut for checkout : alias.co = checkout, and am now so used to type it that I get surprised when I use a machine without the shortcut.

You could plug your command on such a shortcut.

A word on git stash : another way to create such a stash :

git stash store $(git stash create)

This has the advantage of not modifying the files on disk (and possibly triggering some actions watching for files modification ...)

(store and create are mentionned in git help stash)


问:
How does akka compare to Erlang?
I've been looking at akka recently and it's pretty impressive. It looks like it has most of the killer features of erlang - location transparency, supervision hierarchies, and more. Are there any features erlang has that akka doesn't?</p>

答:
Disclaimer: I am the PO for Akka

Erlang does copy-on-send - Akka uses
shared memory (immutable objects) for
in-VM sends

Erlang does per-process GC - Akka uses JVM GCs

Erlang has OTP - Akka integrates with the entire Java ecosystem (Apache Camel, JAX-RS,
etc etc)

Erlang does the process
scheduling for you - Akka allows you
to use many different Dispatchers
with endless configuration
opportunities

Erlang does hot code
reload - Akka can support it, but
it's less flexible because of JVM
classloading

Those are the ones from the top of my head.

On the other hand, using Akka means that you can use Scala, Java, Groovy or JRuby to write your applications.

Title: How does akka compare to Erlang?


问:
Issues with rendering in Android ListView in Visual Studio Xamarin
Hello to all programmers. I try to create simple chat. The first chatter's messages should be in white square with rounded corners, the second chatter's messages should be in blue square with rounded corners and with some icon. So I decided to use listview and adapter for this task. In adapter I use simple set of data {bool type, sting message, DateTime date}. So Adapter Code is

```<code>class ChatMessagesViewHolder : Java.Lang.Object
{
    internal TextView chatMessageView;
    public void initialize(View view){}
}
public class ChatMessagesAdapter : BaseAdapter
{
    Activity _context;
    List<MessageData> _dataList;

    public ChatMessagesAdapter(Activity context, List<MessageData> dataList)
    {
        _context = context;
        _dataList = dataList;
    }
    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        ChatMessagesViewHolder chatMessagesViewHolderClass;
        View view;
        view = convertView;
        int layout = _dataList[position]._type == 0 ? Resource.Layout.MessageLitsUserItem:Resource.Layout.MessageListWorkerItem;
        Typeface openSansRegular = Typeface.CreateFromAsset(_context.Assets, "fonts/OpenSans-Regular.ttf");
        if (view == null)
        {
            view = _context.LayoutInflater.Inflate(layout, parent, false);
            chatMessagesViewHolderClass = new ChatMessagesViewHolder();
            chatMessagesViewHolderClass.chatMessageView = view.FindViewById<TextView>(Resource.Id.messageText);
            chatMessagesViewHolderClass.initialize(view);
            view.Tag = chatMessagesViewHolderClass;
        }
        else
        {
            chatMessagesViewHolderClass = (ChatMessagesViewHolder)view.Tag;
        }
        chatMessagesViewHolderClass.chatMessageView.Typeface = openSansRegular;
        chatMessagesViewHolderClass.chatMessageView.Text = _dataList[position]._date.ToString()+"\n"+ _dataList[position]._message;
        return view;
    }
    public void Add(MessageData messageData)
    {
        _dataList.Add(messageData);
    }
}
</code>```

In Activity I fill Adapter with test information that way - message from 1-st chatter, message from 2-nd chatter. It repeats 10 times.

```<code>public class ChatActivity : Activity{
    ListView chatList;
    ChatMessagesAdapter chatAdapter;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.ChatLayout);
        List<MessageData> dataList = new List<MessageData>();
        for (int i = 0; i < 20; i++)
        {
            string message = "Test message from chatter "+(i%2).ToString();
            dataList.Add(new MessageData(i % 2, message, DateTime.Now));
        }
        chatAdapter = new ChatMessagesAdapter(this, dataList);
        chatList.Adapter = chatAdapter;
    }
}
</code>```

When I run app (in Visual studio emulator for android) first rendering of list is correct, but when I scroll list up/down, the layouts of ListView mixes - 1-st chatter's message sometimes get 2-nd chatter's template (with blue square and icon), 2-nd chatter's message sometimes get 1-st chatter's template (with white square and no icon).
For Example

Can anybody help me with this issue? Any help will be appreciated.

UPDATED

New code of Adapter, updated to work with two different ViewHolders for different type of messages.

```<code>class ChatUserMessagesViewHolder : Java.Lang.Object
{
    internal RelativeLayout messageBox;
    internal TextView messageText;
    public void initialize(View view) { }
}
class ChatWorkerMessagesViewHolder : Java.Lang.Object
{
    internal RelativeLayout messageBox;
    internal TextView messageText;
    internal ImageView workerIcon;
    public void initialize(View view) { }
}
public class ChatMessagesAdapter : BaseAdapter
{
    Activity _context;
    List<MessageData> _dataList;

    public ChatMessagesAdapter(Activity context, List<MessageData> dataList)
    {
        _context = context;
        _dataList = dataList;
    }
    public override Java.Lang.Object GetItem(int position)
    {
        return position;
    }
    public override long GetItemId(int position)
    {
        return position;
    }
    public override int Count
    {
        get
        {
            return _dataList.Count;
        }
    }
    public override int GetItemViewType(int position)
    {
        return _dataList[position]._type;
    }
    public override int ViewTypeCount
    {
        get
        {
            return 2;
        }
    }
    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        ChatMessagesViewHolder chatMessagesViewHolderClass;
        ChatWorkerMessagesViewHolder chatWorkerMessagesViewHolderClass;
        ChatUserMessagesViewHolder chatUserMessagesViewHolderClass;
        View view;
        view = convertView;
        int layout = _dataList[position]._type == 0 ? Resource.Layout.MessageLitsUserItem:Resource.Layout.MessageListWorkerItem;
        Typeface openSansRegular = Typeface.CreateFromAsset(_context.Assets, "fonts/OpenSans-Regular.ttf");
        if (view == null)
        {
            switch (GetItemViewType(position))
            {
                case 0:
                    view = _context.LayoutInflater.Inflate(Resource.Layout.MessageLitsUserItem, null);
                    chatUserMessagesViewHolderClass = new ChatUserMessagesViewHolder();
                    chatUserMessagesViewHolderClass.messageBox = view.FindViewById<RelativeLayout>(Resource.Id.messageBox);
                    chatUserMessagesViewHolderClass.messageText = view.FindViewById<TextView>(Resource.Id.messageText);
                    chatUserMessagesViewHolderClass.messageText.Typeface = openSansRegular;
                    chatUserMessagesViewHolderClass.messageText.Text = _dataList[position]._date.ToString() + "\n" + _dataList[position]._message;
                    view.Tag = chatUserMessagesViewHolderClass;
                    break;
                case 1:
                    view = _context.LayoutInflater.Inflate(Resource.Layout.MessageListWorkerItem, null);
                    chatWorkerMessagesViewHolderClass = new ChatWorkerMessagesViewHolder();
                    chatWorkerMessagesViewHolderClass.messageBox = view.FindViewById<RelativeLayout>(Resource.Id.messageBox);
                    chatWorkerMessagesViewHolderClass.messageText = view.FindViewById<TextView>(Resource.Id.messageText);
                    chatWorkerMessagesViewHolderClass.workerIcon = view.FindViewById<ImageView>(Resource.Id.workerIcon);
                    chatWorkerMessagesViewHolderClass.messageText.Typeface = openSansRegular;
                    chatWorkerMessagesViewHolderClass.messageText.Text = _dataList[position]._date.ToString() + "\n" + _dataList[position]._message;
                    break;
            }
        }
        else
        {
            switch (GetItemViewType(position))
            {
                case 0:
                    chatUserMessagesViewHolderClass = (ChatUserMessagesViewHolder)view.Tag;
                    chatUserMessagesViewHolderClass.messageText.Typeface = openSansRegular;
                    chatUserMessagesViewHolderClass.messageText.Text = _dataList[position]._date.ToString() + "\n" + _dataList[position]._message;
                    break;
                case 1:
                    chatWorkerMessagesViewHolderClass = (ChatWorkerMessagesViewHolder)view.Tag;
                    chatWorkerMessagesViewHolderClass.messageText.Typeface = openSansRegular;
                    chatWorkerMessagesViewHolderClass.messageText.Text = _dataList[position]._date.ToString() + "\n" + _dataList[position]._message;
                    break;
            }
        }
        return view;
    }

    public void Add(MessageData messageData)
    {
        _dataList.Add(messageData);
    }
}
</code>```

答:
This behaviour happens because of a mechanism called view recycling, which basically reuses an existing list view item if it is no longer visible (which usually happens when is it scrolled outside of the screen, hence your behaviour only when scroll is made).

```<code> chatMessagesViewHolderClass.chatMessageView.Typeface = openSansRegular;
 chatMessagesViewHolderClass.chatMessageView.Text = _dataList[position]._date.ToString()+"\n"+ _dataList[position]._message;
</code>```

In the above code you set the data for you list, but you ignore completely how the row should be generated.

To fix the problem you have to implement in your adapter getItemViewType in order to let it know that you have more than one layout. I can't help you with any C# code,  but here you can find an example how to use that in Java.

Body:
Hello to all programmers. I try to create simple chat. The first chatter's messages should be in white square with rounded corners, the second chatter's messages should be in blue square with rounded corners and with some icon. So I decided to use listview and adapter for this task. In adapter I use simple set of data {bool type, sting message, DateTime date}. So Adapter Code is

class ChatMessagesViewHolder : Java.Lang.Object
{
    internal TextView chatMessageView;
    public void initialize(View view){}
}
public class ChatMessagesAdapter : BaseAdapter
{
    Activity _context;
    List<MessageData> _dataList;

    public ChatMessagesAdapter(Activity context, List<MessageData> dataList)
    {
        _context = context;
        _dataList = dataList;
    }
    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        ChatMessagesViewHolder chatMessagesViewHolderClass;
        View view;
        view = convertView;
        int layout = _dataList[position]._type == 0 ? Resource.Layout.MessageLitsUserItem:Resource.Layout.MessageListWorkerItem;
        Typeface openSansRegular = Typeface.CreateFromAsset(_context.Assets, "fonts/OpenSans-Regular.ttf");
        if (view == null)
        {
            view = _context.LayoutInflater.Inflate(layout, parent, false);
            chatMessagesViewHolderClass = new ChatMessagesViewHolder();
            chatMessagesViewHolderClass.chatMessageView = view.FindViewById<TextView>(Resource.Id.messageText);
            chatMessagesViewHolderClass.initialize(view);
            view.Tag = chatMessagesViewHolderClass;
        }
        else
        {
            chatMessagesViewHolderClass = (ChatMessagesViewHolder)view.Tag;
        }
        chatMessagesViewHolderClass.chatMessageView.Typeface = openSansRegular;
        chatMessagesViewHolderClass.chatMessageView.Text = _dataList[position]._date.ToString()+"\n"+ _dataList[position]._message;
        return view;
    }
    public void Add(MessageData messageData)
    {
        _dataList.Add(messageData);
    }
}

In Activity I fill Adapter with test information that way - message from 1-st chatter, message from 2-nd chatter. It repeats 10 times.

public class ChatActivity : Activity{
    ListView chatList;
    ChatMessagesAdapter chatAdapter;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.ChatLayout);
        List<MessageData> dataList = new List<MessageData>();
        for (int i = 0; i < 20; i++)
        {
            string message = "Test message from chatter "+(i%2).ToString();
            dataList.Add(new MessageData(i % 2, message, DateTime.Now));
        }
        chatAdapter = new ChatMessagesAdapter(this, dataList);
        chatList.Adapter = chatAdapter;
    }
}

When I run app (in Visual studio emulator for android) first rendering of list is correct, but when I scroll list up/down, the layouts of ListView mixes - 1-st chatter's message sometimes get 2-nd chatter's template (with blue square and icon), 2-nd chatter's message sometimes get 1-st chatter's template (with white square and no icon).
For Example

Can anybody help me with this issue? Any help will be appreciated.

UPDATED

New code of Adapter, updated to work with two different ViewHolders for different type of messages.

class ChatUserMessagesViewHolder : Java.Lang.Object
{
    internal RelativeLayout messageBox;
    internal TextView messageText;
    public void initialize(View view) { }
}
class ChatWorkerMessagesViewHolder : Java.Lang.Object
{
    internal RelativeLayout messageBox;
    internal TextView messageText;
    internal ImageView workerIcon;
    public void initialize(View view) { }
}
public class ChatMessagesAdapter : BaseAdapter
{
    Activity _context;
    List<MessageData> _dataList;

    public ChatMessagesAdapter(Activity context, List<MessageData> dataList)
    {
        _context = context;
        _dataList = dataList;
    }
    public override Java.Lang.Object GetItem(int position)
    {
        return position;
    }
    public override long GetItemId(int position)
    {
        return position;
    }
    public override int Count
    {
        get
        {
            return _dataList.Count;
        }
    }
    public override int GetItemViewType(int position)
    {
        return _dataList[position]._type;
    }
    public override int ViewTypeCount
    {
        get
        {
            return 2;
        }
    }
    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        ChatMessagesViewHolder chatMessagesViewHolderClass;
        ChatWorkerMessagesViewHolder chatWorkerMessagesViewHolderClass;
        ChatUserMessagesViewHolder chatUserMessagesViewHolderClass;
        View view;
        view = convertView;
        int layout = _dataList[position]._type == 0 ? Resource.Layout.MessageLitsUserItem:Resource.Layout.MessageListWorkerItem;
        Typeface openSansRegular = Typeface.CreateFromAsset(_context.Assets, "fonts/OpenSans-Regular.ttf");
        if (view == null)
        {
            switch (GetItemViewType(position))
            {
                case 0:
                    view = _context.LayoutInflater.Inflate(Resource.Layout.MessageLitsUserItem, null);
                    chatUserMessagesViewHolderClass = new ChatUserMessagesViewHolder();
                    chatUserMessagesViewHolderClass.messageBox = view.FindViewById<RelativeLayout>(Resource.Id.messageBox);
                    chatUserMessagesViewHolderClass.messageText = view.FindViewById<TextView>(Resource.Id.messageText);
                    chatUserMessagesViewHolderClass.messageText.Typeface = openSansRegular;
                    chatUserMessagesViewHolderClass.messageText.Text = _dataList[position]._date.ToString() + "\n" + _dataList[position]._message;
                    view.Tag = chatUserMessagesViewHolderClass;
                    break;
                case 1:
                    view = _context.LayoutInflater.Inflate(Resource.Layout.MessageListWorkerItem, null);
                    chatWorkerMessagesViewHolderClass = new ChatWorkerMessagesViewHolder();
                    chatWorkerMessagesViewHolderClass.messageBox = view.FindViewById<RelativeLayout>(Resource.Id.messageBox);
                    chatWorkerMessagesViewHolderClass.messageText = view.FindViewById<TextView>(Resource.Id.messageText);
                    chatWorkerMessagesViewHolderClass.workerIcon = view.FindViewById<ImageView>(Resource.Id.workerIcon);
                    chatWorkerMessagesViewHolderClass.messageText.Typeface = openSansRegular;
                    chatWorkerMessagesViewHolderClass.messageText.Text = _dataList[position]._date.ToString() + "\n" + _dataList[position]._message;
                    break;
            }
        }
        else
        {
            switch (GetItemViewType(position))
            {
                case 0:
                    chatUserMessagesViewHolderClass = (ChatUserMessagesViewHolder)view.Tag;
                    chatUserMessagesViewHolderClass.messageText.Typeface = openSansRegular;
                    chatUserMessagesViewHolderClass.messageText.Text = _dataList[position]._date.ToString() + "\n" + _dataList[position]._message;
                    break;
                case 1:
                    chatWorkerMessagesViewHolderClass = (ChatWorkerMessagesViewHolder)view.Tag;
                    chatWorkerMessagesViewHolderClass.messageText.Typeface = openSansRegular;
                    chatWorkerMessagesViewHolderClass.messageText.Text = _dataList[position]._date.ToString() + "\n" + _dataList[position]._message;
                    break;
            }
        }
        return view;
    }

    public void Add(MessageData messageData)
    {
        _dataList.Add(messageData);
    }
}

Body:
This behaviour happens because of a mechanism called view recycling, which basically reuses an existing list view item if it is no longer visible (which usually happens when is it scrolled outside of the screen, hence your behaviour only when scroll is made).

 chatMessagesViewHolderClass.chatMessageView.Typeface = openSansRegular;
 chatMessagesViewHolderClass.chatMessageView.Text = _dataList[position]._date.ToString()+"\n"+ _dataList[position]._message;

In the above code you set the data for you list, but you ignore completely how the row should be generated.

To fix the problem you have to implement in your adapter getItemViewType in order to let it know that you have more than one layout. I can't help you with any C# code,  but here you can find an example how to use that in Java.


问:
How to deal with page breaks when printing a large HTML table
I have a project which requires printing an HTML table with many rows.

My problem is the way the table is printed over multiple page. It will sometimes cut a row in half, making it unreadable because one half is on the bleeding edge of a page and the remainder is printed on the top of the next page.

The only plausible solution I can think of is using stacked DIVs instead of a table and force page-breaks if needed.. but before going through the whole change I thought I could ask here before.

答:
Well Guys... Most of the Solutions up here didn't worked for. So this is how things worked for me..

HTML

```<code><table>
  <thead>
   <tr>
     <th style="border:none;height:26px;"></th>
     <th style="border:none;height:26px;"></th>
     .
     .
   </tr>
   <tr>
     <th style="border:1px solid black">ABC</th>
     <th style="border:1px solid black">ABC</th>
     .
     .
   <tr>
  </thead>
<tbody>

    //YOUR CODE

</tbody>
</table>
</code>```

The first set of head is used as a dummy one so that there won't be a missing top border in 2nd head(i.e. original head) while page break.

Body:
Well Guys... Most of the Solutions up here didn't worked for. So this is how things worked for me..

HTML

<table>
  <thead>
   <tr>
     <th style="border:none;height:26px;"></th>
     <th style="border:none;height:26px;"></th>
     .
     .
   </tr>
   <tr>
     <th style="border:1px solid black">ABC</th>
     <th style="border:1px solid black">ABC</th>
     .
     .
   <tr>
  </thead>
<tbody>

    //YOUR CODE

</tbody>
</table>

The first set of head is used as a dummy one so that there won't be a missing top border in 2nd head(i.e. original head) while page break.


问:
Google Analytics shows events in "Realtime" Section, but does not show anything under reporting
While the event I am sending (with the API, not with analytics.js) is shown in the realtime section, it does not show up in the reporting area.

I was waiting a few days; pageViews that are reported the same way are well listed in reporting.

Here is a sample Request:

https://www.google-analytics.com/collect?v=1&tid=UA-XXXXXXX-X&ds=oo&t=event&ea=testaction&ec=testcat&el=testlabel

答: You are missing the &cid parameter (client ID). This is a required parameter. For a list of which parameters are required, check this.


问:
php correct json numbers and strings encoding
I have a problem with encoding php array to json. Part of my data are stings like '555', '3M', part of data are numbers: floats or integers. On frontend I need to receive strings as strings and numbers as numbers as numbers for correct sorting, searching , etc. Php has a JSON_NUMERIC_CHECK, but this will convert my sting '555' value into number. Is there any approach except first converting strings like strings, then numbers with  JSON_NUMERIC_CHECK option and then concatenating result?

答:
```<code>$a = json_encode(['555', '3M', 123, 1.2, 1.3]);
var_dump($a);//outputs string(24) "["555","3M",123,1.2,1.3]"
</code>```

Maybe you send data the wrong way. Try to see what you receive after your AJAX (POST method). Or read how correctly send data with AJAX.

http://api.jquery.com/jquery.ajax/

Body:
$a = json_encode(['555', '3M', 123, 1.2, 1.3]);
var_dump($a);//outputs string(24) "["555","3M",123,1.2,1.3]"

Maybe you send data the wrong way. Try to see what you receive after your AJAX (POST method). Or read how correctly send data with AJAX.

http://api.jquery.com/jquery.ajax/


问:
Cordova New Media Record save to directory
Working on a recording app with Cordova and using new Media for recording. I'm also using cordoba-file-plugin for creating directories etc. So when the app initialising I'm running

```<code>window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs){
   app.root = fs;
}, function(error){
   console.log(error);
});
</code>```

And then I'm running this code:

```<code>app.root.root.getDirectory('appname', {create:true}, function(dirEntry){
   dirEntry.getDirectory('recordings', {create:true}, function(subDirEntry) {
      app.recordings = subDirEntry;
   }, function(error){
      console.log(error);
   });
}, function(error){
   console.log(error);
});
</code>```

Then I have the recoding script and I would like to save the file directly to app.recordings, the directory I created for this app. But nothing shows up.

```<code>var path = app.recordings.nativeURL;
var filename = path + "recording-" + new Date().getTime() + ".mp3";
var mediaRec = new Media(filename, app.services.audio.success, app.services.audio.error);
mediaRec.startRecord();
mediaRec.stopRecord();
</code>```

I keep getting a tmprecording-12351834581925.3gp in root.

答:
On device ready

```<code>if(device.platform == "iOS"){
   app.path = cordova.file.tempDirectory;
   app.extension = ".wav";
   app.mimeType = "audio/wav";
} else if(device.platform == "Android"){
   app.path = cordova.file.externalRootDirectory;
   app.extension = ".amr";
   app.mimeType = "audio/amr";
}

window.resolveLocalFileSystemURL(app.path, function(fileSystem){
   fileSystem.getDirectory("AppName", {create:true},function(dirEntry){
      dirEntry.getDirectory("Recording", {create:true} , function(subEntry){
            app.recording = subEntry.nativeURL;
         }, function(error){
            console.log(error);
         });
   }, function(error){
      console.log(error);
   });
},function(error){
   console.log(error);
});
</code>```

Then on recording

```<code>var filename = app.recording + new Date().getTime() + app.extension;
var mediaRec = new Media(filename, success, error);
</code>```

The files are now saved in a preferred location where I now have control and access to the files.

Reading files in Recordings

```<code>window.resolveLocalFileSystemURL(app.recording ,function (fileSystem) {
   var reader = fileSystem.createReader();
   reader.readEntries(function (entries) {
      console.log(entries);
      //loop all entries
   }, function(error){
      console.log(error);
   });
}
</code>```

Body:
Working on a recording app with Cordova and using new Media for recording. I'm also using cordoba-file-plugin for creating directories etc. So when the app initialising I'm running

window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs){
   app.root = fs;
}, function(error){
   console.log(error);
});

And then I'm running this code:

app.root.root.getDirectory('appname', {create:true}, function(dirEntry){
   dirEntry.getDirectory('recordings', {create:true}, function(subDirEntry) {
      app.recordings = subDirEntry;
   }, function(error){
      console.log(error);
   });
}, function(error){
   console.log(error);
});

Then I have the recoding script and I would like to save the file directly to app.recordings, the directory I created for this app. But nothing shows up.

var path = app.recordings.nativeURL;
var filename = path + "recording-" + new Date().getTime() + ".mp3";
var mediaRec = new Media(filename, app.services.audio.success, app.services.audio.error);
mediaRec.startRecord();
mediaRec.stopRecord();

I keep getting a tmprecording-12351834581925.3gp in root.

Body:
On device ready

if(device.platform == "iOS"){
   app.path = cordova.file.tempDirectory;
   app.extension = ".wav";
   app.mimeType = "audio/wav";
} else if(device.platform == "Android"){
   app.path = cordova.file.externalRootDirectory;
   app.extension = ".amr";
   app.mimeType = "audio/amr";
}

window.resolveLocalFileSystemURL(app.path, function(fileSystem){
   fileSystem.getDirectory("AppName", {create:true},function(dirEntry){
      dirEntry.getDirectory("Recording", {create:true} , function(subEntry){
            app.recording = subEntry.nativeURL;
         }, function(error){
            console.log(error);
         });
   }, function(error){
      console.log(error);
   });
},function(error){
   console.log(error);
});

Then on recording

var filename = app.recording + new Date().getTime() + app.extension;
var mediaRec = new Media(filename, success, error);

The files are now saved in a preferred location where I now have control and access to the files.

Reading files in Recordings

window.resolveLocalFileSystemURL(app.recording ,function (fileSystem) {
   var reader = fileSystem.createReader();
   reader.readEntries(function (entries) {
      console.log(entries);
      //loop all entries
   }, function(error){
      console.log(error);
   });
}


问:
how to create array of random normalize number?
i want to create a matrix that each row of the matrix have 7 real random number in [0,1]  and the sum of number in each rows  should be equal to 1.
this matrix have 100 rows and 7 columns. how can i do it?
 at first ,i create an array with 1 row and 7 columns. then write the code as bellow. i try normal the number in the rows but sum of each row became more than 1.how can i fix it? thank for taking your time.</p>

```<code>a = rand(1,7);
for i=1:7
a(i) = a(i)/sum(a);
end
sum(a)
</code>```

答:
For 100 by 7, you can use bsxfun:

```<code>a = rand(100,7);
a = bsxfun(@rdivide,a.',sum(a.')).';
</code>```

Here the sum of each row = 1

Body:
i want to create a matrix that each row of the matrix have 7 real random number in [0,1]  and the sum of number in each rows  should be equal to 1.
this matrix have 100 rows and 7 columns. how can i do it?
 at first ,i create an array with 1 row and 7 columns. then write the code as bellow. i try normal the number in the rows but sum of each row became more than 1.how can i fix it? thank for taking your time.

a = rand(1,7);
for i=1:7
a(i) = a(i)/sum(a);
end
sum(a)

Body:
For 100 by 7, you can use bsxfun:

a = rand(100,7);
a = bsxfun(@rdivide,a.',sum(a.')).';

Here the sum of each row = 1


问:
How to replace text inside the jgrowl box smoothly?
I am setting the text inside the jgrowl message box.
Here is the example:

```<code>function findID(whichID, command){
                    if($(whichID).length)
                    {
                        var url='<script>\n\
                         $("'+whichID+'").fadeOut().load("include/common.php?q='+command+'&p='+username+'", function(response, status, xhr) { $(this).fadeIn(); });<\/script>';
                        $(whichID).fadeOut().html(url).fadeIn();
                    }
                }

var myID0="myID0";
var data='<div id="'+myID0+'" class="arm-info"></div>';
            $('#rightcolumn').jGrowl(data, {sticky:true });
mytimerID0=window.setInterval(findID, 3000, '#'+myID0, "show_queue");
</code>```

It works but the replacement is really jerky.

How to make a smooth transition between two load calls?

Thanks Arman.

答:
maybe replace the html after the fadout is complete, then fadeIn again.

```<code>$(whichID).fadeOut(function(){ $(this).html(url).fadeIn(); });
</code>```

if you do

```<code>$(whichID).fadeOut().html(url).fadeIn();
</code>```

it'll replace the html the same time it starts fading out.

edit:

couldn't you just write in the findID function? I don't think you need the script tag:

```<code>$.ajax( url:'include/common.php?q='+command+'&p='+username,
        success: function(data){
           $(this).fadeOut(function(){ $(this).html(data).fadeIn(); });
        }
);
</code>```

Body:
I am setting the text inside the jgrowl message box.
Here is the example:

function findID(whichID, command){
                    if($(whichID).length)
                    {
                        var url='

Body:
maybe replace the html after the fadout is complete, then fadeIn again.

$(whichID).fadeOut(function(){ $(this).html(url).fadeIn(); });

if you do

$(whichID).fadeOut().html(url).fadeIn();

it'll replace the html the same time it starts fading out.

edit:

couldn't you just write in the findID function? I don't think you need the script tag:

$.ajax( url:'include/common.php?q='+command+'&p='+username,
        success: function(data){
           $(this).fadeOut(function(){ $(this).html(data).fadeIn(); });
        }
);


问:
How to remote desktop (RDP) to hosted agents of Azure Pipelines
I have a Azure Pipelines (previously known as VSTS CI/CD pipelines) definition using Hosted Agent. There are cases when the build works locally but fails on hosted agent due to environment configuration differences. It will greatly improve troubleshooting experience if I can remote desktop to the Hosted Agent assigned to my job, like what AppVeyor does. Is it possible for Azure Pipelines as well?</p>

答:
No, you can’t remote desktop to hosted agent, also the hosted agent may different for different builds/release.

You can refer to this article to check hosted agent software: Hosted agents

You also can setup a private build agent for the build: Deploy an agent on Windows

ContentLicense: CC BY-SA 4.0


问:
datepicker not working after making ajax call
//here the code for calling date picker

```<code> <script type="text/javascript">
     $(function () {
       $(".datepicker").datepicker({
        constrainInput: true,
        showOn: 'button',
        buttonText: 'Select...'
    });

});
</script>
<input class="datepicker" disabled="disabled" />
</code>```

//Here Im making an ajax call

```<code>function reFresh(name){
            $.ajax({
            type:"GET",
            url:"Phase",
            data:{projectName:name},
            async: false,
            dataType:"html",
            success:function(data) {
               $("#Left_Panel").html(data);

            },
            error:function() {
                alert("Error ! In fetching data.");
            }
        })

}
</code>```

// After coming to the first page again using ajax , now datepicker not working .

答:
I would suggest you to go this way.

First, make function where you init the datepicker:

```<code>function refreshDatepicker() {
    $(".datepicker").datepicker({
        constrainInput: true,
        showOn: 'button',
        buttonText: 'Select...'
    });
}
</code>```

Second, call this function whenever you need it to - after DOM load, after ajax call, etc. This way it will be easier to maintain:

```<code>$(function() {
    refreshDatepicker();
});
</code>```

Third, after successfully fetching data from ajax call this function again, so it will re-init all datepickers in the DOM.

```<code>success: function(data) {
    $("#Left_Panel").html(data);
    refreshDatepicker();
}
</code>```

If this won't work, then problem is in fetched data. Check the data from ajax if it comes well, then check if it contains input with class datepicker, etc. Otherwise I don't see why this won't work. If you get any error in the console let me know.

Body:
//here the code for calling date picker

<input class="datepicker" disabled="disabled" />

//Here Im making an ajax call

function reFresh(name){
            $.ajax({
            type:"GET",
            url:"Phase",
            data:{projectName:name},
            async: false,
            dataType:"html",
            success:function(data) {
               $("#Left_Panel").html(data);

            },
            error:function() {
                alert("Error ! In fetching data.");
            }
        })

}

// After coming to the first page again using ajax , now datepicker not working .

Body:
I would suggest you to go this way.

First, make function where you init the datepicker:

function refreshDatepicker() {
    $(".datepicker").datepicker({
        constrainInput: true,
        showOn: 'button',
        buttonText: 'Select...'
    });
}

Second, call this function whenever you need it to - after DOM load, after ajax call, etc. This way it will be easier to maintain:

$(function() {
    refreshDatepicker();
});

Third, after successfully fetching data from ajax call this function again, so it will re-init all datepickers in the DOM.

success: function(data) {
    $("#Left_Panel").html(data);
    refreshDatepicker();
}

If this won't work, then problem is in fetched data. Check the data from ajax if it comes well, then check if it contains input with class datepicker, etc. Otherwise I don't see why this won't work. If you get any error in the console let me know.


问:
Want to import bits (a couple of rows) of an .txt to excel
Hey so i found a specific query to import a file into excel from a specific row and delete the following datga each time you open it again. but is it also pssible to stop adding rows at a specific line? and is it possible to leave some rows out if there for example is a specific word in that line?

Sub Sample()
    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;C:\Users\sample.txt", Destination:=Range("$A$1") _
        )
        .Name = "Sample"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False

    End With
End Sub```

答:
You can do it, but not with a Querytable.
Try this code:

```<code>Private Sub Open_Click()
Dim fn As Variant, myLine As Long, txt As String, x As Variant, ouput As String
Dim i As Integer, j As Integer: j = 1
Dim sht As Worksheet

Set sht = Worksheets("Sheet1") 'Modify Sheet Name

fn = Application.GetOpenFilename("Text Files (*.txt),*.txt", , _
       "Open File")
If fn = False Then Exit Sub
txt = CreateObject("Scripting.FileSystemObject").OpenTextFile(fn).ReadAll
x = Split(txt, vbNewLine)

For i = 0 To UBound(x)
    If x(i) <> "SomeCriteria" Then 'Check for some criteria
        sht.Cells(j, 1).Value = x(i)
        j = j + 1
    End If
Next i
End Sub
</code>```

So what it does basically, it opens a user selected txt file and stores it in the variable txt. Do seperate the rows you can use the split-function. Now each line is stored in an array x. You could go trough the array/each line and take out the ones you want. To check if a specific word is in a line, use the InStr-function.

Body:
You can do it, but not with a Querytable.
Try this code:

Private Sub Open_Click()
Dim fn As Variant, myLine As Long, txt As String, x As Variant, ouput As String
Dim i As Integer, j As Integer: j = 1
Dim sht As Worksheet

Set sht = Worksheets("Sheet1") 'Modify Sheet Name

fn = Application.GetOpenFilename("Text Files (*.txt),*.txt", , _
       "Open File")
If fn = False Then Exit Sub
txt = CreateObject("Scripting.FileSystemObject").OpenTextFile(fn).ReadAll
x = Split(txt, vbNewLine)

For i = 0 To UBound(x)
    If x(i) <> "SomeCriteria" Then 'Check for some criteria
        sht.Cells(j, 1).Value = x(i)
        j = j + 1
    End If
Next i
End Sub

So what it does basically, it opens a user selected txt file and stores it in the variable txt. Do seperate the rows you can use the split-function. Now each line is stored in an array x. You could go trough the array/each line and take out the ones you want. To check if a specific word is in a line, use the InStr-function.


问:
log4j.properties file to log4j2.xml conversion
I am upgrading from log4j1.x to log4j-2.8.2
I am trying to convert my existing log4j.properties file to equivalent log4j2.xml.
My first question is can I write log4j2.proeprties file instead of log4j2.xml file?

I found some equivalent tags to log4j.proeprties file in log4j2.xml.
I did not find tags for the below lines. can anybody suggest on this?

```<code># LoggerFactory for ESAPI to utilize Log4J
log4j.loggerFactory=org.owasp.esapi.reference.Log4JLoggerFactory
log4j.category.Default=ALL, CONSOLE, RollingFile2, edelivery
log4j.rootCategory=OFF

log4j.logger.org.apache=INFO
log4j.logger.IntrusionDetector=ERROR
log4j.logger.org.springframework=WARN
</code>```

Thanks in advance.

答:
What i am sure is:

See the last three lines:

```<code>log4j.logger.org.apache=INFO
log4j.logger.IntrusionDetector=ERROR
log4j.logger.org.springframework=WARN
</code>```

I think in log4j.xml they should be instead of like these below:

```<code><Logger name="org.apache" level="INFO"/>
<Logger name="IntrusionDetector" level="ERROR"/>
<Logger name="org.springframework" level="WARN"/>
</code>```

And what I am not sure is:
these two lines:

```<code>log4j.category.Default=ALL, CONSOLE, RollingFile2, edelivery
log4j.rootCategory=OFF
</code>```

I guess you have configured some appenders with the name in above line like:

```<code><appender name="CONSOLE">
  other proerties....
</appender>
</code>```

so i think you could try to use these in your log4j.xml:

```<code><root>
  <appender-ref ref="ALL" />
  <appender-ref ref="CONSOLE" />
  <appender-ref ref="RollingFile2" />
  <appender-ref ref="edelivery" />
</root>
</code>```

And What I really don't know is:

```<code>log4j.loggerFactory=org.owasp.esapi.reference.Log4JLoggerFactory
</code>```

I Know nothing about esapi so i could not suggest how to deal with it, hope someone else to give more answer.

Body:
I am upgrading from log4j1.x to log4j-2.8.2
I am trying to convert my existing log4j.properties file to equivalent log4j2.xml.
My first question is can I write log4j2.proeprties file instead of log4j2.xml file?

I found some equivalent tags to log4j.proeprties file in log4j2.xml.
I did not find tags for the below lines. can anybody suggest on this?

# LoggerFactory for ESAPI to utilize Log4J
log4j.loggerFactory=org.owasp.esapi.reference.Log4JLoggerFactory
log4j.category.Default=ALL, CONSOLE, RollingFile2, edelivery
log4j.rootCategory=OFF

log4j.logger.org.apache=INFO
log4j.logger.IntrusionDetector=ERROR
log4j.logger.org.springframework=WARN

Thanks in advance.

Body:
What i am sure is:

See the last three lines:

log4j.logger.org.apache=INFO
log4j.logger.IntrusionDetector=ERROR
log4j.logger.org.springframework=WARN

I think in log4j.xml they should be instead of like these below:

<Logger name="org.apache" level="INFO"/>
<Logger name="IntrusionDetector" level="ERROR"/>
<Logger name="org.springframework" level="WARN"/>

And what I am not sure is:
these two lines:

log4j.category.Default=ALL, CONSOLE, RollingFile2, edelivery
log4j.rootCategory=OFF

I guess you have configured some appenders with the name in above line like:

<appender name="CONSOLE">
  other proerties....
</appender>

so i think you could try to use these in your log4j.xml:

<root>
  <appender-ref ref="ALL" />
  <appender-ref ref="CONSOLE" />
  <appender-ref ref="RollingFile2" />
  <appender-ref ref="edelivery" />
</root>

And What I really don't know is:

log4j.loggerFactory=org.owasp.esapi.reference.Log4JLoggerFactory

I Know nothing about esapi so i could not suggest how to deal with it, hope someone else to give more answer.


问:
Get continues records on scrolling
Suppose  I have   n number of records. And those records should display on screen.
For first Time it should display 25 records and when user scrolls down then next 25 record should come like facebook does .Is there any solution?</p>

答:
you can try this code

```<code>function loadMoreLeadsOnScroll() {

                if (_.isEqual($location.path(), ('/lead/list'))) {
                    var currentScroll = angular.element(this).scrollTop();
                    if (currentScroll > $scope.previousScroll) {
                        angular.element('#btnBackToTop').addClass('clsHighlightBackBtn');
                    }
                    $scope.previousScroll = currentScroll;
                    if (angular.element(document).height() - 50 <= angular.element(window).scrollTop() + angular.element(window).height()) {
                        //Your function here to load data from db
                    }
                }
                if ((angular.element(window).height() + 100) < angular.element(document).height()) {
                    angular.element('#top-link-block').removeClass('hidden').affix({
                        // how far to scroll down before link "slides" into view
                        offset: {top: 100}
                    });
                }
            }

            angular.element(document).ready(function () {
            });

$scope.leadOnLoad = function () {
                angular.element(window).on('scroll', loadMoreLeadsOnScroll);
            };
  $scope.$on('$viewContentLoaded', $scope.leadOnLoad);
</code>```

this is working for me

Title: Get continues records on scrolling

Body:
you can try this code

function loadMoreLeadsOnScroll() {

                if (_.isEqual($location.path(), ('/lead/list'))) {
                    var currentScroll = angular.element(this).scrollTop();
                    if (currentScroll > $scope.previousScroll) {
                        angular.element('#btnBackToTop').addClass('clsHighlightBackBtn');
                    }
                    $scope.previousScroll = currentScroll;
                    if (angular.element(document).height() - 50 <= angular.element(window).scrollTop() + angular.element(window).height()) {
                        //Your function here to load data from db
                    }
                }
                if ((angular.element(window).height() + 100) < angular.element(document).height()) {
                    angular.element('#top-link-block').removeClass('hidden').affix({
                        // how far to scroll down before link "slides" into view
                        offset: {top: 100}
                    });
                }
            }

            angular.element(document).ready(function () {
            });

$scope.leadOnLoad = function () {
                angular.element(window).on('scroll', loadMoreLeadsOnScroll);
            };
  $scope.$on('$viewContentLoaded', $scope.leadOnLoad);

this is working for me


问:
Jquery - fadeIn - jerky fadein
I've made a simple image switcher that fades different logos in and out. Example and full source code at http://bit.ly/ewrSgp . I fadeout the image, then queue a src attribute change, then fade back in. It seems to work smoothly for a while but after 20 seconds or so it starts to fade the image back in before changing the src, which then changes instantly and  looks ugly. Am I doing this right?

The code that runs the change is:

```<code>// fadeout old image, change to new and fadeback in.
// Call function changeimage again.
$(imToChange).fadeOut(600).queue(function (n) {
    jQuery(this).attr('src', newimageSrc);
    n();
}).fadeIn(1000, function () {
    setTimeout(function () {
        //recall image change function
        changeImage(indexToChange);
    }, o.delay);
});
</code>```

Thanks in advance.

答:
I think you need to wait for the image to finish loading. I'd try displaying the image outside the visible area or behind some other image until the onload event fires, then move it and fade it in at the proper location.

Something like this.

```<code>var img = $("<img href='newimage.png' />").load(function() { movit(); fadeit(); });
$("#ahiddenelement").append(img);
</code>```

Title: Jquery - fadeIn - jerky fadein

Body:
I've made a simple image switcher that fades different logos in and out. Example and full source code at http://bit.ly/ewrSgp . I fadeout the image, then queue a src attribute change, then fade back in. It seems to work smoothly for a while but after 20 seconds or so it starts to fade the image back in before changing the src, which then changes instantly and  looks ugly. Am I doing this right?

The code that runs the change is:

// fadeout old image, change to new and fadeback in.
// Call function changeimage again.
$(imToChange).fadeOut(600).queue(function (n) {
    jQuery(this).attr('src', newimageSrc);
    n();
}).fadeIn(1000, function () {
    setTimeout(function () {
        //recall image change function
        changeImage(indexToChange);
    }, o.delay);
});

Thanks in advance.

Body:
I think you need to wait for the image to finish loading. I'd try displaying the image outside the visible area or behind some other image until the onload event fires, then move it and fade it in at the proper location.

Something like this.

var img = $("<img href='newimage.png' />").load(function() { movit(); fadeit(); });
$("#ahiddenelement").append(img);


问:
Serving gzipped CSS and JavaScript from Amazon CloudFront via S3
I've been looking for ways of making my site load faster and one way that I'd like to explore is making greater use of Cloudfront.

Because Cloudfront was originally not designed as a custom-origin CDN and because it didn't support gzipping, I have so far been using it to host all my images, which are referenced by their Cloudfront cname in my site code, and optimized with far-futures headers.

CSS and javascript files, on the other hand, are hosted on my own server, because until now I was under the impression that they couldn't be served gzipped from Cloudfront, and that the gain from gzipping (about 75 per cent) outweighs that from using a CDN (about 50 per cent): Amazon S3 (and thus Cloudfront) did not support serving gzipped content in a standard manner by using the HTTP Accept-Encoding header that is sent by browsers to indicate their support for gzip compression, and so they were not able to Gzip and serve components on the fly.

Thus I was under the impression, until now, that one had to choose between two alternatives:

move all assets to the Amazon CloudFront and forget about GZipping;

keep components self-hosted and configure our server to detect incoming requests and perform on-the-fly GZipping as appropriate, which is what I chose to do so far.

There were workarounds to solve this issue, but essentially these didn't work. [link].

Now, it seems Amazon Cloudfront supports custom origin, and that it is now possible to use the standard HTTP Accept-Encoding method for serving gzipped content if you are using a Custom Origin  [link].

I haven't so far been able to implement the new feature on my server.  The blog post I linked to above, which is the only one I found detailing the change, seems to imply that you can only enable gzipping (bar workarounds, which I don't want to use), if you opt for custom origin, which I'd rather not: I find it simpler to host the coresponding fileds on my Cloudfront server, and link to them from there. Despite carefully reading the documentation, I don't know:

whether the new feature means the files should be hosted on my own domain server via custom origin, and if so, what code setup will achieve this;

how to configure the css and javascript headers to make sure they are served gzipped from Cloudfront.

答:
You can configure CloudFront to automatically compress files of certain types and serve the compressed files.

See AWS Developer Guide


问:
How to make a variable globally accessible in Prestashop
I'm modifying a module in Prestashop, which has folder structure like this..

```<code>css
translations
index.php
module.php
module.tpl
</code>```

There is a variable $products that has an array of all the products. But it's only accessible to module.tpl which displays all the product on the homepage which I don't like.

I created a controller that redirects to a different page and a template/view/front/products.tpl to display all the products. But that $products variable is undefined in products.tpl file.

答:
I actually figured this out. I had no choice but to instantiate new category and then fetch all the products.
Like this:  </p>

```<code>$category = new Category(Context::getContext()->shop->getCategory(), (int)Context::getContext()->language->id);
$nb = 10000;
$products = $category->getProducts((int)Context::getContext()->language->id, 1, ($nb ? $nb : 10));
</code>```

Body:
I'm modifying a module in Prestashop, which has folder structure like this..

css
translations
index.php
module.php
module.tpl

There is a variable $products that has an array of all the products. But it's only accessible to module.tpl which displays all the product on the homepage which I don't like.

I created a controller that redirects to a different page and a template/view/front/products.tpl to display all the products. But that $products variable is undefined in products.tpl file.

Body:
I actually figured this out. I had no choice but to instantiate new category and then fetch all the products.
Like this:

$category = new Category(Context::getContext()->shop->getCategory(), (int)Context::getContext()->language->id);
$nb = 10000;
$products = $category->getProducts((int)Context::getContext()->language->id, 1, ($nb ? $nb : 10));


问:
Java - Is it possible to call an interface method on a any object?
Lets say I have Object X and Object B. X is an object of a random class, which in turn creates B, and passes itself on to be stored as a variable in object B.

Now object B, wants to run a method in object X, without knowing what class it is.

Is it possible to call a method in any object, and if a method with that name exist, it runs, and if not, it doesn't. I assume some try/catch can work around that part.

But lets say i have something like this:

```<code>public class ObjectB {

  public Object parentX;

  public ObjectB(Object x) {
    parentX = x;
  }

  public void anyMethod() {
    x.runMyMethod();
  }
}
</code>```

In another program I worked with, this was possible with interfaces, and therefore have an idea that it is possible with Java too. However, i cant seem to find the way to set this up. So if the above was the case, how would it be set up, such that ObjectB can call the method on all the classes in my program if that was what i wanted?

答:
Yes its definitely possible.

Define interface MyIntf, and your Class X implements it. now in Class B you can assign the object of Class X (or any class that implements MyIntf) to parent which of type MyIntf the you can invoke method with that parent

```<code>    interface MyIntf
    {
       void runMyMethod()
    }

    public class ObjectX implements MyIntf {
           void runMyMethod()
           {
           }
    }

    public class ObjectB {

      public MyIntf parentX;

      public ObjectB(MyIntf x) {
        parentX = x;
      }

      public void anyMethod() {
        parentX.runMyMethod();
      }
    }
</code>```

Body:
Lets say I have Object X and Object B. X is an object of a random class, which in turn creates B, and passes itself on to be stored as a variable in object B.

Now object B, wants to run a method in object X, without knowing what class it is.

Is it possible to call a method in any object, and if a method with that name exist, it runs, and if not, it doesn't. I assume some try/catch can work around that part.

But lets say i have something like this:

public class ObjectB {

  public Object parentX;

  public ObjectB(Object x) {
    parentX = x;
  }

  public void anyMethod() {
    x.runMyMethod();
  }
}

In another program I worked with, this was possible with interfaces, and therefore have an idea that it is possible with Java too. However, i cant seem to find the way to set this up. So if the above was the case, how would it be set up, such that ObjectB can call the method on all the classes in my program if that was what i wanted?

Body:
Yes its definitely possible.

Define interface MyIntf, and your Class X implements it. now in Class B you can assign the object of Class X (or any class that implements MyIntf) to parent which of type MyIntf the you can invoke method with that parent

    interface MyIntf
    {
       void runMyMethod()
    }

    public class ObjectX implements MyIntf {
           void runMyMethod()
           {
           }
    }

    public class ObjectB {

      public MyIntf parentX;

      public ObjectB(MyIntf x) {
        parentX = x;
      }

      public void anyMethod() {
        parentX.runMyMethod();
      }
    }


问:
Python - Strip line at either one point or another in the same string
I want to save a phrase that´s between a start and a end point.

The start is start = '->'. The problem is that it can have two different end points (depending on which string I get) end = ':\' or end1 ='[Channel].

So I'm trying to split the string at both ends ':\' and '[channel]' in the same loop. I tried using or, split, strip, striplines and others, but nothing does the trick

How  my code looks now (not working)

```<code>        if line.startswith('->'):
                start = '-> '  # take string from
                end = ':\ ' #either end at this character
                end1 = '[Channel]' # or this character
                data.append(line[line.find(start) + 3:line.find(end or end1)].strip())
</code>```

example on how the file with the strings looks

```<code>SEND TEST:
-> 3C 53 25 25 :\TCM_APP_33\MO\NO
-> 32 12 H2 3G [Channel]
-> 43 34 52 4B [Channel]
-> 4C 33 45 24 [Channel]
SEND TEST:
-> 35 32 5V 25 :\ KCM_APP_31\TEST\FIX
-> 3N 21 24 23 [Channel]
SEND TEST:
-> 12 3F 56 7D :\BCM_APP_31\TRY
-> 3N 21 24 23 [Channel]
</code>```

Basically I want to extract the numbers

Body:
I want to save a phrase that´s between a start and a end point.

The start is start = '->'. The problem is that it can have two different end points (depending on which string I get) end = ':\' or end1 ='[Channel].

So I'm trying to split the string at both ends ':\' and '[channel]' in the same loop. I tried using or, split, strip, striplines and others, but nothing does the trick

How  my code looks now (not working)

        if line.startswith('->'):
                start = '-> '  # take string from
                end = ':\ ' #either end at this character
                end1 = '[Channel]' # or this character
                data.append(line[line.find(start) + 3:line.find(end or end1)].strip())

example on how the file with the strings looks

SEND TEST:
-> 3C 53 25 25 :\TCM_APP_33\MO\NO
-> 32 12 H2 3G [Channel]
-> 43 34 52 4B [Channel]
-> 4C 33 45 24 [Channel]
SEND TEST:
-> 35 32 5V 25 :\ KCM_APP_31\TEST\FIX
-> 3N 21 24 23 [Channel]
SEND TEST:
-> 12 3F 56 7D :\BCM_APP_31\TRY
-> 3N 21 24 23 [Channel]

Basically I want to extract the numbers

Body:
You can split with space :

>>> s = "-> 4334524 [Channel]"
>>> data = s.split()
>>> data
[u'->', u'4334524', u'[Channel]']
>>> data[1]
u'4334524'

Edited:

>>> l = "-> 32 12 H2 3G [Channel]"
>>> str("".join(l.split()[1:5]))
'3212H23G'