问:
Program don't complete returns value 3221225477 no compiler errors
Hello i am new to c++ programming and i have write this code </p>

```<code>#include <iostream>
#include <string>

using namespace std;

class Weapon
{
    string weaponName;
public:
    Weapon(string n)
    {
        weaponName=n;
        cout<<"Weapon created"<<endl;
    };

    ~Weapon()
    {
        cout<<"Weapon destroyed"<<endl;
    };

    //getter

    string getWeaponName()
    {
        return weaponName;
    };

    //setter

    string setWeaponName(string name2)
    {
        weaponName=name2;
    };

};

class Samurai
{
    string samuraiWeapon;
    string name;
    int age;
    int numberOfWins;
    int numberOfInjuries;
    int numberOfDuels;
 public:
    Samurai(string t,int w,int i,int d,int a)
    {
        name=t;
        numberOfWins=w;
        numberOfInjuries=i;
        numberOfDuels=d;
        age=a;
        samuraiWeapon="no weapon";
        cout <<"Samurai ready for duel."<<endl;

    };

    ~Samurai()
    {
        cout<<"Samurai " << name <<" deleted "<<endl;
    };

    void  printSamuraiDescription()
    {
        cout<<"Samurai name: "<< name <<" Duels: "<<numberOfDuels<<" Wins: "<<numberOfWins<<"  Injuries: "<<numberOfInjuries<<endl;
    };

    void pickWeapon(Weapon &a)
    {
        if (age<18)
        {
            setSamuraiWeapon("Wooden Sword");
            cout<<samuraiWeapon<<endl;
        }
        else
        {
        setSamuraiWeapon(a.getWeaponName());
            cout<<samuraiWeapon<<endl;
        }
    }

    //getters

    string getName()
    {
        return name;
    };

    string getSamuraiWeapon()
    {
        return samuraiWeapon;
    };

    int getnumberOfWins()
    {
        return numberOfWins;
    };

    int getnumberOfInjuries()
    {
        return numberOfInjuries;
    };

    int getnumberOfDuels()
    {
        return numberOfDuels;
    };

    int getAge()
    {
        return age;
    };

    //setters

    string setName(string a)
    {
         name=a;
    };

    string setSamuraiWeapon(string e)
    {
        samuraiWeapon=e;
    };

    int setnumberOfWins(int b)
    {
         numberOfWins=b;
    };

    int setnumberOfInjuries(int c)
    {
         numberOfInjuries=c;
    };

    int setnumberOfDuels(int d)
    {
         numberOfDuels=d;
    };

    int setAge(int f)
    {
        age=f;
    };

    //friend fuction
    friend void duel(Samurai &a, Samurai &b, bool winner);
    friend string duelForYoungSamurais(Samurai &a, Samurai &b);

};

string duelForYoungSamurais(Samurai &a, Samurai &b)
{
    if (a.age>18 || b.age>18)
    {
        cout<<"Invalid duel"<<endl;
    }

    if (a.samuraiWeapon!="Wooden Sword" || b.samuraiWeapon!="Wooden Sword")
    {
        cout<<"Duel postponed"<<endl;
    }
    else
    {
        cout<<a.getName()<<" duels "<<b.getName()<<endl;
    }

}

void duel(Samurai &a, Samurai &b, bool winner)
{
    a.setnumberOfDuels(a.numberOfWins+1);
    b.setnumberOfDuels(b.numberOfWins+1);

    if (winner==true)
    {
        cout<<"Samurai a is winner "<<endl;
        a.setnumberOfWins(a.numberOfWins+1);
        b.setnumberOfInjuries(b.numberOfInjuries+1);
        if(a.numberOfWins>=10) cout<<"Samurai a is duelist"<<endl;
    }
    else
    {
        cout<<"Samurai b is winner "<<endl;
        b.setnumberOfWins(b.numberOfWins+1);
        a.setnumberOfInjuries(a.numberOfInjuries+1);
        if(b.numberOfWins>=10) cout<<"Samurai b is duelist"<<endl;
    }

}

int main()
{
    Samurai a("Giorgos",9,0,0,18);
    Samurai b("Giannis",1,2,3,13);
    Weapon a1("Rock");
    a.pickWeapon(a1);
    b.pickWeapon(a1);
    duelForYoungSamurais(a,b);
    duel(a,b,true);
    a.printSamuraiDescription();
    b.printSamuraiDescription();

}
</code>```

<p>The programm compiles with no errors but when it starts and run it stops and in a few seconds end without do what i want and returns 3221225477 if i put in comments the part that have to do with the Weapon class and pickWeapon and duelForYoungSamurais fuctions my code runs just fine </p>

答:
Here, I corrected all setters with return type other than void and now it works:

```<code>#include <iostream>
#include <string>

using namespace std;

class Weapon
{
    string weaponName;
public:
    Weapon(string n)
    {
        weaponName=n;
        cout<<"Weapon created"<<endl;
    }

    ~Weapon()
    {
        cout<<"Weapon destroyed"<<endl;
    }

    //getter

    string getWeaponName()
    {
        return weaponName;
    }

    //setter

    void setWeaponName(string name2)
    {
        weaponName=name2;
    }

};

class Samurai
{
    string samuraiWeapon;
    string name;
    int age;
    int numberOfWins;
    int numberOfInjuries;
    int numberOfDuels;
    public:

    Samurai(string t,int w,int i,int d,int a)
    {
        name=t;
        numberOfWins=w;
        numberOfInjuries=i;
        numberOfDuels=d;
        age=a;
        samuraiWeapon="no weapon";
        cout <<"Samurai ready for duel."<<endl;

    };

    ~Samurai()
    {
        cout<<"Samurai " << name <<" deleted "<<endl;
    }

    void  printSamuraiDescription()
    {
        cout<<"Samurai name: "<< name <<" Duels: "<<numberOfDuels<<" Wins: "<<numberOfWins<<"  Injuries: "<<numberOfInjuries<<endl;
    }

    void pickWeapon(Weapon &a)
    {
        if (age<18)
        {
            setSamuraiWeapon("Wooden Sword");
            cout<<samuraiWeapon<<endl;
        }
        else
        {
        setSamuraiWeapon(a.getWeaponName());
            cout<<samuraiWeapon<<endl;
        }
    }

    //getters

    string getName()
    {
        return name;
    }

    string getSamuraiWeapon()
    {
        return samuraiWeapon;
    }

    int getnumberOfWins()
    {
        return numberOfWins;
    }

    int getnumberOfInjuries()
    {
        return numberOfInjuries;
    }

    int getnumberOfDuels()
    {
        return numberOfDuels;
    }

    int getAge()
    {
        return age;
    }

    //setters

    void setName(string a)
    {
         name=a;
    }

    void setSamuraiWeapon(string e)
    {
        samuraiWeapon=e;
    }

    void setnumberOfWins(int b)
    {
         numberOfWins=b;
    }

    void setnumberOfInjuries(int c)
    {
         numberOfInjuries=c;
    }

    void setnumberOfDuels(int d)
    {
         numberOfDuels=d;
    }

    void setAge(int f)
    {
        age=f;
    }

    //friend fuction
    friend void duel(Samurai &a, Samurai &b, bool winner);
    friend void duelForYoungSamurais(Samurai &a, Samurai &b);

};

void duelForYoungSamurais(Samurai &a, Samurai &b)
{
    if (a.age>18 || b.age>18)
    {
        cout<<"Invalid duel"<<endl;
    }

    if (a.samuraiWeapon!="Wooden Sword" || b.samuraiWeapon!="Wooden Sword")
    {
        cout<<"Duel postponed"<<endl;
    }
    else
    {
        cout<<a.getName()<<" duels "<<b.getName()<<endl;
    }

}

void duel(Samurai &a, Samurai &b, bool winner)
{
    a.setnumberOfDuels(a.numberOfWins+1);
    b.setnumberOfDuels(b.numberOfWins+1);

    if (winner==true)
    {
        cout<<"Samurai a is winner "<<endl;
        a.setnumberOfWins(a.numberOfWins+1);
        b.setnumberOfInjuries(b.numberOfInjuries+1);
        if(a.numberOfWins>=10) cout<<"Samurai a is duelist"<<endl;
    }
    else
    {
        cout<<"Samurai b is winner "<<endl;
        b.setnumberOfWins(b.numberOfWins+1);
        a.setnumberOfInjuries(a.numberOfInjuries+1);
        if(b.numberOfWins>=10) cout<<"Samurai b is duelist"<<endl;
    }

}

int main()
{
    Samurai a("Giorgos",9,0,0,18);
    Samurai b("Giannis",1,2,3,13);
    Weapon a1("Rock");
    a.pickWeapon(a1);
    b.pickWeapon(a1);
    duelForYoungSamurais(a,b);
    duel(a,b,true);
    a.printSamuraiDescription();
    b.printSamuraiDescription();

}
</code>```

Body:
Hello i am new to c++ programming and i have write this code

#include <iostream>
#include <string>

using namespace std;

class Weapon
{
    string weaponName;
public:
    Weapon(string n)
    {
        weaponName=n;
        cout<<"Weapon created"<<endl;
    };

    ~Weapon()
    {
        cout<<"Weapon destroyed"<<endl;
    };

    //getter

    string getWeaponName()
    {
        return weaponName;
    };

    //setter

    string setWeaponName(string name2)
    {
        weaponName=name2;
    };

};

class Samurai
{
    string samuraiWeapon;
    string name;
    int age;
    int numberOfWins;
    int numberOfInjuries;
    int numberOfDuels;
 public:
    Samurai(string t,int w,int i,int d,int a)
    {
        name=t;
        numberOfWins=w;
        numberOfInjuries=i;
        numberOfDuels=d;
        age=a;
        samuraiWeapon="no weapon";
        cout <<"Samurai ready for duel."<<endl;

    };

    ~Samurai()
    {
        cout<<"Samurai " << name <<" deleted "<<endl;
    };

    void  printSamuraiDescription()
    {
        cout<<"Samurai name: "<< name <<" Duels: "<<numberOfDuels<<" Wins: "<<numberOfWins<<"  Injuries: "<<numberOfInjuries<<endl;
    };

    void pickWeapon(Weapon &a)
    {
        if (age<18)
        {
            setSamuraiWeapon("Wooden Sword");
            cout<<samuraiWeapon<<endl;
        }
        else
        {
        setSamuraiWeapon(a.getWeaponName());
            cout<<samuraiWeapon<<endl;
        }
    }

    //getters

    string getName()
    {
        return name;
    };

    string getSamuraiWeapon()
    {
        return samuraiWeapon;
    };

    int getnumberOfWins()
    {
        return numberOfWins;
    };

    int getnumberOfInjuries()
    {
        return numberOfInjuries;
    };

    int getnumberOfDuels()
    {
        return numberOfDuels;
    };

    int getAge()
    {
        return age;
    };

    //setters

    string setName(string a)
    {
         name=a;
    };

    string setSamuraiWeapon(string e)
    {
        samuraiWeapon=e;
    };

    int setnumberOfWins(int b)
    {
         numberOfWins=b;
    };

    int setnumberOfInjuries(int c)
    {
         numberOfInjuries=c;
    };

    int setnumberOfDuels(int d)
    {
         numberOfDuels=d;
    };

    int setAge(int f)
    {
        age=f;
    };

    //friend fuction
    friend void duel(Samurai &a, Samurai &b, bool winner);
    friend string duelForYoungSamurais(Samurai &a, Samurai &b);

};

string duelForYoungSamurais(Samurai &a, Samurai &b)
{
    if (a.age>18 || b.age>18)
    {
        cout<<"Invalid duel"<<endl;
    }

    if (a.samuraiWeapon!="Wooden Sword" || b.samuraiWeapon!="Wooden Sword")
    {
        cout<<"Duel postponed"<<endl;
    }
    else
    {
        cout<<a.getName()<<" duels "<<b.getName()<<endl;
    }

}

void duel(Samurai &a, Samurai &b, bool winner)
{
    a.setnumberOfDuels(a.numberOfWins+1);
    b.setnumberOfDuels(b.numberOfWins+1);

    if (winner==true)
    {
        cout<<"Samurai a is winner "<<endl;
        a.setnumberOfWins(a.numberOfWins+1);
        b.setnumberOfInjuries(b.numberOfInjuries+1);
        if(a.numberOfWins>=10) cout<<"Samurai a is duelist"<<endl;
    }
    else
    {
        cout<<"Samurai b is winner "<<endl;
        b.setnumberOfWins(b.numberOfWins+1);
        a.setnumberOfInjuries(a.numberOfInjuries+1);
        if(b.numberOfWins>=10) cout<<"Samurai b is duelist"<<endl;
    }

}

int main()
{
    Samurai a("Giorgos",9,0,0,18);
    Samurai b("Giannis",1,2,3,13);
    Weapon a1("Rock");
    a.pickWeapon(a1);
    b.pickWeapon(a1);
    duelForYoungSamurais(a,b);
    duel(a,b,true);
    a.printSamuraiDescription();
    b.printSamuraiDescription();

}

The programm compiles with no errors but when it starts and run it stops and in a few seconds end without do what i want and returns 3221225477 if i put in comments the part that have to do with the Weapon class and pickWeapon and duelForYoungSamurais fuctions my code runs just fine

Body:
Here, I corrected all setters with return type other than void and now it works:

#include <iostream>
#include <string>

using namespace std;

class Weapon
{
    string weaponName;
public:
    Weapon(string n)
    {
        weaponName=n;
        cout<<"Weapon created"<<endl;
    }

    ~Weapon()
    {
        cout<<"Weapon destroyed"<<endl;
    }

    //getter

    string getWeaponName()
    {
        return weaponName;
    }

    //setter

    void setWeaponName(string name2)
    {
        weaponName=name2;
    }

};

class Samurai
{
    string samuraiWeapon;
    string name;
    int age;
    int numberOfWins;
    int numberOfInjuries;
    int numberOfDuels;
    public:

    Samurai(string t,int w,int i,int d,int a)
    {
        name=t;
        numberOfWins=w;
        numberOfInjuries=i;
        numberOfDuels=d;
        age=a;
        samuraiWeapon="no weapon";
        cout <<"Samurai ready for duel."<<endl;

    };

    ~Samurai()
    {
        cout<<"Samurai " << name <<" deleted "<<endl;
    }

    void  printSamuraiDescription()
    {
        cout<<"Samurai name: "<< name <<" Duels: "<<numberOfDuels<<" Wins: "<<numberOfWins<<"  Injuries: "<<numberOfInjuries<<endl;
    }

    void pickWeapon(Weapon &a)
    {
        if (age<18)
        {
            setSamuraiWeapon("Wooden Sword");
            cout<<samuraiWeapon<<endl;
        }
        else
        {
        setSamuraiWeapon(a.getWeaponName());
            cout<<samuraiWeapon<<endl;
        }
    }

    //getters

    string getName()
    {
        return name;
    }

    string getSamuraiWeapon()
    {
        return samuraiWeapon;
    }

    int getnumberOfWins()
    {
        return numberOfWins;
    }

    int getnumberOfInjuries()
    {
        return numberOfInjuries;
    }

    int getnumberOfDuels()
    {
        return numberOfDuels;
    }

    int getAge()
    {
        return age;
    }

    //setters

    void setName(string a)
    {
         name=a;
    }

    void setSamuraiWeapon(string e)
    {
        samuraiWeapon=e;
    }

    void setnumberOfWins(int b)
    {
         numberOfWins=b;
    }

    void setnumberOfInjuries(int c)
    {
         numberOfInjuries=c;
    }

    void setnumberOfDuels(int d)
    {
         numberOfDuels=d;
    }

    void setAge(int f)
    {
        age=f;
    }

    //friend fuction
    friend void duel(Samurai &a, Samurai &b, bool winner);
    friend void duelForYoungSamurais(Samurai &a, Samurai &b);

};

void duelForYoungSamurais(Samurai &a, Samurai &b)
{
    if (a.age>18 || b.age>18)
    {
        cout<<"Invalid duel"<<endl;
    }

    if (a.samuraiWeapon!="Wooden Sword" || b.samuraiWeapon!="Wooden Sword")
    {
        cout<<"Duel postponed"<<endl;
    }
    else
    {
        cout<<a.getName()<<" duels "<<b.getName()<<endl;
    }

}

void duel(Samurai &a, Samurai &b, bool winner)
{
    a.setnumberOfDuels(a.numberOfWins+1);
    b.setnumberOfDuels(b.numberOfWins+1);

    if (winner==true)
    {
        cout<<"Samurai a is winner "<<endl;
        a.setnumberOfWins(a.numberOfWins+1);
        b.setnumberOfInjuries(b.numberOfInjuries+1);
        if(a.numberOfWins>=10) cout<<"Samurai a is duelist"<<endl;
    }
    else
    {
        cout<<"Samurai b is winner "<<endl;
        b.setnumberOfWins(b.numberOfWins+1);
        a.setnumberOfInjuries(a.numberOfInjuries+1);
        if(b.numberOfWins>=10) cout<<"Samurai b is duelist"<<endl;
    }

}

int main()
{
    Samurai a("Giorgos",9,0,0,18);
    Samurai b("Giannis",1,2,3,13);
    Weapon a1("Rock");
    a.pickWeapon(a1);
    b.pickWeapon(a1);
    duelForYoungSamurais(a,b);
    duel(a,b,true);
    a.printSamuraiDescription();
    b.printSamuraiDescription();

}


来源: stackexchange

问:
Pulling external data to next empty row as static, then repeating with next empty row? (Backing up Google Sheet data to Excel)
I have an Excel sheet that I would like to serve as the backup of a Google sheet, which I'll be clearing out periodically to prevent it from slowing down. I'm attempting to write a macro which, after a set period of time, will find the next empty row in the Excel sheet, activate the cell in column "A", and import the data from the Google Sheet. I don't want to "refresh" the data in Excel, because the plan is to delete the data in the Google Sheet every so often while the Excel sheet serves as a continuous record. I would simply like to pull the current Google Sheet data into the first cell of the next empty row, and schedule this to repeat.

Here's what I've been trying:

```<code>Sub addData()
newCell = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Address
MsgBox newCell
Sheet1.QueryTables.Add(Connection:= _
        "URL;googleSheetURL" _
        , Destination:=Range(newCell))
        .PostText = "transaction-data_1"
        .Name = False
        .FieldNames = False
        .RefreshStyle = xlInsertDeleteCells
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .HasAutoFormat = False
        .RefreshOnFileOpen = 2
        .BackgroundQuery = False
        .TablesOnlyFromHTML = True
        .SaveData = True
        .Refresh BackgroundQuery:=False
        .UseListObject = False
    End With
End Sub
</code>```

Where googleSheetURL is replaced with the published link of the sheet.

I just keep getting errors, debug mode highlights the Refresh BackgroundQuery line. I disabled background refresh because I didn't want the queries to update once I pulled them. Does anyone have any insight?

答:
This code doesn't compile. You're missing a With in front of Sheet1:

```<code>Sub addData()
    newCell = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Address

    With Sheet1.QueryTables.Add(Connection:= _
        "URL;googleSheetURL" _
        , Destination:=Range(newCell))
        .PostText = "transaction-data_1"
        .Name = False
        .FieldNames = False
        .RefreshStyle = xlInsertDeleteCells
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .HasAutoFormat = False
        .RefreshOnFileOpen = 2
        .BackgroundQuery = False
        .TablesOnlyFromHTML = True
        .SaveData = True
        .Refresh BackgroundQuery:=False
        .UseListObject = False
    End With
End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an Excel sheet that I would like to serve as the backup of a Google sheet, which I'll be clearing out periodically to prevent it from slowing down. I'm attempting to write a macro which, after a set period of time, will find the next empty row in the Excel sheet, activate the cell in column "A", and import the data from the Google Sheet. I don't want to "refresh" the data in Excel, because the plan is to delete the data in the Google Sheet every so often while the Excel sheet serves as a continuous record. I would simply like to pull the current Google Sheet data into the first cell of the next empty row, and schedule this to repeat.

Here's what I've been trying:

Sub addData()
newCell = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Address
MsgBox newCell
Sheet1.QueryTables.Add(Connection:= _
        "URL;googleSheetURL" _
        , Destination:=Range(newCell))
        .PostText = "transaction-data_1"
        .Name = False
        .FieldNames = False
        .RefreshStyle = xlInsertDeleteCells
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .HasAutoFormat = False
        .RefreshOnFileOpen = 2
        .BackgroundQuery = False
        .TablesOnlyFromHTML = True
        .SaveData = True
        .Refresh BackgroundQuery:=False
        .UseListObject = False
    End With
End Sub

Where googleSheetURL is replaced with the published link of the sheet.

I just keep getting errors, debug mode highlights the Refresh BackgroundQuery line. I disabled background refresh because I didn't want the queries to update once I pulled them. Does anyone have any insight?

Body:
This code doesn't compile. You're missing a With in front of Sheet1:

Sub addData()
    newCell = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Address

    With Sheet1.QueryTables.Add(Connection:= _
        "URL;googleSheetURL" _
        , Destination:=Range(newCell))
        .PostText = "transaction-data_1"
        .Name = False
        .FieldNames = False
        .RefreshStyle = xlInsertDeleteCells
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .HasAutoFormat = False
        .RefreshOnFileOpen = 2
        .BackgroundQuery = False
        .TablesOnlyFromHTML = True
        .SaveData = True
        .Refresh BackgroundQuery:=False
        .UseListObject = False
    End With
End Sub


问:
Java: Anybody have an example project using google protocol buffers over a network?
I'm not sure how to send messages with google protocol buffers to start, so an example with how to build a message, send it, and the reconstruct the message would be awesome.</p>

答: The outcome of a protobuf is a byte array that can be transported over many protocols like HTTP (using POST). If you want a low level RPC mechanism then there are many RPC plugins available. You can find the list here. You can also get the example usage on their respective websites.</p>

ContentLicense: CC BY-SA 2.5


问:
Read msi file in perl
I would like to read an msi file. I use the library Win32 :: MSI :: HighLevel but this one sends me undef all the time.

My code:

```<code>use strict;
use warnings FATAL => 'all';
use Win32::MSI::DB qw(Win32::MSI::DB::MSIDBOPEN_READONLY);
use Win32::MSI::HighLevel;
use Data::Dumper;
my $msi = Win32::MSI::HighLevel->new (-file => "Firefox.msi", -mode => $Win32::MSI::DB::MSIDBOPEN_READONLY) or die "error $!";
my $productCode = $msi->getProductCode;
my $product = $msi->getProduct;

print Dumper  $productCode;
</code>```

The $product returns ': - ' and $productCode is undef .

I have checked the information of msi file in the Windows file properties and verified the information are inside. I have tried the code with another msi file and I have the same problem.

答:
The ProductCode of an MSI file is in a table called Properties inside the MSI file, which is a relational database. It's not a file property. This post should help:

PowerShell: Get the MSI product code out of a MSI file without installing?

because it outlines the various calls that need to be made, which are basically to open the database, do an OpenView with the SQL query ""SELECT Value FROM Property WHERE Property = 'ProductCode' and so on, and similar here:

https://codereview.stackexchange.com/questions/143304/get-productcode-from-msi-file-using-dtf-in-c

Title: Read msi file in perl

Body:
I would like to read an msi file. I use the library Win32 :: MSI :: HighLevel but this one sends me undef all the time.

My code:

use strict;
use warnings FATAL => 'all';
use Win32::MSI::DB qw(Win32::MSI::DB::MSIDBOPEN_READONLY);
use Win32::MSI::HighLevel;
use Data::Dumper;
my $msi = Win32::MSI::HighLevel->new (-file => "Firefox.msi", -mode => $Win32::MSI::DB::MSIDBOPEN_READONLY) or die "error $!";
my $productCode = $msi->getProductCode;
my $product = $msi->getProduct;

print Dumper  $productCode;

The $product returns ': - ' and $productCode is undef .

I have checked the information of msi file in the Windows file properties and verified the information are inside. I have tried the code with another msi file and I have the same problem.


问:
JavaCard Cannot Delete Application - return 6985 (CONDITIONS_NOT_SATISFIED)
I am trying to delete a java card application and delete return 6985, what's wrong? The same code works with other card...</p>

```<code>SELECT CARD MANAGER
   -> [00 A4 04 00 00]
   <- [6F 10 84 08 A0 00 00 01 51 00 00 00 A5 04 9F 65 01 FF 90 00]
   Tag 6F: File Control Information (FCI) Template:
8408A000000151000000A5049F6501FF
      Tag 84: Executable Module AID: A000000151000000
      Tag A5: File Control Information (FCI) Proprietary Template: 9F6501FF
         Tag 9F65: Unknown: FF

INITIALIZE UPDATE
   -> [80 50 00 00 08 37 80 A7 1F 74 AA 5F 3A 00]
   <- [00 00 00 00 00 00 00 00 00 00 FF 02 00 13 88 4A B6 A8 4A 18 71 29 04
7E E3 B4 5E DC 90 00]
   Key diversification data: 00000000000000000000
   Key information: FF02
   Card challenge: 0013884AB6A84A18
   Card cryptogram: 7129047EE3B45EDC

EXTERNAL AUTHENTICATE
   -> [84 82 01 00 10 3A 10 F0 30 A2 F2 E4 64 1D 7B 7E E0 FA 68 A2 1E 00]
   <- [90 00]

DELETE
   -> [84 E4 00 80 11 4F 07 A0 00 00 00 03 10 10 03 0D 24 5B A7 4B E2 B5 00]
   P2:
      Delete object and related object
   Tag 4F: AID: A0000000031010
   <- [69 85] CONDITIONS_NOT_SATISFIED
</code>```

答:
You seem to try to delete a VISA application as the RID part of the AID reads A000000003. Furthermore, it says: and related objects which leads me to believe that you also try to delete the module (i.e. the load package, the code). This package could be in ROM, which means it may not be eligible for removal.

Even if you would be able to delete it you would probably not free up any memory as ROM is, well, ROM; you would just remove any reference to it. It may also be that this is simply not an application that you are allowed to remove.

You may have more luck with other AID's or modules that are in EEPROM or flash. There are also "all flash" cards out there where no ROM is present (probably except a small boot ROM, you have to start somewhere).

Body:
I am trying to delete a java card application and delete return 6985, what's wrong? The same code works with other card...

SELECT CARD MANAGER
   -> [00 A4 04 00 00]
   <- [6F 10 84 08 A0 00 00 01 51 00 00 00 A5 04 9F 65 01 FF 90 00]
   Tag 6F: File Control Information (FCI) Template:
8408A000000151000000A5049F6501FF
      Tag 84: Executable Module AID: A000000151000000
      Tag A5: File Control Information (FCI) Proprietary Template: 9F6501FF
         Tag 9F65: Unknown: FF

INITIALIZE UPDATE
   -> [80 50 00 00 08 37 80 A7 1F 74 AA 5F 3A 00]
   <- [00 00 00 00 00 00 00 00 00 00 FF 02 00 13 88 4A B6 A8 4A 18 71 29 04
7E E3 B4 5E DC 90 00]
   Key diversification data: 00000000000000000000
   Key information: FF02
   Card challenge: 0013884AB6A84A18
   Card cryptogram: 7129047EE3B45EDC

EXTERNAL AUTHENTICATE
   -> [84 82 01 00 10 3A 10 F0 30 A2 F2 E4 64 1D 7B 7E E0 FA 68 A2 1E 00]
   <- [90 00]

DELETE
   -> [84 E4 00 80 11 4F 07 A0 00 00 00 03 10 10 03 0D 24 5B A7 4B E2 B5 00]
   P2:
      Delete object and related object
   Tag 4F: AID: A0000000031010
   <- [69 85] CONDITIONS_NOT_SATISFIED


问:
Combine master-detail databinding
I have created data sources from my objects in my project, some of which have other objects as members. When I want to bind a some objects to a data grid I would like to display some of the values from the member objects in the data grid as well but the examples I have come across seem to use an entire other datagrid or controls to display these member object values.

How can I combine these values into one data grid? (Preferably without creating a wrapping class)
Can I achieve this with LINQ somehow?

Your help is greatly appreciated.

Thanks

P.S. C# or VB examples will do.

答:
I faced the same problem recently, and solved it using the third approach suggested above. The DeepBindingList below is similar to a regular BindingList, but with two enhancements:

1) It traverses the sub-properties of each property and exposes them all as bindable properties.

2) It adds support for sorting.

Use in any way you like, I hope it's useful.

```<code>using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Text;

namespace DeepBindingList
{
    /// Extends the BindingList to provide sorting and deep property
    /// binding (e.g. Address.Street).
    public class DeepBindingList<T> : BindingList<T>, ITypedList
    {
        //-----------------------------------------------------------------------
        #region ** IBindingList overrides (to provide sorting)

        PropertyDescriptor _sort;
        ListSortDirection _direction;

        protected override bool IsSortedCore
        {
            get { return _sort != null; }
        }
        protected override void RemoveSortCore()
        {
            _sort = null;
        }
        protected override ListSortDirection SortDirectionCore
        {
            get { return _direction; }
        }
        protected override PropertyDescriptor SortPropertyCore
        {
            get { return _sort; }
        }
        protected override bool SupportsSortingCore
        {
            get { return true; }
        }
        protected override void ApplySortCore(PropertyDescriptor pd, ListSortDirection direction)
        {
            // get list to sort
            var items = this.Items as List<T>;

            // apply the sort
            if (items != null)
            {
                var pc = new PropertyComparer<T>(pd, direction);
                items.Sort(pc);
            }

            // save new settings and notify listeners
            _sort = pd;
            _direction = direction;
            this.OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
        }

        // PropertyComparer (used to sort the list)
        class PropertyComparer<TC> : IComparer<TC>
        {
            PropertyDescriptor _pd;
            ListSortDirection _direction;
            public PropertyComparer(PropertyDescriptor pd, ListSortDirection direction)
            {
                _pd = pd;
                _direction = direction;
            }
            public int Compare(TC x, TC y)
            {
                try
                {
                    var v1 = _pd.GetValue(x) as IComparable;
                    var v2 = _pd.GetValue(y) as IComparable;

                    int cmp =
                        v1 == null && v2 == null ? 0 :
                        v1 == null ? +1 :
                        v2 == null ? -1 :
                        v1.CompareTo(v2);

                    return _direction == ListSortDirection.Ascending ? +cmp : -cmp;
                }
                catch
                {
                    return 0; // comparison failed...
                }
            }
        }

        #endregion

        //-----------------------------------------------------------------------
        #region ** ITypedList (to expose inner properties)

        public PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors)
        {
            var list = new List<PropertyDescriptor>();
            foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(typeof(T)))
            {
                AddProperties(pd, null, list);
            }
            return new PropertyDescriptorCollection(list.ToArray());
        }
        void AddProperties(PropertyDescriptor pd, PropertyDescriptor parent, List<PropertyDescriptor> list)
        {
            // add this property
            pd = new DeepPropertyDescriptor(pd, parent);
            list.Add(pd);

            // and subproperties for non-value types
            if (!pd.PropertyType.IsValueType && pd.PropertyType != typeof(string))
            {
                foreach (PropertyDescriptor sub in TypeDescriptor.GetProperties(pd.PropertyType))
                {
                    AddProperties(sub, pd, list);
                }
            }
        }
        public string GetListName(PropertyDescriptor[] listAccessors)
        {
            return null;
        }

        // property descriptor with support for sub properties (e.g. Address.Street)
        class DeepPropertyDescriptor : PropertyDescriptor
        {
            PropertyDescriptor _pd;
            PropertyDescriptor _parentPD;

            public DeepPropertyDescriptor(PropertyDescriptor pd, PropertyDescriptor parentPd)
                : base(pd.Name, null)
            {
                _pd = pd;
                _parentPD = parentPd;
            }
            public override string Name
            {
                get
                {
                    return _parentPD != null
                        ? string.Format("{0}.{1}", _parentPD.Name, _pd.Name)
                        : _pd.Name;
                }
            }
            public override bool IsReadOnly
            {
                get { return _pd.IsReadOnly; }
            }
            public override void ResetValue(object component)
            {
                _pd.ResetValue(component);
            }
            public override bool CanResetValue(object component)
            {
                return _pd.CanResetValue(component);
            }
            public override bool ShouldSerializeValue(object component)
            {
                return _pd.ShouldSerializeValue(component);
            }
            public override Type ComponentType
            {
                get { return _pd.ComponentType; }
            }
            public override Type PropertyType
            {
                get { return _pd.PropertyType; }
            }
            public override object GetValue(object component)
            {
                if (_parentPD != null)
                {
                    component = _parentPD.GetValue(component);
                }
                return _pd.GetValue(component);
            }
            public override void SetValue(object component, object value)
            {
                _pd.SetValue(_parentPD.GetValue(component), value);
                OnValueChanged(component, EventArgs.Empty);
            }
        }

        #endregion
    }
}
</code>```

Title: Combine master-detail databinding

Body:
I faced the same problem recently, and solved it using the third approach suggested above. The DeepBindingList below is similar to a regular BindingList, but with two enhancements:

1) It traverses the sub-properties of each property and exposes them all as bindable properties.

2) It adds support for sorting.

Use in any way you like, I hope it's useful.

using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Text;

namespace DeepBindingList
{
    /// Extends the BindingList to provide sorting and deep property
    /// binding (e.g. Address.Street).
    public class DeepBindingList<T> : BindingList<T>, ITypedList
    {
        //-----------------------------------------------------------------------
        #region ** IBindingList overrides (to provide sorting)

        PropertyDescriptor _sort;
        ListSortDirection _direction;

        protected override bool IsSortedCore
        {
            get { return _sort != null; }
        }
        protected override void RemoveSortCore()
        {
            _sort = null;
        }
        protected override ListSortDirection SortDirectionCore
        {
            get { return _direction; }
        }
        protected override PropertyDescriptor SortPropertyCore
        {
            get { return _sort; }
        }
        protected override bool SupportsSortingCore
        {
            get { return true; }
        }
        protected override void ApplySortCore(PropertyDescriptor pd, ListSortDirection direction)
        {
            // get list to sort
            var items = this.Items as List<T>;

            // apply the sort
            if (items != null)
            {
                var pc = new PropertyComparer<T>(pd, direction);
                items.Sort(pc);
            }

            // save new settings and notify listeners
            _sort = pd;
            _direction = direction;
            this.OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
        }

        // PropertyComparer (used to sort the list)
        class PropertyComparer<TC> : IComparer<TC>
        {
            PropertyDescriptor _pd;
            ListSortDirection _direction;
            public PropertyComparer(PropertyDescriptor pd, ListSortDirection direction)
            {
                _pd = pd;
                _direction = direction;
            }
            public int Compare(TC x, TC y)
            {
                try
                {
                    var v1 = _pd.GetValue(x) as IComparable;
                    var v2 = _pd.GetValue(y) as IComparable;

                    int cmp =
                        v1 == null && v2 == null ? 0 :
                        v1 == null ? +1 :
                        v2 == null ? -1 :
                        v1.CompareTo(v2);

                    return _direction == ListSortDirection.Ascending ? +cmp : -cmp;
                }
                catch
                {
                    return 0; // comparison failed...
                }
            }
        }

        #endregion

        //-----------------------------------------------------------------------
        #region ** ITypedList (to expose inner properties)

        public PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors)
        {
            var list = new List<PropertyDescriptor>();
            foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(typeof(T)))
            {
                AddProperties(pd, null, list);
            }
            return new PropertyDescriptorCollection(list.ToArray());
        }
        void AddProperties(PropertyDescriptor pd, PropertyDescriptor parent, List<PropertyDescriptor> list)
        {
            // add this property
            pd = new DeepPropertyDescriptor(pd, parent);
            list.Add(pd);

            // and subproperties for non-value types
            if (!pd.PropertyType.IsValueType && pd.PropertyType != typeof(string))
            {
                foreach (PropertyDescriptor sub in TypeDescriptor.GetProperties(pd.PropertyType))
                {
                    AddProperties(sub, pd, list);
                }
            }
        }
        public string GetListName(PropertyDescriptor[] listAccessors)
        {
            return null;
        }

        // property descriptor with support for sub properties (e.g. Address.Street)
        class DeepPropertyDescriptor : PropertyDescriptor
        {
            PropertyDescriptor _pd;
            PropertyDescriptor _parentPD;

            public DeepPropertyDescriptor(PropertyDescriptor pd, PropertyDescriptor parentPd)
                : base(pd.Name, null)
            {
                _pd = pd;
                _parentPD = parentPd;
            }
            public override string Name
            {
                get
                {
                    return _parentPD != null
                        ? string.Format("{0}.{1}", _parentPD.Name, _pd.Name)
                        : _pd.Name;
                }
            }
            public override bool IsReadOnly
            {
                get { return _pd.IsReadOnly; }
            }
            public override void ResetValue(object component)
            {
                _pd.ResetValue(component);
            }
            public override bool CanResetValue(object component)
            {
                return _pd.CanResetValue(component);
            }
            public override bool ShouldSerializeValue(object component)
            {
                return _pd.ShouldSerializeValue(component);
            }
            public override Type ComponentType
            {
                get { return _pd.ComponentType; }
            }
            public override Type PropertyType
            {
                get { return _pd.PropertyType; }
            }
            public override object GetValue(object component)
            {
                if (_parentPD != null)
                {
                    component = _parentPD.GetValue(component);
                }
                return _pd.GetValue(component);
            }
            public override void SetValue(object component, object value)
            {
                _pd.SetValue(_parentPD.GetValue(component), value);
                OnValueChanged(component, EventArgs.Empty);
            }
        }

        #endregion
    }
}


问:
What is the difference between FlxTypedButton<T> and FlxButton in Haxe and Haxeflixel
I have been coding in haxe and haxeflixel, but when I looked at it's API for buttons I saw there were two different types. http://api.haxeflixel.com/flixel/ui/FlxButton.html , http://api.haxeflixel.com/flixel/ui/FlxTypedButton.html
When I viewed examples online, they declared a button as

```<code>    var button:FlxButton = new FlxButton(50, 50, "Click here", OnClickButton);
    add(button);
</code>```

but what is the difference between a typedbutton and button?
What does the "typed" prefix even mean?

(Additionally, what is special about the sprite button. http://api.haxeflixel.com/flixel/ui/FlxSpriteButton.html )

Please and thank you.

答:
Just from looking at the documentation and source, this is what I'm getting: FlxButton is the simplest to use. It's used the most often because of that. All you need is a string, a position, and a callback. It requires the least amount of typing.

FlxTypedButton is actually the parent class of FlxButton. It has a lot of the functions that exist in FlxButton, but it also has a type parameter:

```<code>class FlxTypedButton<T:FlxSprite> extends FlxSprite implements IFlxInput
{
    /**
     * The label that appears on the button. Can be any `FlxSprite`.
     */
     public var label(default, set):T;

     // The rest of the class...
}
</code>```

This means that FlxTypedButton's label can have a label that is any type, constrained to objects/classes that inherit from FlxSprite. In the case of FlxButton, that is a FlxText object.

FlxSpriteButton is pretty much the same as FlxButton, but instead of FlxText it is bound to FlxSprite's. The only unique thing it really brings to the table is the createTextLabel function. I don't know why it's a separate class though.

Body:
I have been coding in haxe and haxeflixel, but when I looked at it's API for buttons I saw there were two different types. http://api.haxeflixel.com/flixel/ui/FlxButton.html , http://api.haxeflixel.com/flixel/ui/FlxTypedButton.html
When I viewed examples online, they declared a button as

    var button:FlxButton = new FlxButton(50, 50, "Click here", OnClickButton);
    add(button);

but what is the difference between a typedbutton and button?
What does the "typed" prefix even mean?

(Additionally, what is special about the sprite button. http://api.haxeflixel.com/flixel/ui/FlxSpriteButton.html )

Please and thank you.

Body:
Just from looking at the documentation and source, this is what I'm getting: FlxButton is the simplest to use. It's used the most often because of that. All you need is a string, a position, and a callback. It requires the least amount of typing.

FlxTypedButton is actually the parent class of FlxButton. It has a lot of the functions that exist in FlxButton, but it also has a type parameter:

class FlxTypedButton<T:FlxSprite> extends FlxSprite implements IFlxInput
{
    /**
     * The label that appears on the button. Can be any `FlxSprite`.
     */
     public var label(default, set):T;

     // The rest of the class...
}

This means that FlxTypedButton's label can have a label that is any type, constrained to objects/classes that inherit from FlxSprite. In the case of FlxButton, that is a FlxText object.

FlxSpriteButton is pretty much the same as FlxButton, but instead of FlxText it is bound to FlxSprite's. The only unique thing it really brings to the table is the createTextLabel function. I don't know why it's a separate class though.


问:
LINQ Parent class queries db for fields in child class
I'm using EF 6.1.3 and .NET framework 4.5.2

I'm updating code which uses two classes:

```<code>Public Class Holder
    <Key(), Column(Order:=0)>
    Property Holder_No As Integer?

    <Key(), Column(Order:=1)>
    Property Title_No As Integer?

    Property Family_Name As String
    Property Given_Name_1 As String
    Property Given_Name_2 As String
End Class

Public Class OwnerChange
    Inherits Holder
    Public Property Change_Type As String
    Public Property Change_Date As Date
    Public Property Process_Date As Date?
End Class
</code>```

The Holder class is a 1:1 mapping with a table in the db.

The DbContext only creates a dbSet for the Holder class.

```<code>Public Property Holder As DbSet(Of Holder)
</code>```

When I create a simple query to access data from the holder table in the db, I get column errors for change_type, change_date and process_date.

```<code>Using contextdb = New userContext()
     Dim att1 = (From b In contextdb.Holder
                             Select b).Take(10)
End Using
</code>```

The query seems to think I'm trying to query the parent table for the child class' information.

Why does LINQ request the child's columns from the parent class' table in the database?  Do I need to do something to specify that I only want to retrieve the holder information?

答:
The Entity Framework apparently creates a hierarchy whenever one class is inherited from another.  So, when I was querying for the holder record, it was looking in the holder table for the elements from the OwnerChange class.

What I needed to do was take the holder class and turn it into an abstract class, then inherit it into the two classes I want to access different tables in the database.

```<code>Public MustInherit Class base_class
<Key(), Column(Order:=0)>
Property Holder_No As Integer?

<Key(), Column(Order:=1)>
Property Title_No As Integer?

Property Family_Name As String
Property Given_Name_1 As String
Property Given_Name_2 As String
End Class

Public Class OwnerChange
    Inherits base_class
    Public Property Change_Type As String
    Public Property Change_Date As Date
    Public Property Process_Date As Date?
End Class

Public Class holder
    Inherits base_class
End Class
</code>```

Changing the class hierarchy ultimately solved the problem.

Body:
I'm using EF 6.1.3 and .NET framework 4.5.2

I'm updating code which uses two classes:

Public Class Holder
    <Key(), Column(Order:=0)>
    Property Holder_No As Integer?

    <Key(), Column(Order:=1)>
    Property Title_No As Integer?

    Property Family_Name As String
    Property Given_Name_1 As String
    Property Given_Name_2 As String
End Class

Public Class OwnerChange
    Inherits Holder
    Public Property Change_Type As String
    Public Property Change_Date As Date
    Public Property Process_Date As Date?
End Class

The Holder class is a 1:1 mapping with a table in the db.

The DbContext only creates a dbSet for the Holder class.

Public Property Holder As DbSet(Of Holder)

When I create a simple query to access data from the holder table in the db, I get column errors for change_type, change_date and process_date.

Using contextdb = New userContext()
     Dim att1 = (From b In contextdb.Holder
                             Select b).Take(10)
End Using

The query seems to think I'm trying to query the parent table for the child class' information.

Why does LINQ request the child's columns from the parent class' table in the database?  Do I need to do something to specify that I only want to retrieve the holder information?

Body:
The Entity Framework apparently creates a hierarchy whenever one class is inherited from another.  So, when I was querying for the holder record, it was looking in the holder table for the elements from the OwnerChange class.

What I needed to do was take the holder class and turn it into an abstract class, then inherit it into the two classes I want to access different tables in the database.

Public MustInherit Class base_class
<Key(), Column(Order:=0)>
Property Holder_No As Integer?

<Key(), Column(Order:=1)>
Property Title_No As Integer?

Property Family_Name As String
Property Given_Name_1 As String
Property Given_Name_2 As String
End Class

Public Class OwnerChange
    Inherits base_class
    Public Property Change_Type As String
    Public Property Change_Date As Date
    Public Property Process_Date As Date?
End Class

Public Class holder
    Inherits base_class
End Class

Changing the class hierarchy ultimately solved the problem.


问:
What is the fastest way to count the number of nonzero entries in an __mm256 vector?
I've written an algorithm that does multiple single precision operations in parallel using Intel intrinsic functions. The result of each iteration of my algorithm is the number of nonzero entries in a single 256 bit vector (__m256).

For example:

```<code> 00000000  FFFFFFFF  00000000  00000000  00000000  FFFFFFFF  FFFFFFFF  FFFFFFFF
</code>```

where the result of the iteration is 4.

What is the fastest way to count the number nonzero entries in the vector?

Currently I'm doing something like this:

float results[8];
_mm256_storeu_ps(results, result_vector);

int count = 0;
for (uint32_t idx = 0; idx < 8; ++idx)
{
    if (results[idx] != 0)
    {
        ++count;
    }
}
```

This approach works just fine but I wonder if there is a more efficient way to do it, perhaps one that doesn't involve a store.

答:
The hardware popcnt instruction is your best bet here.  It's fast, and vmovmskps is also very efficient for giving you the high bit of each element as an integer bitmask.  (compare / movemask is a standard way to branch on a vector compare result, or use it to index a lookup table of shuffle masks).

movemask / popcnt can be useful when left-packing, to increment a destination pointer by the number of elements you stored (after shuffling).

```<code>#include <immintrin.h>

// use only with compare-results.
// or to count elements with their sign-bit set
unsigned count_true(__m256 v) {
    unsigned mask = _mm256_movemask_ps(v);
    return _mm_popcnt_u32(mask);
}
</code>```

popcnt has a separate feature-bit from AVX, so in theory there could be a CPU (or virtual machine) with AVX but not hardware popcnt, but in practice I wouldn't worry about it.  (popcnt was introduced with SSE4.2, and AVX implies SSE4.2)

Even if you want the result in a vector register for something, vmovmskps / popcnt / movd is probably a better sequence than horizontally adding the 0 / -1 elements with integer adds.  That would take 3 shuffle/add steps to reduce 8 elements down to 1, and you'd have a negative sum.

I mostly mention this because treating compare results as integer 0 / -1 is useful in some cases.  e.g. to conditionally increment a vector of counters, cmpps / psubd does the trick.  (0 + x = x, so the false elements are unchanged.)

Body:
I've written an algorithm that does multiple single precision operations in parallel using Intel intrinsic functions. The result of each iteration of my algorithm is the number of nonzero entries in a single 256 bit vector (__m256).

For example:

 00000000  FFFFFFFF  00000000  00000000  00000000  FFFFFFFF  FFFFFFFF  FFFFFFFF

where the result of the iteration is 4.

What is the fastest way to count the number nonzero entries in the vector?

Currently I'm doing something like this:

float results[8];
_mm256_storeu_ps(results, result_vector);

int count = 0;
for (uint32_t idx = 0; idx < 8; ++idx)
{
    if (results[idx] != 0)
    {
        ++count;
    }
}

This approach works just fine but I wonder if there is a more efficient way to do it, perhaps one that doesn't involve a store.

Body:
The hardware popcnt instruction is your best bet here.  It's fast, and vmovmskps is also very efficient for giving you the high bit of each element as an integer bitmask.  (compare / movemask is a standard way to branch on a vector compare result, or use it to index a lookup table of shuffle masks).

movemask / popcnt can be useful when left-packing, to increment a destination pointer by the number of elements you stored (after shuffling).

#include <immintrin.h>

// use only with compare-results.
// or to count elements with their sign-bit set
unsigned count_true(__m256 v) {
    unsigned mask = _mm256_movemask_ps(v);
    return _mm_popcnt_u32(mask);
}

popcnt has a separate feature-bit from AVX, so in theory there could be a CPU (or virtual machine) with AVX but not hardware popcnt, but in practice I wouldn't worry about it.  (popcnt was introduced with SSE4.2, and AVX implies SSE4.2)

Even if you want the result in a vector register for something, vmovmskps / popcnt / movd is probably a better sequence than horizontally adding the 0 / -1 elements with integer adds.  That would take 3 shuffle/add steps to reduce 8 elements down to 1, and you'd have a negative sum.

I mostly mention this because treating compare results as integer 0 / -1 is useful in some cases.  e.g. to conditionally increment a vector of counters, cmpps / psubd does the trick.  (0 + x = x, so the false elements are unchanged.)


问:
Contents from text file are rearranged when using hashmap
I have to print out the top 5 contents from a txt file using a HashMap.
Here is a sample of what is in the text file.

A01 Web app

A02 Engagement

A03 Embedding

A04 Impressions

A05 Influencer

A06 Mention

A07 Microblogging

A08 Organic

A09 Reach

A10 Social graph

A11 User-generated content

A12 Affiliate marketing

A13 Bounce rate

A14 Call to Action

A15 Click through rate

etc....

Here is what i have so far:

```<code> final int assumedLineLength = 16;
       File file = new File("src/hw7p1/Acronyms.txt");
     try {
    Scanner scan = new Scanner(file);
     HashMap<String, String> hashMap = new HashMap<String, String>((int)(file.length() / assumedLineLength) * 2);

    while(scan.hasNextLine()) {
        String[] columns = scan.nextLine().split(" ");
        hashMap.put(columns[0], columns[1]);

    }

    for (String key : hashMap.keySet()) {

    System.out.println(key +" " + hashMap.get(key));}

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

}
     }}
</code>```

This is what I am getting for my output:

```<code> A87 Big
 A88 Data
 A01 Web
 A89 Database
 A02 Engagement
 A03 Embedding
 A04 Impressions
 A05 Influencer
 A06 Mention
 A07 Microblogging
 A08 Organic
 A09 Reach
 A90 Data
 A91 Data
 A92 Relational
 A93 Hybrid
 A94 IDE
 A95 Native
 A96 NFC
 A97 Responsive
 A10 Social
 A98 SDK
 A11 User-generated
 A99 Content
</code>```

For some reason it is mixing some of the out put around when it is suppose to look the example above. Any help would be greatly appreciated. Thank you

答:
I would Suggest using a LinkedHashMap as it preserves the order of input</p>

```<code> LinkedHashMap<String, String> hashMap = new LinkedHashMap<String, String>((int)(file.length() / assumedLineLength) * 2);
</code>```

Body:
I have to print out the top 5 contents from a txt file using a HashMap.
Here is a sample of what is in the text file.

A01 Web app

A02 Engagement

A03 Embedding

A04 Impressions

A05 Influencer

A06 Mention

A07 Microblogging

A08 Organic

A09 Reach

A10 Social graph

A11 User-generated content

A12 Affiliate marketing

A13 Bounce rate

A14 Call to Action

A15 Click through rate

etc....

Here is what i have so far:

 final int assumedLineLength = 16;
       File file = new File("src/hw7p1/Acronyms.txt");
     try {
    Scanner scan = new Scanner(file);
     HashMap<String, String> hashMap = new HashMap<String, String>((int)(file.length() / assumedLineLength) * 2);

    while(scan.hasNextLine()) {
        String[] columns = scan.nextLine().split(" ");
        hashMap.put(columns[0], columns[1]);

    }

    for (String key : hashMap.keySet()) {

    System.out.println(key +" " + hashMap.get(key));}

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

}
     }}

This is what I am getting for my output:

 A87 Big
 A88 Data
 A01 Web
 A89 Database
 A02 Engagement
 A03 Embedding
 A04 Impressions
 A05 Influencer
 A06 Mention
 A07 Microblogging
 A08 Organic
 A09 Reach
 A90 Data
 A91 Data
 A92 Relational
 A93 Hybrid
 A94 IDE
 A95 Native
 A96 NFC
 A97 Responsive
 A10 Social
 A98 SDK
 A11 User-generated
 A99 Content

For some reason it is mixing some of the out put around when it is suppose to look the example above. Any help would be greatly appreciated. Thank you

Body:
I would Suggest using a LinkedHashMap as it preserves the order of input

 LinkedHashMap<String, String> hashMap = new LinkedHashMap<String, String>((int)(file.length() / assumedLineLength) * 2);


问:
CSS - Display: Inline-block issue
I'm trying to debug a display problem shown below:
Here is the HTML:

```<code><span class="pw_brand_product_list"><div class="wb-posted_in">Brand:</div><a href="https://www.google.com">My First Brand</a></span>
</code>```

and here is the CSS:

```<code> .wb-posted_in {display:inline-block; margin:5px}
</code>```

When I put all this into JSFiddle, it shows properly "Brand: My First Brand" however, when I actually implement this onto my website, it doesn't seem to display properly it still shows as:

Brand:

My First Brand

Can anyone shed some light on this? I'm assuming it's some very beginners mistake? I even tried to use !important and it still doesn't apply correctly.

答: I took a look at the page you linked. It seems that .wb-posted_in has a width: 100%. Changing this with width: auto seems to have fixed the issue.

Title: CSS - Display: Inline-block issue

Body:
I'm trying to debug a display problem shown below:
Here is the HTML:

Brand:
My First Brand

and here is the CSS:

 .wb-posted_in {display:inline-block; margin:5px}

When I put all this into JSFiddle, it shows properly "Brand: My First Brand" however, when I actually implement this onto my website, it doesn't seem to display properly it still shows as:

Brand:

My First Brand

Can anyone shed some light on this? I'm assuming it's some very beginners mistake? I even tried to use !important and it still doesn't apply correctly.


问:
Slow data structures in multiprocessing Python library
I am trying to make simple computations for large data structures with multiprocessing library. It is something that I need for my thesis, so please don't be stern for me.

When I decided to divide my computations for multiple "workers", "threads", "processes" or call it as you want, I started looking into python docs to find what I need and I found two modules, 'threading' and 'multiprocessing'. After reading, I decided to use 'multiprocessing' cause it looks like something I need.

The problem is that with multiple workers (processes) my computations are much slower. First thought was related to size of my input data. I understand that for small data, 'cost' of running threads is much bigger than simple computation, but for larger structures efficiency should growth.

I was really supriced that my computation (for example 2D Rosenbrock) is few times faster for iterative algorithm than with computation made with few processes. And computation is done for 100k tuples.

I also noticed that multiprocessing.Queue access is few times slower than access to collections.deque, but I really need to have this computation is some kind of "shared memory" or something similar.

Can someone explain me where is the problem? Is it Python so much efficient that it's not worth to compute it with multi processes? Do I use proper data structures? Can I change something in my perception of multiprocessing? Or maybe even I measure it in bad way? I really appreciate for any clue how I can speed it up.

Full code below

```<code>#!/usr/bin/python
import multiprocessing
from timeit import default_timer as timer
import random
import collections

class Worker(multiprocessing.Process):
    counter = 0
    def __init__(self, idx, from_queue):
        super(Worker, self).__init__()
        self.from_queue = from_queue
        self.idx = idx

    def run(self):
        print ("Worker started", self.idx)
        for data in iter(self.from_queue.pop, None):
            x_1, x_2 = data
            result = 100*(x_2-x_1**2)**2 + (1-x_1)**2

def main():
    tuple_counts = 100000
    min_x = -5
    max_x = 5

    tuples = multiprocessing.Queue()
    for _ in range(tuple_counts):
        my_tuple = {random.uniform(min_x, max_x), random.uniform(min_x, max_x)}
    tuples.put(my_tuple)

    cores = multiprocessing.cpu_count() - 1

    pops = []
    for _ in range(cores):
        pop = collections.deque()
        pops.append(pop)

    for pop in pops:
        for _ in range(int(tuple_counts/cores)):
            pop.append(tuples.get())

    for _ in range(int(tuple_counts % cores)):
        pops[_].append(tuples.get())

    for pop in pops:
        pop.append(None)

    workers = []
    process_time = 0
    process_time_start = timer()
    for i in range(multiprocessing.cpu_count()-1):
        worker = Worker(i, pops[i])
        workers.append(worker)
        worker.start()
    for worker in workers:
        worker.join()
    process_time_stop = timer()
    process_time += (process_time_stop-process_time_start)
    print("process_time", process_time)

    iter_time = 0
    iter_timer_start = timer()
    for _ in range(tuples.qsize()):
        x_1, x_2 = tuples.qet()
        result = 100*(x_2-x_1**2)**2 + (1-x_1)**2
    iter_timer_stop = timer()
    iter_time += (iter_timer_stop-iter_timer_start)
    print("iter_time", iter_time)

if __name__ == "__main__":
    main()
</code>```

答:
You are passing arguments across process boundaries to do a simple calculation.  I expect it will be extremely slow.

If you need speed, I recommend you fall back to a single threaded implementation, and find a way to vectorize it using numpy. Profile it with cProfile. Attack the hot spots.

A huge benefit of numpy is reduced python overhead (name resolution, looping, etc).

Once you've got the single-threaded approach fast, only then move on to parallel processing.

An added benefit of vectorizing your problem is that numpy unlocks the GIL for lengthy calls, allowing true threading, vs multiprocessing.

Body:
I am trying to make simple computations for large data structures with multiprocessing library. It is something that I need for my thesis, so please don't be stern for me.

When I decided to divide my computations for multiple "workers", "threads", "processes" or call it as you want, I started looking into python docs to find what I need and I found two modules, 'threading' and 'multiprocessing'. After reading, I decided to use 'multiprocessing' cause it looks like something I need.

The problem is that with multiple workers (processes) my computations are much slower. First thought was related to size of my input data. I understand that for small data, 'cost' of running threads is much bigger than simple computation, but for larger structures efficiency should growth.

I was really supriced that my computation (for example 2D Rosenbrock) is few times faster for iterative algorithm than with computation made with few processes. And computation is done for 100k tuples.

I also noticed that multiprocessing.Queue access is few times slower than access to collections.deque, but I really need to have this computation is some kind of "shared memory" or something similar.

Can someone explain me where is the problem? Is it Python so much efficient that it's not worth to compute it with multi processes? Do I use proper data structures? Can I change something in my perception of multiprocessing? Or maybe even I measure it in bad way? I really appreciate for any clue how I can speed it up.

Full code below

#!/usr/bin/python
import multiprocessing
from timeit import default_timer as timer
import random
import collections

class Worker(multiprocessing.Process):
    counter = 0
    def __init__(self, idx, from_queue):
        super(Worker, self).__init__()
        self.from_queue = from_queue
        self.idx = idx

    def run(self):
        print ("Worker started", self.idx)
        for data in iter(self.from_queue.pop, None):
            x_1, x_2 = data
            result = 100*(x_2-x_1**2)**2 + (1-x_1)**2

def main():
    tuple_counts = 100000
    min_x = -5
    max_x = 5

    tuples = multiprocessing.Queue()
    for _ in range(tuple_counts):
        my_tuple = {random.uniform(min_x, max_x), random.uniform(min_x, max_x)}
    tuples.put(my_tuple)

    cores = multiprocessing.cpu_count() - 1

    pops = []
    for _ in range(cores):
        pop = collections.deque()
        pops.append(pop)

    for pop in pops:
        for _ in range(int(tuple_counts/cores)):
            pop.append(tuples.get())

    for _ in range(int(tuple_counts % cores)):
        pops[_].append(tuples.get())

    for pop in pops:
        pop.append(None)

    workers = []
    process_time = 0
    process_time_start = timer()
    for i in range(multiprocessing.cpu_count()-1):
        worker = Worker(i, pops[i])
        workers.append(worker)
        worker.start()
    for worker in workers:
        worker.join()
    process_time_stop = timer()
    process_time += (process_time_stop-process_time_start)
    print("process_time", process_time)

    iter_time = 0
    iter_timer_start = timer()
    for _ in range(tuples.qsize()):
        x_1, x_2 = tuples.qet()
        result = 100*(x_2-x_1**2)**2 + (1-x_1)**2
    iter_timer_stop = timer()
    iter_time += (iter_timer_stop-iter_timer_start)
    print("iter_time", iter_time)

if __name__ == "__main__":
    main()


问:
use fractal to decode from array to custom PHP object
using League/fractal, i am attempting to transform data from array to my PHP object...in the following way

```<code>final class StatusDeserializer extends AbstractTransformer
{

    public function transform(Status $status)
    {
        return new StatusObject(
            $status['name'],
            $status['message']
        );
    }
}
</code>```

my object definition

```<code>final class StatusObject
{

    private $name;
    private $message;

    public function __construct($name, $message)
    {
        $this->name = $name;
        $this->message = $message;
    }
}
</code>```

test implementation here

```<code>$data = [ 'name' => 'foo', 'message' => 'bar' ]
$this->fractalManager->createData($data, new StatusDeserializer());
</code>```

But i get this error

```<code>Fatal error: Uncaught TypeError: Argument 1 passed to League\Fractal\Scope::filterFieldsets() must be of the type array, object given
</code>```

Edit 1

I tried wrapping the array into Fractals collection,  i.e

```<code>$data = new Collection([ 'name' => 'foo', 'message' => 'bar' ]);
</code>```

and it now returns an instance of League\Fractal\Scope instead of my StatusObject instance

Edit 2

Adding ->toArray() brought me back to the first error

```<code>$this->fractalManager->createData($data, new StatusDeserializer())->toArray();
</code>```

see screen shot : https://gmkr.io/s/5a0b755c683d0d77313ff0fa/0

答:
FractalManager wants an instance of ResourceInterface as first argument. So you just want to change your code like this

```<code>$data = new Collection([ 'name' => 'foo', 'message' => 'bar' ]);
$this->fractalManager->createData($data, new StatusDeserializer());
</code>```

Body:
using League/fractal, i am attempting to transform data from array to my PHP object...in the following way

final class StatusDeserializer extends AbstractTransformer
{

    public function transform(Status $status)
    {
        return new StatusObject(
            $status['name'],
            $status['message']
        );
    }
}

my object definition

final class StatusObject
{

    private $name;
    private $message;

    public function __construct($name, $message)
    {
        $this->name = $name;
        $this->message = $message;
    }
}

test implementation here

$data = [ 'name' => 'foo', 'message' => 'bar' ]
$this->fractalManager->createData($data, new StatusDeserializer());

But i get this error

Fatal error: Uncaught TypeError: Argument 1 passed to League\Fractal\Scope::filterFieldsets() must be of the type array, object given

Edit 1

I tried wrapping the array into Fractals collection,  i.e

$data = new Collection([ 'name' => 'foo', 'message' => 'bar' ]);

and it now returns an instance of League\Fractal\Scope instead of my StatusObject instance

Edit 2

Adding ->toArray() brought me back to the first error

$this->fractalManager->createData($data, new StatusDeserializer())->toArray();

see screen shot : https://gmkr.io/s/5a0b755c683d0d77313ff0fa/0

Body:
FractalManager wants an instance of ResourceInterface as first argument. So you just want to change your code like this

$data = new Collection([ 'name' => 'foo', 'message' => 'bar' ]);
$this->fractalManager->createData($data, new StatusDeserializer());


问:
Remove trailing whitespace recursively only at end of file using grep/sed?
Basically, I've got about 1,500 files and the last character of any of these files should not be any type of white space.

How do I check a bunch of files to make sure that they don't end in some form of whitespace?(newline, space, carriage return, tab, etc.)?

答:
A Perl solution:</p>

```<code># command-line arguments are the names of the files to check.
# output is names of files that end with trailing whitespace
for (@ARGV) {
  open F, '<', $_;
  seek F, -1, 2;                # seek to before last char in file
  print "$_\n" if <F> =~ /\s/
}
</code>```

Body:
A Perl solution:

# command-line arguments are the names of the files to check.
# output is names of files that end with trailing whitespace
for (@ARGV) {
  open F, '<', $_;
  seek F, -1, 2;                # seek to before last char in file
  print "$_\n" if <F> =~ /\s/
}


问:
Regular expression works in pythex.org & rubular.com, doesn't work in pyrex.com & in the code. Why?
I have this line

```<code>line = learnAction&subscriberId=604c21a0-0dc5-47da-9a1e-bfb53fa0fab8&
</code>```

and this regex to find  subscriberId=604c21a0-0dc5-47da-9a1e-bfb53fa0fab8

```<code>subscriberId=[\d\w-]*
</code>```

it finds this string in pythex.org & rubular.com and not in pyrex.com and in my code

```<code>(r"""subscriberId=[\d\w-]*""",line)
</code>```

Who's to blame? and what to do?
Thanks!

答:
try re</p>

```<code>import re
line = 'learnAction&subscriberId=604c21a0-0dc5-47da-9a1e-bfb53fa0fab8&'
if re.search("subscriberId=[\d\w-]*", line):
    print 'match'
</code>```

Body:
I have this line

line = learnAction&subscriberId=604c21a0-0dc5-47da-9a1e-bfb53fa0fab8&

and this regex to find  subscriberId=604c21a0-0dc5-47da-9a1e-bfb53fa0fab8

subscriberId=[\d\w-]*

it finds this string in pythex.org & rubular.com and not in pyrex.com and in my code

(r"""subscriberId=[\d\w-]*""",line)

Who's to blame? and what to do?
Thanks!

Body:
try re

import re
line = 'learnAction&subscriberId=604c21a0-0dc5-47da-9a1e-bfb53fa0fab8&'
if re.search("subscriberId=[\d\w-]*", line):
    print 'match'


问:
Count and remove extraneous files (bash)
I am getting stuck on finding a succint solution to the following.

In a given directory, I have the following files:

```<code>10_MIDAP.nii.gz
12_MIDAP.nii.gz
14_MIDAP.nii.gz
16_restAP.nii.gz
18_restAP.nii.gz
</code>```

I am only supposed to have two "MIDAP" files and one "restAP" file. The additional files may not contain the full data, so I need to remove them. These are likely going to be smaller in size and/or the earlier sequence number (e.g., 10).

I know how to count / echo the number of files:

```<code>MIDAP=`find $DATADIR -name "*MIDAP.nii.gz" | wc -l`
RestAP=`find $DATADIR -name "*restAP.nii.gz" | wc -l`

echo "MIDAP files = $MIDAP"
echo "RestAP files = $RestAP"
</code>```

Any suggestions on how to succinctly remove the unneeded files, such that I end up with two "MIDAP" files and one "restAP" (in cases where there are extraneous files)? As of now, imagining it would be something like this...

```<code>if (( $MIDAP > 2 )); then
  ...magic happens
fi
</code>```

Thanks for any advice!

答:
here is an approach

create test files

```<code>$ for i in {1..10}; do touch ${i}_restAP; touch ${i}_MIDAP; done
</code>```

sort based on numbers, and remove the top N-1 (or N-2) files.

```<code>$ find . -name '*restAP*' | sort -V | head -n -1 | xargs rm
$ find . -name '*MIDAP*'  | sort -V | head -n -2 | xargs rm

$ ls -1

10_MIDAP
10_restAP
9_MIDAP
</code>```

you may want to change the sort if based on file size.

Body:
I am getting stuck on finding a succint solution to the following.

In a given directory, I have the following files:

10_MIDAP.nii.gz
12_MIDAP.nii.gz
14_MIDAP.nii.gz
16_restAP.nii.gz
18_restAP.nii.gz

I am only supposed to have two "MIDAP" files and one "restAP" file. The additional files may not contain the full data, so I need to remove them. These are likely going to be smaller in size and/or the earlier sequence number (e.g., 10).

I know how to count / echo the number of files:

MIDAP=`find $DATADIR -name "*MIDAP.nii.gz" | wc -l`
RestAP=`find $DATADIR -name "*restAP.nii.gz" | wc -l`

echo "MIDAP files = $MIDAP"
echo "RestAP files = $RestAP"

Any suggestions on how to succinctly remove the unneeded files, such that I end up with two "MIDAP" files and one "restAP" (in cases where there are extraneous files)? As of now, imagining it would be something like this...

if (( $MIDAP > 2 )); then
  ...magic happens
fi

Thanks for any advice!

Body:
here is an approach

create test files

$ for i in {1..10}; do touch ${i}_restAP; touch ${i}_MIDAP; done

sort based on numbers, and remove the top N-1 (or N-2) files.

$ find . -name '*restAP*' | sort -V | head -n -1 | xargs rm
$ find . -name '*MIDAP*'  | sort -V | head -n -2 | xargs rm

$ ls -1

10_MIDAP
10_restAP
9_MIDAP

you may want to change the sort if based on file size.


问:
Matlab integer strings decoding ... speed optimization
I have the following problem:

I need decode integer sequences "c" to char string messages "m" by following association:

```<code>  numpos = 10 % ( = size(c,2)/2)
  c = [3 4 1 1 4 2 5 2 3 3,1 1 1 1 2 2 2 3 3 3]
</code>```

Each row of "c" represents 2*numpos integers, where first numpos parameters encoded position of

```<code>types = {'a' 'b@2' 'c@6' 'd@10' 'e@11'}
</code>```

and second numpos parameters are applied only if type contains character '@' like this:

```<code>  m = ' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'
</code>```

My current solution is as follows:

```<code>  function m = c2m(c,types)

  numpos = size(c,2)/2;

  F = cellfun(@(f) [' ' f], strrep(types,'@',':%d@'),'unif',0);
  m = arrayfun(@(f,k) sprintf(f{1},k),F(c(:,1:numpos)),c(:,numpos+(1:numpos)),'unif', 0);
  m = arrayfun(@(i) horzcat(m{i,:}), (1:numlines)', 'unif', 0)

  end
</code>```

and the testing code is as follows:

```<code>  numlines = 10;
  c = repmat([3 4 1 1 4 2 5 2 3 3,1 1 1 1 2 2 2 3 3 3],numlines,1);
  types = {'a' 'b@2' 'c@6' 'd@10' 'e@11'};

  m = c2m(c,types);

  m =

    10×1 cell array

      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
</code>```

The code is still too slow for me, I am looking for any speed up. In this case the most significant fraction of CPU time is spent at built-in function "sprintf".

Typical realistic sizes of problem are:

```<code>   numpos ~ 30 ... 60
   numlines ~ 1e4 ... 1e5
</code>```

Any idea?

Body:
I have the following problem:

I need decode integer sequences "c" to char string messages "m" by following association:

  numpos = 10 % ( = size(c,2)/2)
  c = [3 4 1 1 4 2 5 2 3 3,1 1 1 1 2 2 2 3 3 3]

Each row of "c" represents 2*numpos integers, where first numpos parameters encoded position of

types = {'a' 'b@2' 'c@6' 'd@10' 'e@11'}

and second numpos parameters are applied only if type contains character '@' like this:

  m = ' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'

My current solution is as follows:

  function m = c2m(c,types)

  numpos = size(c,2)/2;

  F = cellfun(@(f) [' ' f], strrep(types,'@',':%d@'),'unif',0);
  m = arrayfun(@(f,k) sprintf(f{1},k),F(c(:,1:numpos)),c(:,numpos+(1:numpos)),'unif', 0);
  m = arrayfun(@(i) horzcat(m{i,:}), (1:numlines)', 'unif', 0)

  end

and the testing code is as follows:

  numlines = 10;
  c = repmat([3 4 1 1 4 2 5 2 3 3,1 1 1 1 2 2 2 3 3 3],numlines,1);
  types = {'a' 'b@2' 'c@6' 'd@10' 'e@11'};

  m = c2m(c,types);

  m =

    10×1 cell array

      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}
      {' c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6'}

The code is still too slow for me, I am looking for any speed up. In this case the most significant fraction of CPU time is spent at built-in function "sprintf".

Typical realistic sizes of problem are:

   numpos ~ 30 ... 60
   numlines ~ 1e4 ... 1e5

Any idea?

Body:
In 16b MATLAB shipped some new text functions that make this easy. Also in 16b MATLAB shipped the new string datatype that makes this fast.

 function m = c2m_new(c,types, numlines)

     types = string(types);

     num_values = size(c,2)/2;

     a = c(:,1:num_values);
     b = c(:,(num_values+1):end);

     m = types(a);
     m = insertBefore(m,"@", ":" + b);
     m = join(m,2);
 end

>> numlines = 10;
>> c = repmat([3 4 1 1 4 2 5 2 3 3,1 1 1 1 2 2 2 3 3 3],numlines,1);
>> types = {'a' 'b@2' 'c@6' 'd@10' 'e@11'};
>> c2m_new(c,types,numlines)

ans =

  10×1 string array

    "c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6"
    "c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6"
    "c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6"
    "c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6"
    "c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6"
    "c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6"
    "c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6"
    "c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6"
    "c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6"
    "c:1@6 d:1@10 a a d:2@10 b:2@2 e:2@11 b:3@2 c:3@6 c:3@6"

Looking at performance:

>> numlines = 1E4;
>> c = repmat([3 4 1 1 4 2 5 2 3 3,1 1 1 1 2 2 2 3 3 3],numlines,1);
>> types = {'a' 'b@2' 'c@6' 'd@10' 'e@11'};

% My solution
>> tic; for i = 1:10; c2m_new(c,types, numlines); end; toc
Elapsed time is 0.669311 seconds.

% michalkvasnicka's solution
>> tic; for i = 1:10; c2m(c,types, numlines); end; toc
Elapsed time is 23.643991 seconds.

% gnovice's solution
>> tic; for i = 1:10; c2m_gnovice(c,types, numlines); end; toc
Elapsed time is 8.960392 seconds.


问:
How to join two tables in a one-to-many relation, and keep only one-to-one records?
I have two tables : Folders and References. A folder can have 0 to 2 references (usually 1 or 2).

I have an existing query that search Folders that respect certains conditions. The query must have a new condition : Find only Folders with one reference.

Ideally, to limits change to this old application, the new condition should be within the WHERE clause only (This rule out group by x, having y).

Ex :

```<code>FolderId Name
0        Folder0
1        Folder1
2        Folder2

RefId FolderId Name
0     1        ref1
1     2        ref2
2     2        ref3
</code>```

The output should only contain the FolderId 1

答:
You probably want this:</p>

```<code>select . . .
from folders f join
     (select r.*, count(*) over (partition by folderid) as cnt
      from references r
     ) r
     on f.folderid = r.folderid and cnt = 1;
</code>```

Body:
I have two tables : Folders and References. A folder can have 0 to 2 references (usually 1 or 2).

I have an existing query that search Folders that respect certains conditions. The query must have a new condition : Find only Folders with one reference.

Ideally, to limits change to this old application, the new condition should be within the WHERE clause only (This rule out group by x, having y).

Ex :

FolderId Name
0        Folder0
1        Folder1
2        Folder2

RefId FolderId Name
0     1        ref1
1     2        ref2
2     2        ref3

The output should only contain the FolderId 1

Body:
You probably want this:

select . . .
from folders f join
     (select r.*, count(*) over (partition by folderid) as cnt
      from references r
     ) r
     on f.folderid = r.folderid and cnt = 1;


问:
python gtk poo programming many files?
the code of my program becomes heavier and I would like to separate it into many files.

I found a single tutorial whose code here is:

```<code>#!/usr/bin/env python3
# coding: utf-8

#Box.py
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk,  GdkPixbuf

from BoxBoutton import BoxBoutton

class MainWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self)

        box = Gtk.Box()
        sublayout = BoxBoutton()

        box.pack_start(sublayout, True, True, 0)
        self.add(box)

win = MainWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
</code>```

The second:

```<code>#!/usr/bin/env python3
# coding: utf-8

#BoxBoutton.py

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class BoxBoutton(Gtk.Grid):
    def __init__(self):
        Gtk.Grid.__init__(self)

        btn = Gtk.Button(label="Mon super bouton")
        self.attach(0, 0, 1, 1)
</code>```

but I have this error:

```<code>TypeError: Gtk.Grid.attach() takes exactly 6 arguments (5 given)
</code>```

Thank you very much for your help

答:
You forgot the child in the attach method of Gtk.Grid.

attach(child, left, top, width, height)

try the following:

```<code>self.attach(btn, 0, 0, 1, 1)
</code>```

Title: python gtk poo programming many files?

Body:
the code of my program becomes heavier and I would like to separate it into many files.

I found a single tutorial whose code here is:

#!/usr/bin/env python3
# coding: utf-8

#Box.py
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk,  GdkPixbuf

from BoxBoutton import BoxBoutton

class MainWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self)

        box = Gtk.Box()
        sublayout = BoxBoutton()

        box.pack_start(sublayout, True, True, 0)
        self.add(box)

win = MainWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

The second:

#!/usr/bin/env python3
# coding: utf-8

#BoxBoutton.py

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class BoxBoutton(Gtk.Grid):
    def __init__(self):
        Gtk.Grid.__init__(self)

        btn = Gtk.Button(label="Mon super bouton")
        self.attach(0, 0, 1, 1)

but I have this error:

TypeError: Gtk.Grid.attach() takes exactly 6 arguments (5 given)

Thank you very much for your help

Body:
You forgot the child in the attach method of Gtk.Grid.

attach(child, left, top, width, height)

try the following:

self.attach(btn, 0, 0, 1, 1)


答:
Use the query below to create a temporary table or create a table variable:

```<code>create table #Temp
(
    column_name int
)

insert into #Temp
     SELECT column_name
      FROM table_name
     GROUP BY column_name
    HAVING COUNT(column_name) = 1;
</code>```

Then use the temp table with join to other tables and place the conditions you want.

Title: How to join two tables in a one-to-many relation, and keep only one-to-one records?

Body:
Use the query below to create a temporary table or create a table variable:

create table #Temp
(
    column_name int
)

insert into #Temp
     SELECT column_name
      FROM table_name
     GROUP BY column_name
    HAVING COUNT(column_name) = 1;

Then use the temp table with join to other tables and place the conditions you want.


问:
Can I check for existence of a given element? Does find throw errors when it cannot find any matching elements?
Using Flutter, I'd like to write a test to check for existence of a given element. How do I do that?

Also, will the test throw errors when it cannot find any matching elements?

答:
Yes, you can use the find utility (or more generally the Finder class). Finders are quite powerful in what you can express with them, including checking for existence of widgets in the UI or even check how many of them are there. We have plenty of examples in the framework tests. Here are some examples:

```<code>// check that MyWidget is displayed
expect(find.byType(MyWidget), findOneWidget);

// check that 5 widgets of type MyWidgets are displayed
expect(find.byType(MyWidget), findNWidgets(5));
</code>```

The finder itself does not throw errors, but expect does when the matcher (e.g. findOneWidget) is not satisfied. If you need to interact with the widget rather than simply assert its existence, use one of the methods in WidgetTester, e.g.:

```<code>// Get the layout size of the render object for the given widget
tester.renderObject<RenderBox>(find.byType(Text)).size;
</code>```

Body:
Yes, you can use the find utility (or more generally the Finder class). Finders are quite powerful in what you can express with them, including checking for existence of widgets in the UI or even check how many of them are there. We have plenty of examples in the framework tests. Here are some examples:

// check that MyWidget is displayed
expect(find.byType(MyWidget), findOneWidget);

// check that 5 widgets of type MyWidgets are displayed
expect(find.byType(MyWidget), findNWidgets(5));

The finder itself does not throw errors, but expect does when the matcher (e.g. findOneWidget) is not satisfied. If you need to interact with the widget rather than simply assert its existence, use one of the methods in WidgetTester, e.g.:

// Get the layout size of the render object for the given widget
tester.renderObject<RenderBox>(find.byType(Text)).size;


问:
Connecting to a Database with Java
I'm very confused about how to connect my Java application to a database, any database. I'm not sure where to start. Could anybody provide for me a simple example that might help me along?</p>

答: You're welcome to ask more specific questions, but as the question is quite general, start with the JDBC tutorial from Oracle, http://download.oracle.com/javase/tutorial/jdbc/index.html</p>

Title: Connecting to a Database with Java


问:
Bash, cut word with dot character from string
I have a string:

Log for: squid.log.2017.11.13

I need to cut out squid.log. so that I see:

Log for: 2017.11.13

I tried to cut

```<code>echo "Log for: squid.log.2017.11.13" | cut -d'.' -f3-5
</code>```

But I ended up with:

2017.11.13

How can I get the result I want?

答:
You can use sed to cut the unwanted part:

```<code>echo "Log for: squid.log.2017.11.13" | sed 's/squid\.log\.//'
</code>```

Body:
I have a string:

Log for: squid.log.2017.11.13

I need to cut out squid.log. so that I see:

Log for: 2017.11.13

I tried to cut

echo "Log for: squid.log.2017.11.13" | cut -d'.' -f3-5

But I ended up with:

2017.11.13

How can I get the result I want?

Body:
You can use sed to cut the unwanted part:

echo "Log for: squid.log.2017.11.13" | sed 's/squid\.log\.//'


答:
Use sed to remove the part you don't want:

```<code>echo "Log for: squid.log.2017.11.13" | sed 's/squid\.log\.//'
</code>```

Title: Bash, cut word with dot character from string

Body:
Use sed to remove the part you don't want:

echo "Log for: squid.log.2017.11.13" | sed 's/squid\.log\.//'


问:
Why are there recovered references in my xcode project file?
I have a react native app and just noticed that a few lines were added for Recovered References in my project.pbxproj file in Xcode.

I don't remember adding or deleting any references and the recovered references show libraries that I normally use.  I'm hesitant to check in the local changes to git without knowing what these changes were.  Should I just discard these changes?

Can someone explain why these lines might be added if I didn't add or remove these packages myself?  Does this mean some references were deleted to later be recovered?  The only thing I can think of is that I ran react-native link, would that have made these changes?

This line was added

```<code>E3C5B1001F6966D2006296E1 /* Recovered References */,
</code>```

This entire section is new:

```<code>E3C5B1001F6966D2006296E1 /* Recovered References */ = {
            isa = PBXGroup;
            children = (
                E602D61E379048BF92DC0C6D /* libRNDeviceInfo.a */,
                DEE39860F1B042208F193884 /* libRNVectorIcons.a */,
                C193FEFE9F3B45388016E921 /* libRNShare.a */,
                58B3A26CAB2543FB941C3D8D /* libRNFIRMessaging.a */,
                0BFBA42D662C492EBC1957A0 /* libreact-native-branch.a */,
                4BC248DD95524DE091A41CEC /* libCodePush.a */,
                6DB0E4FE64B34B68A29B262E /* libRNImagePicker.a */,
                E1502CC537D94CF4A5711814 /* libRNAddCalendarEvent.a */,
                065361D30B3F47D4A5101A1D /* libRNAccountKit.a */,
            );
            name = "Recovered References";
            sourceTree = "<group>";
        };
</code>```

答: Fixed it by renaming the file, manually removing everything in the project file related to Recovered References quitting Xcode, and running synx - a useful ruby utility. When I opened it again I could build and everything was fine.

ContentLicense: CC BY-SA 4.0

Body:
I have a react native app and just noticed that a few lines were added for Recovered References in my project.pbxproj file in Xcode.

I don't remember adding or deleting any references and the recovered references show libraries that I normally use.  I'm hesitant to check in the local changes to git without knowing what these changes were.  Should I just discard these changes?

Can someone explain why these lines might be added if I didn't add or remove these packages myself?  Does this mean some references were deleted to later be recovered?  The only thing I can think of is that I ran react-native link, would that have made these changes?

This line was added

E3C5B1001F6966D2006296E1 /* Recovered References */,

This entire section is new:

E3C5B1001F6966D2006296E1 /* Recovered References */ = {
            isa = PBXGroup;
            children = (
                E602D61E379048BF92DC0C6D /* libRNDeviceInfo.a */,
                DEE39860F1B042208F193884 /* libRNVectorIcons.a */,
                C193FEFE9F3B45388016E921 /* libRNShare.a */,
                58B3A26CAB2543FB941C3D8D /* libRNFIRMessaging.a */,
                0BFBA42D662C492EBC1957A0 /* libreact-native-branch.a */,
                4BC248DD95524DE091A41CEC /* libCodePush.a */,
                6DB0E4FE64B34B68A29B262E /* libRNImagePicker.a */,
                E1502CC537D94CF4A5711814 /* libRNAddCalendarEvent.a */,
                065361D30B3F47D4A5101A1D /* libRNAccountKit.a */,
            );
            name = "Recovered References";
            sourceTree = "<group>";
        };


问:
Would using Redux on Angular without ng2-redux be a bad practice?
I ask because the ng2-redux adds a layer of complexity, async pipes and a bunch of setup, when all we really need to do to use redux natively is subscribe/unsubscribe to the store on any component/service that uses it - letting change detection handle DOM updates - like so:

```<code> sub
 store = store.getStore()

 ngOnDestroy(){
     sub()
 }

 ngOnInit(){
     sub = store.subscribe(d => this.store = d)
 }
</code>```

Is it a bad practice to use redux natively?

Why would you opt to use the library?

答:
We are using redux with seamless-immutable package and writing our "actions" and "reducers".

Here is the package.json part

```<code>"redux": "^3.6.0",
"redux-seamless-immutable": "^0.3.0"
</code>```

There are two popular redux implementations for Angular.

ngrx: Reactive Extensions for Angular
angular.redux: Angular 2+ bindings for Redux

It cannot be said which is better. Angular-redux uses the existing implementation of React. ngrs ist a own implementation on the basis of RxJS. In principle, it is recommended to study both projects.

Don't miss the Redux extension for Chrome!

Body:
I ask because the ng2-redux adds a layer of complexity, async pipes and a bunch of setup, when all we really need to do to use redux natively is subscribe/unsubscribe to the store on any component/service that uses it - letting change detection handle DOM updates - like so:

 sub
 store = store.getStore()

 ngOnDestroy(){
     sub()
 }

 ngOnInit(){
     sub = store.subscribe(d => this.store = d)
 }

Is it a bad practice to use redux natively?

Why would you opt to use the library?

Body:
We are using redux with seamless-immutable package and writing our "actions" and "reducers".

Here is the package.json part

"redux": "^3.6.0",
"redux-seamless-immutable": "^0.3.0"

There are two popular redux implementations for Angular.

ngrx: Reactive Extensions for Angular
angular.redux: Angular 2+ bindings for Redux

It cannot be said which is better. Angular-redux uses the existing implementation of React. ngrs ist a own implementation on the basis of RxJS. In principle, it is recommended to study both projects.

Don't miss the Redux extension for Chrome!


问:
Automating telnet session using Bash scripts
I am working on automating some telnet related tasks, using Bash scripts.

Once automated, there will be no interaction of the user with telnet (that is, the script will be totally automated).

The scripts looks something like this:

```<code># execute some commands on the local system
# access a remote system with an IP address: 10.1.1.1 (for example)

telnet 10.1.1.1

# execute some commands on the remote system
# log all the activity (in a file) on the local system
# exit telnet
# continue with executing the rest of the script
</code>```

There are two problems I am facing here:

How to execute the commands on the remote system from the script (without human interaction)?

From my experience with some test code, I was able to deduce that when telnet 10.1.1.1 is executed, telnet goes into an interactive session and the subsequent lines of code in the script are executed on the local system. How can I run the lines of code on the remote system rather than on the local one?

I am unable to get a log file for the activity in the telnet session on the local system. The stdout redirect I used makes a copy on the remote system (I do not want to perform a copy operation to copy the log to the local system). How can I achieve this functionality?

答:
Here is how to use telnet in bash shell/expect  </p>

```<code>#!/usr/bin/expect
# just do a chmod 755 one the script
# ./YOUR_SCRIPT_NAME.sh $YOUHOST $PORT
# if you get "Escape character is '^]'" as the output it means got connected otherwise it has failed

set ip [lindex $argv 0]
set port [lindex $argv 1]

set timeout 5
spawn telnet $ip $port
expect "'^]'."
</code>```

Body:
I am working on automating some telnet related tasks, using Bash scripts.

Once automated, there will be no interaction of the user with telnet (that is, the script will be totally automated).

The scripts looks something like this:

# execute some commands on the local system
# access a remote system with an IP address: 10.1.1.1 (for example)

telnet 10.1.1.1

# execute some commands on the remote system
# log all the activity (in a file) on the local system
# exit telnet
# continue with executing the rest of the script

There are two problems I am facing here:

How to execute the commands on the remote system from the script (without human interaction)?

From my experience with some test code, I was able to deduce that when telnet 10.1.1.1 is executed, telnet goes into an interactive session and the subsequent lines of code in the script are executed on the local system. How can I run the lines of code on the remote system rather than on the local one?

I am unable to get a log file for the activity in the telnet session on the local system. The stdout redirect I used makes a copy on the remote system (I do not want to perform a copy operation to copy the log to the local system). How can I achieve this functionality?

Body:
Here is how to use telnet in bash shell/expect

#!/usr/bin/expect
# just do a chmod 755 one the script
# ./YOUR_SCRIPT_NAME.sh $YOUHOST $PORT
# if you get "Escape character is '^]'" as the output it means got connected otherwise it has failed

set ip [lindex $argv 0]
set port [lindex $argv 1]

set timeout 5
spawn telnet $ip $port
expect "'^]'."


问:
Crytal Reports - Subreport
I have a main report and a group subreport the is driven off of a value in the mainreport.  What I want to do is have the subreport printon a new page without the Headers showing from the main report.  Is this possible?

Thanks.

答:
There are several ways to do this, depending on how your report is structured and how it's being viewed (in it's native .rpt format, exported to PDF, etc.).

If you're looking for a "Do not print page header/footers if there is a subreport on this page" function, I've never seen one. Sure would be convenient though if it did exist. However, the InRepeatedGroupHeader boolean might help you in conditionally suppressing the header/footer sections.  This will take a lot of trial & error, however.

If the subreports are that different from the main report, don't try to combine them.  Keep these "subreports" in a completely separate file.

Are the page numbers of the subreports locked down? i.e. If you know for certain that these subreports are only 1 page long and appear only on even-numbered pages? In this case, you can 'suppress' page headers and footers only on even-numbered pages.

Title: Crytal Reports - Subreport