问:
how pass from to another Layout using View.OnClickListener and dynamic buttons?

Hello, I create buttons dynamic and now I want when one of this buttons click, pass to another layout, but I can't! maybe somebody can give me solution, thank you

onCreate:

```<code>enter code here//-------------------Creating Buttons as per in server -------------------------------
        final Button[] myButton = new Button[jsonArray.length()];
        int count = jsonArray.length();
       for (int i = 0; i < jsonArray.length(); i++) { //upside down -> HAFUH
       // for (int i = jsonArray.length(); i > 0 ; i--) {
            final Button rowButton = new Button(this);// create a new button

            --count;//to upside down the buttons, that mean: check last will be on Top

         //   rowButton.setText(dateIn[count] + "  KM: "+ kmIn[count]+" GAS: "+ gasIn[count]);
           rowButton.setText( "KM: "+ kmIn[count]+" GAS: "+ gasIn[count]+"    "+dateIn[count]);
           rowButton.setId(Integer.parseInt(idIn[count]));//string convert to int "ID"
           /*-----------Build onClick and what happened after ------------*/
            rowButton.setOnClickListener(btnClick(myButton[i]));//WHEN Click on button
           /*-------------FINISH Build onClick and what happened after---*/
           b.addView(rowButton);
           // save a reference to the button for later
           myButton[i] = rowButton;

        }//end for jsonArray
        /************Finish Creating Buttons as per in server**********************************/
    }//END IF FOR JSON AND BUILD BUTTON
}//End Create Button
</code>```

outside onCreate method, in the class:

```<code>enter code hereprivate View.OnClickListener btnClick(final Button button) {
    return new View.OnClickListener(){
        public void onClick(View v){
            Intent intent = new Intent(this,GalleryHistoryCheckIn.class);
            startActivity(intent);
        }
    };
}
</code>```

I expect just pass to another class

答:
HAHA I understand what was my problem, this is answer
method onCreate:
     final Button[] myButton = new Button[jsonArray.length()];

```<code>        int count = jsonArray.length();
       for (int i = 0; i < jsonArray.length(); i++) { //upside down -> HAFUH
       // for (int i = jsonArray.length(); i > 0 ; i--) {
            final Button rowButton = new Button(this);// create a new button

            --count;//to upside down the buttons, that mean: check last will be on Top

         //   rowButton.setText(dateIn[count] + "  KM: "+ kmIn[count]+" GAS: "+ gasIn[count]);
           rowButton.setText( "KM: "+ kmIn[count]+" GAS: "+ gasIn[count]+"    "+dateIn[count]);
           rowButton.setId(Integer.parseInt(idIn[count]));//string convert to int "ID"
           /*-----------Build onClick and what happened after ------------*/
           // rowButton.setOnClickListener(btnClick(myButton[i]));//WHEN Click on button
           /*-------------FINISH Build onClick and what happened after---*/
           b.addView(rowButton);
           // save a reference to the button for later
           myButton[i] = rowButton;
            myButton[i].setOnClickListener(btnClick(rowButton));
       }//end for jsonArray
        /************Finish Creating Buttons as per in server**********************************/
    }//END IF FOR JSON AND BUILD BUTTON
}//End Create Button
</code>```

outside of on create but in class:

```<code>  private View.OnClickListener btnClick(final Button button) {
    return new View.OnClickListener(){
        public void onClick(View v){
            Intent intent = new Intent(v.getContext(),GalleryHistoryCheckIn.class);
            intent.putExtra("result", v.getId());
            startActivity(intent);
        }
    };
}
</code>```

Body:
Hello, I create buttons dynamic and now I want when one of this buttons click, pass to another layout, but I can't! maybe somebody can give me solution, thank you

onCreate:

enter code here//-------------------Creating Buttons as per in server -------------------------------
        final Button[] myButton = new Button[jsonArray.length()];
        int count = jsonArray.length();
       for (int i = 0; i < jsonArray.length(); i++) { //upside down -> HAFUH
       // for (int i = jsonArray.length(); i > 0 ; i--) {
            final Button rowButton = new Button(this);// create a new button

            --count;//to upside down the buttons, that mean: check last will be on Top

         //   rowButton.setText(dateIn[count] + "  KM: "+ kmIn[count]+" GAS: "+ gasIn[count]);
           rowButton.setText( "KM: "+ kmIn[count]+" GAS: "+ gasIn[count]+"    "+dateIn[count]);
           rowButton.setId(Integer.parseInt(idIn[count]));//string convert to int "ID"
           /*-----------Build onClick and what happened after ------------*/
            rowButton.setOnClickListener(btnClick(myButton[i]));//WHEN Click on button
           /*-------------FINISH Build onClick and what happened after---*/
           b.addView(rowButton);
           // save a reference to the button for later
           myButton[i] = rowButton;

        }//end for jsonArray
        /************Finish Creating Buttons as per in server**********************************/
    }//END IF FOR JSON AND BUILD BUTTON
}//End Create Button

outside onCreate method, in the class:

enter code hereprivate View.OnClickListener btnClick(final Button button) {
    return new View.OnClickListener(){
        public void onClick(View v){
            Intent intent = new Intent(this,GalleryHistoryCheckIn.class);
            startActivity(intent);
        }
    };
}

I expect just pass to another class

Body:
HAHA I understand what was my problem, this is answer
method onCreate:
     final Button[] myButton = new Button[jsonArray.length()];

        int count = jsonArray.length();
       for (int i = 0; i < jsonArray.length(); i++) { //upside down -> HAFUH
       // for (int i = jsonArray.length(); i > 0 ; i--) {
            final Button rowButton = new Button(this);// create a new button

            --count;//to upside down the buttons, that mean: check last will be on Top

         //   rowButton.setText(dateIn[count] + "  KM: "+ kmIn[count]+" GAS: "+ gasIn[count]);
           rowButton.setText( "KM: "+ kmIn[count]+" GAS: "+ gasIn[count]+"    "+dateIn[count]);
           rowButton.setId(Integer.parseInt(idIn[count]));//string convert to int "ID"
           /*-----------Build onClick and what happened after ------------*/
           // rowButton.setOnClickListener(btnClick(myButton[i]));//WHEN Click on button
           /*-------------FINISH Build onClick and what happened after---*/
           b.addView(rowButton);
           // save a reference to the button for later
           myButton[i] = rowButton;
            myButton[i].setOnClickListener(btnClick(rowButton));
       }//end for jsonArray
        /************Finish Creating Buttons as per in server**********************************/
    }//END IF FOR JSON AND BUILD BUTTON
}//End Create Button

outside of on create but in class:

  private View.OnClickListener btnClick(final Button button) {
    return new View.OnClickListener(){
        public void onClick(View v){
            Intent intent = new Intent(v.getContext(),GalleryHistoryCheckIn.class);
            intent.putExtra("result", v.getId());
            startActivity(intent);
        }
    };
}


来源: stackexchange

问:
empty base class optimization
Below is a simple test on ebco, I compiled it on both vc9 and g++. The outputs differ on both compilers. What I want to know is that whether the behavior of vc is conformant.

```<code>#include <iostream>

class empty
{
};

class empty_one : public empty {};
class empty_two : public empty {};

class non_empty
    : public empty_one
    , public empty_two
{
};

int main()
{
    std::cout << "sizeof(empty): " << sizeof(empty) << std::endl;
    std::cout << "sizeof(empty_one): " << sizeof(empty_one) << std::endl;
    std::cout << "sizeof(empty_two): " << sizeof(empty_two) << std::endl;
    std::cout << "sizeof(non_empty): " << sizeof(non_empty) << std::endl;

    std::cout << std::endl;

    non_empty a[2];

    void* pe10 = static_cast<empty*>(static_cast<empty_one*>(&a[0]));
    void* pe20 = static_cast<empty*>(static_cast<empty_two*>(&a[0]));
    std::cout << "address of non_empty[0]: " << &a[0] << std::endl;
    std::cout << "address of empty of empty_one: " << pe10 << std::endl;
    std::cout << "address of empty of empty_two: " << pe20 << std::endl;

    std::cout << std::endl;

    void* pe11 = static_cast<empty*>(static_cast<empty_one*>(&a[1]));
    void* pe21 = static_cast<empty*>(static_cast<empty_two*>(&a[1]));
    std::cout << "address of non_empty[1]: " << &a[1] << std::endl;
    std::cout << "address of empty of empty_one: " << pe11 << std::endl;
    std::cout << "address of empty of empty_two: " << pe21 << std::endl;
}
</code>```

On vc,

```<code>pe20 == pe11. (test1)
</code>```

Can two sub-objects of two objects have the same address? Is this conformant?

Besides,

```<code>pe20 >= &a[0] + sizeof(a[0]) (test2)
</code>```

Can the address of an sub-object passes the end of an object ?

On g++, above two tests does not hold.

EDIT: In c++0x standard draft, 1.8/6,

Unless an object is a bit-field or a base class subobject of zero size, the address of that object is the address of the first byte it occupies. Two distinct objects that are neither bit-fields nor base class subobjects of zero size shall have distinct addresses

The standard requires that two objects have different address when they are neither bit-fields nor base class subobjects of zero size. But it doesn't require that two sub-objects of zero size cannot have same address. So test1 can be true ?

答:
pe10 == pe11.  Can two sub-objects of
  two objects have the same address? Is
  this conformant?

No, two different objects cannot have same address. If they've, the compiler is not Standard Complaint.

By the way, which version of VC++ you're using? I'm using MSVC++2008, and it's output is this:

I think, you meant pe20==pe11? If so, then this also is wrong, non-standard. MSVC++2008 compiler has bug!

GCC is correct; see the output yourself : http://www.ideone.com/Cf2Ov

Similar topic:

When do programmers use Empty Base Optimization (EBO)

ContentLicense: CC BY-SA 2.5

Title: empty base class optimization

Body:
Below is a simple test on ebco, I compiled it on both vc9 and g++. The outputs differ on both compilers. What I want to know is that whether the behavior of vc is conformant.

#include <iostream>

class empty
{
};

class empty_one : public empty {};
class empty_two : public empty {};

class non_empty
    : public empty_one
    , public empty_two
{
};

int main()
{
    std::cout << "sizeof(empty): " << sizeof(empty) << std::endl;
    std::cout << "sizeof(empty_one): " << sizeof(empty_one) << std::endl;
    std::cout << "sizeof(empty_two): " << sizeof(empty_two) << std::endl;
    std::cout << "sizeof(non_empty): " << sizeof(non_empty) << std::endl;

    std::cout << std::endl;

    non_empty a[2];

    void* pe10 = static_cast<empty*>(static_cast<empty_one*>(&a[0]));
    void* pe20 = static_cast<empty*>(static_cast<empty_two*>(&a[0]));
    std::cout << "address of non_empty[0]: " << &a[0] << std::endl;
    std::cout << "address of empty of empty_one: " << pe10 << std::endl;
    std::cout << "address of empty of empty_two: " << pe20 << std::endl;

    std::cout << std::endl;

    void* pe11 = static_cast<empty*>(static_cast<empty_one*>(&a[1]));
    void* pe21 = static_cast<empty*>(static_cast<empty_two*>(&a[1]));
    std::cout << "address of non_empty[1]: " << &a[1] << std::endl;
    std::cout << "address of empty of empty_one: " << pe11 << std::endl;
    std::cout << "address of empty of empty_two: " << pe21 << std::endl;
}

On vc,

pe20 == pe11. (test1)

Can two sub-objects of two objects have the same address? Is this conformant?

Besides,

pe20 >= &a[0] + sizeof(a[0]) (test2)

Can the address of an sub-object passes the end of an object ?

On g++, above two tests does not hold.

EDIT: In c++0x standard draft, 1.8/6,

Unless an object is a bit-field or a base class subobject of zero size, the address of that object is the address of the first byte it occupies. Two distinct objects that are neither bit-fields nor base class subobjects of zero size shall have distinct addresses

The standard requires that two objects have different address when they are neither bit-fields nor base class subobjects of zero size. But it doesn't require that two sub-objects of zero size cannot have same address. So test1 can be true ?


问:
Adding Callout type annotation to iOS PDFTron library
I am facing an issue wherein the PDFNET framework for iOS is successfully rendering callout type annotation made from other platform. But I am unable to allow users of iOS app to make the same annotation from start.</p>

答:
This is a programmatic example of how to create a callout annotation using PDFNet:

```<code>    let txtannot: PTFreeText = PTFreeText.create(doc.getSDFDoc(), pos: PTPDFRect(x1: 100, y1: 100, x2: 350, y2: 500))
        txtannot.setContentRect(PTPDFRect(x1: 200, y1: 200, x2: 350, y2: 500))
        txtannot.setContents("\n\nSome swift brown fox snatched a gray hare out of the air by freezing it with an angry glare." +
            "\n\nAha!\n\nAnd there was much rejoicing!")
        txtannot.setCalloutLinePoints(withKneePoint: PTPDFPoint(px: 200, py: 300), p2: PTPDFPoint(px: 150, py: 290), p3: PTPDFPoint(px: 110, py: 110))
        txtannot.setBorderStyle(PTBorderStyle(s: e_ptsolid, b_width: 1, b_hr: 10, b_vr: 20), oldStyleOnly: true)
        txtannot.setEndingStyle(e_ptClosedArrow)
        txtannot.setColor(PTColorPt(x: 0, y: 1, z: 0, w: 0), numcomp: 3)
        txtannot.setQuaddingFormat(1)
        first_page.annotPushBack(txtannot)
        txtannot.refreshAppearance()
</code>```

(An Obj-C version can be found in the miscellaneous sample project, or on PDFTron's website.)

If you wish to create a callout annotation interactively, you will need to create a new "tool" to do so. All of PDFNet for iOS's UI widgets and annotation creation/editing methods are part of the open source framework Tools.framework, found in /Lib/Tools. By using existing tools as sa guide (which create free text annotations, text markup annotations, fill forms, sign documents, etc.), you can create a new tool for creating callout annotations interactively.

SO discolsure: I work for PDFTron.

ContentLicense: CC BY-SA 3.0

Body:
This is a programmatic example of how to create a callout annotation using PDFNet:

    let txtannot: PTFreeText = PTFreeText.create(doc.getSDFDoc(), pos: PTPDFRect(x1: 100, y1: 100, x2: 350, y2: 500))
        txtannot.setContentRect(PTPDFRect(x1: 200, y1: 200, x2: 350, y2: 500))
        txtannot.setContents("\n\nSome swift brown fox snatched a gray hare out of the air by freezing it with an angry glare." +
            "\n\nAha!\n\nAnd there was much rejoicing!")
        txtannot.setCalloutLinePoints(withKneePoint: PTPDFPoint(px: 200, py: 300), p2: PTPDFPoint(px: 150, py: 290), p3: PTPDFPoint(px: 110, py: 110))
        txtannot.setBorderStyle(PTBorderStyle(s: e_ptsolid, b_width: 1, b_hr: 10, b_vr: 20), oldStyleOnly: true)
        txtannot.setEndingStyle(e_ptClosedArrow)
        txtannot.setColor(PTColorPt(x: 0, y: 1, z: 0, w: 0), numcomp: 3)
        txtannot.setQuaddingFormat(1)
        first_page.annotPushBack(txtannot)
        txtannot.refreshAppearance()

(An Obj-C version can be found in the miscellaneous sample project, or on PDFTron's website.)

If you wish to create a callout annotation interactively, you will need to create a new "tool" to do so. All of PDFNet for iOS's UI widgets and annotation creation/editing methods are part of the open source framework Tools.framework, found in /Lib/Tools. By using existing tools as sa guide (which create free text annotations, text markup annotations, fill forms, sign documents, etc.), you can create a new tool for creating callout annotations interactively.

SO discolsure: I work for PDFTron.


问:
Error ORA-00923 after trying to generate random number in Oracle SQL Developer
The following procedure is not complete, but I am having trouble trying to generate a random integer between 1 and the size of a table. Any Ideas?

```<code>create or replace PROCEDURE AssignPlayersTMs AS

TYPE usertype IS TABLE OF TEAM_MANAGERS.ACCT_USERNAME%TYPE;
UserNM usertype;
TYPE usertype2 IS TABLE OF ROSTERS.PLAYER_ID%TYPE;
Play usertype2;
Rn INT;

BEGIN
    SELECT ACCT_USERNAME BULK COLLECT INTO UserNM FROM TEAM_MANAGERS;
    SELECT PLAYER_ID BULK COLLECT INTO Play FROM PLAYERS;

    for i in 1..UserNM.count
    loop
        SELECT FLOOR(RAND()*(Play.count-1)+1) INTO Rn;

    end loop;
END;
</code>```

Compiler Error:

```<code>Error(17,9): PL/SQL: SQL Statement ignored
Error(17,54): PL/SQL: ORA-00923: FROM keyword not found where expected
</code>```

答:
A SELECT needs a FROM clause in SQL - just like the errors says. But you don't need a SELECT to assign a value to a variable. Just assign it:

Also, Oracle has no rand() function. You have to use dbms_random for that

```<code>create or replace PROCEDURE AssignPlayersTMs AS

  TYPE usertype IS TABLE OF TEAM_MANAGERS.ACCT_USERNAME%TYPE;
  UserNM usertype;
  TYPE usertype2 IS TABLE OF ROSTERS.PLAYER_ID%TYPE;
  Play usertype2;
  Rn INT;
BEGIN
    SELECT ACCT_USERNAME BULK COLLECT INTO UserNM FROM TEAM_MANAGERS;
    SELECT PLAYER_ID BULK COLLECT INTO Play FROM PLAYERS;

    for i in 1..UserNM.count
    loop
        rn := dbms.random.value(1, Play.count-1);
    end loop;
END;
</code>```

Body:
The following procedure is not complete, but I am having trouble trying to generate a random integer between 1 and the size of a table. Any Ideas?

create or replace PROCEDURE AssignPlayersTMs AS

TYPE usertype IS TABLE OF TEAM_MANAGERS.ACCT_USERNAME%TYPE;
UserNM usertype;
TYPE usertype2 IS TABLE OF ROSTERS.PLAYER_ID%TYPE;
Play usertype2;
Rn INT;

BEGIN
    SELECT ACCT_USERNAME BULK COLLECT INTO UserNM FROM TEAM_MANAGERS;
    SELECT PLAYER_ID BULK COLLECT INTO Play FROM PLAYERS;

    for i in 1..UserNM.count
    loop
        SELECT FLOOR(RAND()*(Play.count-1)+1) INTO Rn;

    end loop;
END;

Compiler Error:

Error(17,9): PL/SQL: SQL Statement ignored
Error(17,54): PL/SQL: ORA-00923: FROM keyword not found where expected

Body:
A SELECT needs a FROM clause in SQL - just like the errors says. But you don't need a SELECT to assign a value to a variable. Just assign it:

Also, Oracle has no rand() function. You have to use dbms_random for that

create or replace PROCEDURE AssignPlayersTMs AS

  TYPE usertype IS TABLE OF TEAM_MANAGERS.ACCT_USERNAME%TYPE;
  UserNM usertype;
  TYPE usertype2 IS TABLE OF ROSTERS.PLAYER_ID%TYPE;
  Play usertype2;
  Rn INT;
BEGIN
    SELECT ACCT_USERNAME BULK COLLECT INTO UserNM FROM TEAM_MANAGERS;
    SELECT PLAYER_ID BULK COLLECT INTO Play FROM PLAYERS;

    for i in 1..UserNM.count
    loop
        rn := dbms.random.value(1, Play.count-1);
    end loop;
END;


问:
Many-to-Many relation in sqlalchemy doesnt load while it adds and deletes items
I created a many-to-many self referential relation in SQLAlchemy like this:

```<code>blacklist_association_table = Table('userblacklist', Base.metadata,
    Column('user_id', Integer, ForeignKey('user.id'), primary_key=True),
    Column('blacklisted_id', Integer, ForeignKey('user.id'), primary_key=True)
)

class User(Base):
    __tablename__ = 'user'

    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=True)

    blacklist = relationship("User",
                             secondary=blacklist_association_table,
                             primaryjoin=(id == blacklist_association_table.c.user_id),
                             secondaryjoin=(blacklist_association_table.c.blacklisted_id == id))
</code>```

When I use append to add items to blacklist field it works and new data is committed to DB

But when I need to access list the blacklist field is empty!!
i.e.

```<code>u = session.query(User).filter(User.id == userid).one_or_none()
print len(u.blacklist)
</code>```

output is 0 while data exists in DB!

What is the problem?

答:
Did you mean to put

```<code>print len(u.blacklist)
</code>```

Otherwise I think you need more context.

EDIT

can you try:

```<code>u = session.query(User).filter(User.id == userid).one_or_none()
print len(u.blacklist)
u.blacklist.append(session.query(User).first())
session.commit()
print len(u.blacklist)
u = session.query(User).filter(User.id == userid).one_or_none()
print len(u.blacklist)
</code>```

From what I can tell your code is correct above.
You are saying that you get will get the following output from the above:

```<code>0
1
0
</code>```

?

Body:
I created a many-to-many self referential relation in SQLAlchemy like this:

blacklist_association_table = Table('userblacklist', Base.metadata,
    Column('user_id', Integer, ForeignKey('user.id'), primary_key=True),
    Column('blacklisted_id', Integer, ForeignKey('user.id'), primary_key=True)
)

class User(Base):
    __tablename__ = 'user'

    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=True)

    blacklist = relationship("User",
                             secondary=blacklist_association_table,
                             primaryjoin=(id == blacklist_association_table.c.user_id),
                             secondaryjoin=(blacklist_association_table.c.blacklisted_id == id))

When I use append to add items to blacklist field it works and new data is committed to DB

But when I need to access list the blacklist field is empty!!
i.e.

u = session.query(User).filter(User.id == userid).one_or_none()
print len(u.blacklist)

output is 0 while data exists in DB!

What is the problem?

Body:
Did you mean to put

print len(u.blacklist)

Otherwise I think you need more context.

EDIT

can you try:

u = session.query(User).filter(User.id == userid).one_or_none()
print len(u.blacklist)
u.blacklist.append(session.query(User).first())
session.commit()
print len(u.blacklist)
u = session.query(User).filter(User.id == userid).one_or_none()
print len(u.blacklist)

From what I can tell your code is correct above.
You are saying that you get will get the following output from the above:

0
1
0

?


问:
PHP & MYSQL - Display user-uploaded photos from Database according to date photos were uploaded
I created photo upload form. Different users are able to upload multiple photos at once and the photos, the user's details and input get stored in the database as shown in picture below:

I want to be able to display the users and their photos in my index.php page according to the date the photos were uploaded. I would like the index.php page to look something like this

I tried to use GROUP_CONCAT() and GROUP BY in my SQL statement hoping to achieve something like the table below which might allow me to loop through the table data in order to display the photos alongside the users

This is my code which did not work:

```<code>$sql = "SELECT id, unique_id, GROUP_CONCAT(fileName) as fileName,  title,date GROUP BY unique_id FROM images";
$result = $conn->query($sql);
if ($result->num_rows > 0) { // This is the line 22 in my code.
    while($row = $result->fetch_assoc()) {
        echo $row['fileName']; //I wanted to know if echo $row['fileName']; would print something like cow1.jpg, cow2,jpg etc.
    }
}
</code>```

But I am getting error as follows:

Notice: Trying to get property of non-object in C:\xampp\htdocs\display.php on line 22

Someone suggested the GROUP_CONCAT() to me. I have done some search but all tutorials give example of how the table will look after using GROUP_CONCAT() but not how to get data from the final table to use in e.g index.php. I am new to GROUP_CONCAT() and I don't really know how to work with that.

答:
Try this:</p>

```<code>$sql = "SELECT id, unique_id, GROUP_CONCAT(fileName) AS filenames, title, date FROM images GROUP BY unique_id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo $row['filenames'];
    }
}
</code>```

Body:
I created photo upload form. Different users are able to upload multiple photos at once and the photos, the user's details and input get stored in the database as shown in picture below:

I want to be able to display the users and their photos in my index.php page according to the date the photos were uploaded. I would like the index.php page to look something like this

I tried to use GROUP_CONCAT() and GROUP BY in my SQL statement hoping to achieve something like the table below which might allow me to loop through the table data in order to display the photos alongside the users

This is my code which did not work:

$sql = "SELECT id, unique_id, GROUP_CONCAT(fileName) as fileName,  title,date GROUP BY unique_id FROM images";
$result = $conn->query($sql);
if ($result->num_rows > 0) { // This is the line 22 in my code.
    while($row = $result->fetch_assoc()) {
        echo $row['fileName']; //I wanted to know if echo $row['fileName']; would print something like cow1.jpg, cow2,jpg etc.
    }
}

But I am getting error as follows:

Notice: Trying to get property of non-object in C:\xampp\htdocs\display.php on line 22

Someone suggested the GROUP_CONCAT() to me. I have done some search but all tutorials give example of how the table will look after using GROUP_CONCAT() but not how to get data from the final table to use in e.g index.php. I am new to GROUP_CONCAT() and I don't really know how to work with that.

Body:
Try this:

$sql = "SELECT id, unique_id, GROUP_CONCAT(fileName) AS filenames, title, date FROM images GROUP BY unique_id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo $row['filenames'];
    }
}


问:
SSIS Excel destination blank
I am debugging an SSIS package that starts with SQL Server data, transforms it, and puts it into an Excel file.  I do this frequently in my work, and have never encountered this issue before:  no rows are written to the Excel file.  I attached a data viewer to the precedence constraint that leads to the Excel destination, and I see hundreds of rows of data flowing to the destination.  When the package finishes executing, I open the Excel file and there is no data!</p>

答:
I had a similar issue today and it was due to some interim SQL I was performing before the final SELECT.

Adding "SET NOCOUNT ON" as the first line fixed the issue.

Title: SSIS Excel destination blank


问:
Python - Getting access to class instance via module property (by string name)
Ok, let me try and explain this to the best of my ability. Lets say I have a class called Foobar:

```<code>class Foobar():
    def __init__(self, foo, bar, choo):
        self.foo = foo
        self.bar = bar
        self.choo = choo

    def doIt(self):
        return self.foo + self.bar
</code>```

and I want to have a set of 10 possibilities of instances of Foobar that I will use in my application. Now my end user does not know or care about the values of foo, bar and choo, but would would like to pick one of the 10 possibilities, which I will label.

So I would like to store their choice in a db (but I only want to store the label, which represents a particular instance of the Foobar class).  So that way i can just grab the instance I need.

So I tried setting up all my instances in a module like so (lets call it "my_instances.py")

```<code>import Foobar

label_one = Foobar("eenie", "meenie", "miney")
label_two = Foobar("teeny", "toony", "tiny")
...
label_ten = Foobar("biggie", "boogie", "baggie")
</code>```

and that way, once I have the string from the db that represents their choice, I can grab that instance like so (I'm ignoring how you would get the string, but showing how I'm obtaining the instance).

```<code>import my_instances

my_object = getattr(my_instances, 'label_one')
result = my_object.doIt()
</code>```

I am getting a TypeError: unbound method doIt() must be called with Foobar instance as first argument.

So it appears I'm getting Foobar, but not a real instance of it.  Any help would be greatly appreciated. I believe I've explained my scenario enough that is you see a simpler workaround for what I am trying to do, please suggest it.

答:
I can't reproduce your error, (using from foobar import Foobar) so it seems there's something in your code that you're not showing us. But it's better not to do dynamic lookup anyway. Why not create a factory function that returns a dict of foobars?

```<code>def get_foobars(x, y, z):
    foobars = {}
    foobars["label_one"] = Foobar(x, y, z)
    foobars["label_two"] = Foobar(z, y, x)
    ...
</code>```

Or, if you don't want the function to create new foobars every time,

```<code>foobars = {}
foobars["label_one"] = Foobar(...

def get_foobars():
    return foobars
</code>```

Or, more tersely,

```<code>foobars = {'label_one':Foobar("eenie", "meenie", "miney"),
           'label_two':Foobar(...),
           ... }
</code>```

Body:
Ok, let me try and explain this to the best of my ability. Lets say I have a class called Foobar:

class Foobar():
    def __init__(self, foo, bar, choo):
        self.foo = foo
        self.bar = bar
        self.choo = choo

    def doIt(self):
        return self.foo + self.bar

and I want to have a set of 10 possibilities of instances of Foobar that I will use in my application. Now my end user does not know or care about the values of foo, bar and choo, but would would like to pick one of the 10 possibilities, which I will label.

So I would like to store their choice in a db (but I only want to store the label, which represents a particular instance of the Foobar class).  So that way i can just grab the instance I need.

So I tried setting up all my instances in a module like so (lets call it "my_instances.py")

import Foobar

label_one = Foobar("eenie", "meenie", "miney")
label_two = Foobar("teeny", "toony", "tiny")
...
label_ten = Foobar("biggie", "boogie", "baggie")

and that way, once I have the string from the db that represents their choice, I can grab that instance like so (I'm ignoring how you would get the string, but showing how I'm obtaining the instance).

import my_instances

my_object = getattr(my_instances, 'label_one')
result = my_object.doIt()

I am getting a TypeError: unbound method doIt() must be called with Foobar instance as first argument.

So it appears I'm getting Foobar, but not a real instance of it.  Any help would be greatly appreciated. I believe I've explained my scenario enough that is you see a simpler workaround for what I am trying to do, please suggest it.

Body:
I can't reproduce your error, (using from foobar import Foobar) so it seems there's something in your code that you're not showing us. But it's better not to do dynamic lookup anyway. Why not create a factory function that returns a dict of foobars?

def get_foobars(x, y, z):
    foobars = {}
    foobars["label_one"] = Foobar(x, y, z)
    foobars["label_two"] = Foobar(z, y, x)
    ...

Or, if you don't want the function to create new foobars every time,

foobars = {}
foobars["label_one"] = Foobar(...

def get_foobars():
    return foobars

Or, more tersely,

foobars = {'label_one':Foobar("eenie", "meenie", "miney"),
           'label_two':Foobar(...),
           ... }


问:
How to rewrite the text of buttons that are not separately defined
I have started trying to write a code similar to the game 2048, however the size of the board can have any value depending on what the user inputs. I decided to make the numbers on the board, for style purposes, separate buttons.

This is the current GUI:

How can I make it so that when the buttons: up, down left, or right are pressed each of the button's in the board texts are changed? I know about event listeners I just mean how can I replace the button's in the same grid with different values when I defined the buttons on the board as:

```<code>`for(int i = 2; i < rows + 2; i++) {
  for(int j = 2; j < columns + 2; j++) {
    gbc.gridx = j;
    gbc.gridy = i;
    num = new JButton(board.board[j-2][i-2].getValue()+"");
    num.setFont(new Font("monospaced", Font.PLAIN, screenSize.height/50));
    num.setEnabled(false);
    this.add(num, gbc);
  }
}`
</code>```

The only ideas I've had was to create an array of buttons and then change the button's text in the array of buttons and then replace the old array of buttons with the new one. Also sorry if it has some super simple answer that I just couldn't find, I am just about finished with one semester of coding courses in college.

答:
You could store the JButtons on a HashMap and use column number and row number as a key to find the correct button.

Something like:

```<code>Map<String, JButton> grid = new HashMap<String, JButton>;

for(int i = 2; i < rows + 2; i++) {
    for(int j = 2; j < columns + 2; j++) {
        grid.put(String.valueOf(i) + String.valueOf(i), new JButton("some text"));
        // we transform the integers into String, otherwise the operator "+" will sum them
        // instead of concatenate them.
     }
}
</code>```

Now you cant get the desired button with grid.get(row + column);

```<code>JButton bt;
JButton bt = grid.get("4" + "6");
bt.setText("different text");
grid.put("4" + "6", bt);
</code>```

Body:
I have started trying to write a code similar to the game 2048, however the size of the board can have any value depending on what the user inputs. I decided to make the numbers on the board, for style purposes, separate buttons.

This is the current GUI:

How can I make it so that when the buttons: up, down left, or right are pressed each of the button's in the board texts are changed? I know about event listeners I just mean how can I replace the button's in the same grid with different values when I defined the buttons on the board as:

`for(int i = 2; i < rows + 2; i++) {
  for(int j = 2; j < columns + 2; j++) {
    gbc.gridx = j;
    gbc.gridy = i;
    num = new JButton(board.board[j-2][i-2].getValue()+"");
    num.setFont(new Font("monospaced", Font.PLAIN, screenSize.height/50));
    num.setEnabled(false);
    this.add(num, gbc);
  }
}`

The only ideas I've had was to create an array of buttons and then change the button's text in the array of buttons and then replace the old array of buttons with the new one. Also sorry if it has some super simple answer that I just couldn't find, I am just about finished with one semester of coding courses in college.

Body:
You could store the JButtons on a HashMap and use column number and row number as a key to find the correct button.

Something like:

Map<String, JButton> grid = new HashMap<String, JButton>;

for(int i = 2; i < rows + 2; i++) {
    for(int j = 2; j < columns + 2; j++) {
        grid.put(String.valueOf(i) + String.valueOf(i), new JButton("some text"));
        // we transform the integers into String, otherwise the operator "+" will sum them
        // instead of concatenate them.
     }
}

Now you cant get the desired button with grid.get(row + column);

JButton bt;
JButton bt = grid.get("4" + "6");
bt.setText("different text");
grid.put("4" + "6", bt);


问:
Wordwrap not working correctly with NavMenu and Div
I created a ASP.Net Core Web Application with Angular in VS2017.
The initial application word wraps the way I want.
However after I added some HTML and styles the word wrap no longer works when the left panel is showing.

I found that the following HTML

```<code><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>

<div class="container">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
</div>
</code>```

causes the following display

How do I fix the effect of the Div?

答:
Instead of using

```<code><div class="container">
</code>```

I needed to use

```<code><div class="container-fluid">
</code>```

Body:
I created a ASP.Net Core Web Application with Angular in VS2017.
The initial application word wraps the way I want.
However after I added some HTML and styles the word wrap no longer works when the left panel is showing.

I found that the following HTML

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

causes the following display

How do I fix the effect of the Div?

Body:
Instead of using

<div class="container">

I needed to use

<div class="container-fluid">


问:
How can I iteratively partition the same string multiple times?
I have a string of unknown length that can repeat the pattern of interest any number of times.
The string looks like so:

blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah

blahblahblahblahblahblahblahblahblahblah

JOHNNYSMITH has entered the above notes on 12/05/2017 14:18
  blahblahblahblahblahblahblahblahblahblahblahblahblahblahblah

blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah

JOHNNYSMITH has entered the above notes on 12/05/2017 14:19

SARAHJOHNSON has entered the above notes on 12/05/2017 17:45
  blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah

SARAHJOHNSON has entered the above notes on 12/05/2017 17:46

I'm trying separate out the comment, username, and date to create a nicer looking comment box (with some css). The following is what I have to separate the user name

```<code>before_keyword, keyword, after_keyword = stringg.partition("has entered the above notes on ")
namedate = before_keyword.split()[-1] + "--" + after_keyword.split()[0] + after_keyword.split()[1]
comment = before_keyword.replace(before_keyword.split()[-1], '').rstrip()
print comment
print namedate
</code>```

This works for the first case of Username entered the above notes. How can I iterate through the string to collect all comments/usernames/dates in the string and print them out separately.

Thanks.

Edit: put in fake names instead of USERNAME2389 to show how the names appear for me.

答:
The solution from Bernz worked, I'm using something like the code shown below. datawrestler's answer would also work.</p>

```<code>for line in stringg.split('\n'):
      if re.findall('(\w+) has entered the above notes on (\d{1,2}/\d{1,2}/\d{4}) (\d{1,2}:\d{1,2})', line):
        print line.split()[0] + "--" + line.split()[-2] + line.split()[-1]
      else:
        print line
</code>```

Body:
I have a string of unknown length that can repeat the pattern of interest any number of times.
The string looks like so:

blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah

blahblahblahblahblahblahblahblahblahblah

JOHNNYSMITH has entered the above notes on 12/05/2017 14:18
  blahblahblahblahblahblahblahblahblahblahblahblahblahblahblah

blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah

JOHNNYSMITH has entered the above notes on 12/05/2017 14:19

SARAHJOHNSON has entered the above notes on 12/05/2017 17:45
  blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah

SARAHJOHNSON has entered the above notes on 12/05/2017 17:46

I'm trying separate out the comment, username, and date to create a nicer looking comment box (with some css). The following is what I have to separate the user name

before_keyword, keyword, after_keyword = stringg.partition("has entered the above notes on ")
namedate = before_keyword.split()[-1] + "--" + after_keyword.split()[0] + after_keyword.split()[1]
comment = before_keyword.replace(before_keyword.split()[-1], '').rstrip()
print comment
print namedate

This works for the first case of Username entered the above notes. How can I iterate through the string to collect all comments/usernames/dates in the string and print them out separately.

Thanks.

Edit: put in fake names instead of USERNAME2389 to show how the names appear for me.

Body:
The solution from Bernz worked, I'm using something like the code shown below. datawrestler's answer would also work.

for line in stringg.split('\n'):
      if re.findall('(\w+) has entered the above notes on (\d{1,2}/\d{1,2}/\d{4}) (\d{1,2}:\d{1,2})', line):
        print line.split()[0] + "--" + line.split()[-2] + line.split()[-1]
      else:
        print line


问:
SQL - Counting Records By Group
I would like my results to include records only where there is more than Tag Date per Debt Number.

```<code>SELECT DISTINCT
    tag.tag_shrt_nm AS [Tag]
    ,cnsmr.cnsmr_idntfr_agncy_id AS [Borrower Number]
    ,CAST(cnsmr_pymnt_tag.cnsmr_pymnt_tag_assgn_dt AS Date) AS [Tag Date]
    ,cnsmr_accnt_idntfr_agncy_id [Debt Number]
FROM
    cnsmr INNER JOIN
    cnsmr_pymnt_jrnl ON cnsmr.cnsmr_id = cnsmr_pymnt_jrnl.cnsmr_id INNER JOIN
    cnsmr_pymnt_tag ON cnsmr_pymnt_jrnl.cnsmr_pymnt_jrnl_id =  cnsmr_pymnt_tag.cnsmr_pymnt_jrnl_id INNER JOIN
    tag ON cnsmr_pymnt_tag.tag_id = tag.tag_id INNER JOIN
    cnsmr_accnt ON cnsmr.cnsmr_id = cnsmr_accnt.cnsmr_id
WHERE
    tag.tag_shrt_nm IN ('tRehab')
ORDER BY
    cnsmr_accnt_idntfr_agncy_id
</code>```

Here there is more than 1 date per debt number so this is my desired output.

```<code>Tag         Borrower Number     Tag Date        Debt Number
tRehab      1000020234          2012-02-20      1089484
tRehab      1000020234          2012-04-07      1089484
tRehab      1000020234          2012-04-10      1089484
tRehab      1000020234          2012-02-20      1089487
tRehab      1000020234          2012-04-07      1089487
tRehab      1000020234          2012-04-10      1089487
</code>```

Here there is only 1 debt number per tag date so this not what I'm looking for and should not be in the results.

```<code>Tag         Borrower Number     Tag Date        Debt Number
tRehab      1000020234          2012-02-19      1089484
tRehab      1000020234          2012-04-07      1089485
tRehab      1000020234          2012-04-10      1089486
tRehab      1000020234          2012-02-20      1089487
tRehab      1000020234          2012-04-07      1089488
tRehab      1000020234          2012-04-10      1089489
</code>```

答:
This should do it.</p>

```<code>DECLARE @TabA TABLE (id INT IDENTITY(1,1), Tag VARCHAR(25), Borrower VARCHAR(25), TagDate DATE, DebtNumber VARCHAR(25))
INSERT INTO @TabA
        ( Tag, Borrower, TagDate, DebtNumber )

  select 'tRehab','1000020234','2012-02-20','1089484'
union select 'tRehab','1000020234','2012-04-07','1089484'
union select 'tRehab','1000020234','2012-04-10','1089484'
union select 'tRehab','1000020234','2012-02-20','1089487'
union select 'tRehab','1000020234','2012-04-07','1089487'
union select 'tRehab','1000020234','2012-04-10','1089487'

DECLARE @TabB TABLE (id INT IDENTITY(1,1), Tag VARCHAR(25), Borrower VARCHAR(25), TagDate DATE, DebtNumber VARCHAR(25))
INSERT INTO @TabB
        ( Tag, Borrower, TagDate, DebtNumber )

  select 'tRehab','1000020234','2012-02-19','1089484'
union select 'tRehab','1000020234','2012-04-07','1089485'
union select 'tRehab','1000020234','2012-04-10','1089486'
union select 'tRehab','1000020234','2012-02-20','1089487'
union select 'tRehab','1000020234','2012-04-07','1089488'
union select 'tRehab','1000020234','2012-04-10','1089489'

SELECT * FROM @TabA TA
WHERE EXISTS (SELECT 1 FROM @TabA TA2 WHERE TA2.DebtNumber = TA.DebtNumber AND TA2.TagDate <> TA.TagDate AND TA.Id <> TA2.ID)

SELECT * FROM @TabB TA
WHERE EXISTS (SELECT 1 FROM @TabB TA2 WHERE TA2.DebtNumber = TA.DebtNumber AND TA2.TagDate <> TA.TagDate AND TA.Id <> TA2.ID)
</code>```

Title: SQL - Counting Records By Group

Body:
I would like my results to include records only where there is more than Tag Date per Debt Number.

SELECT DISTINCT
    tag.tag_shrt_nm AS [Tag]
    ,cnsmr.cnsmr_idntfr_agncy_id AS [Borrower Number]
    ,CAST(cnsmr_pymnt_tag.cnsmr_pymnt_tag_assgn_dt AS Date) AS [Tag Date]
    ,cnsmr_accnt_idntfr_agncy_id [Debt Number]
FROM
    cnsmr INNER JOIN
    cnsmr_pymnt_jrnl ON cnsmr.cnsmr_id = cnsmr_pymnt_jrnl.cnsmr_id INNER JOIN
    cnsmr_pymnt_tag ON cnsmr_pymnt_jrnl.cnsmr_pymnt_jrnl_id =  cnsmr_pymnt_tag.cnsmr_pymnt_jrnl_id INNER JOIN
    tag ON cnsmr_pymnt_tag.tag_id = tag.tag_id INNER JOIN
    cnsmr_accnt ON cnsmr.cnsmr_id = cnsmr_accnt.cnsmr_id
WHERE
    tag.tag_shrt_nm IN ('tRehab')
ORDER BY
    cnsmr_accnt_idntfr_agncy_id

Here there is more than 1 date per debt number so this is my desired output.

Tag         Borrower Number     Tag Date        Debt Number
tRehab      1000020234          2012-02-20      1089484
tRehab      1000020234          2012-04-07      1089484
tRehab      1000020234          2012-04-10      1089484
tRehab      1000020234          2012-02-20      1089487
tRehab      1000020234          2012-04-07      1089487
tRehab      1000020234          2012-04-10      1089487

Here there is only 1 debt number per tag date so this not what I'm looking for and should not be in the results.

Tag         Borrower Number     Tag Date        Debt Number
tRehab      1000020234          2012-02-19      1089484
tRehab      1000020234          2012-04-07      1089485
tRehab      1000020234          2012-04-10      1089486
tRehab      1000020234          2012-02-20      1089487
tRehab      1000020234          2012-04-07      1089488
tRehab      1000020234          2012-04-10      1089489

Body:
This should do it.

DECLARE @TabA TABLE (id INT IDENTITY(1,1), Tag VARCHAR(25), Borrower VARCHAR(25), TagDate DATE, DebtNumber VARCHAR(25))
INSERT INTO @TabA
        ( Tag, Borrower, TagDate, DebtNumber )

  select 'tRehab','1000020234','2012-02-20','1089484'
union select 'tRehab','1000020234','2012-04-07','1089484'
union select 'tRehab','1000020234','2012-04-10','1089484'
union select 'tRehab','1000020234','2012-02-20','1089487'
union select 'tRehab','1000020234','2012-04-07','1089487'
union select 'tRehab','1000020234','2012-04-10','1089487'

DECLARE @TabB TABLE (id INT IDENTITY(1,1), Tag VARCHAR(25), Borrower VARCHAR(25), TagDate DATE, DebtNumber VARCHAR(25))
INSERT INTO @TabB
        ( Tag, Borrower, TagDate, DebtNumber )

  select 'tRehab','1000020234','2012-02-19','1089484'
union select 'tRehab','1000020234','2012-04-07','1089485'
union select 'tRehab','1000020234','2012-04-10','1089486'
union select 'tRehab','1000020234','2012-02-20','1089487'
union select 'tRehab','1000020234','2012-04-07','1089488'
union select 'tRehab','1000020234','2012-04-10','1089489'

SELECT * FROM @TabA TA
WHERE EXISTS (SELECT 1 FROM @TabA TA2 WHERE TA2.DebtNumber = TA.DebtNumber AND TA2.TagDate <> TA.TagDate AND TA.Id <> TA2.ID)

SELECT * FROM @TabB TA
WHERE EXISTS (SELECT 1 FROM @TabB TA2 WHERE TA2.DebtNumber = TA.DebtNumber AND TA2.TagDate <> TA.TagDate AND TA.Id <> TA2.ID)


问:
Does being trivially copyable imply being nothrow copyable?
Alternatively, is there an example of a type with a copy constructor that can throw, but is nontheless trivial?
And if not, does that imply that the is_nothrow_copy_constructible_v<T> should be true whenever is_trivially_copy_constructible_v<T> is true?

Note that according to the standard (latest draft [23.15.4.3]), for a type T to be nothrow copyable, we need the expression T t(declval<const T&>()); to be a well-formed variable definition that is known not to throw any exceptions. This wording seems to be somewhat vauge to me - what does it mean for something to be known? Should the noexcept specifier be sufficient to establish that knowledge? or maybe the determination is left to the implementation?

Edit: I realize there's a difference between being trivially copyable, and being trivially copy constructible. My focus is on the latter.

答:
Does being trivially copyable imply being nothrow copyable?

No. For example:

```<code>struct X {
    X(X&& ) = default;
    X(X const& ) = delete;
};
</code>```

This type is trivially copyable, but not nothrow copyable... or even copyable at all.

However, given that a type is copyable† and trivially copyable, then it must be copyable without throwing (any potential exception would have to come from a non-trivial copy, which can't exist).

†Simply defaulting a copy constructor but marking it noexcept(false) defines it as deleted, so such a type would not be copyable.

Body:
Does being trivially copyable imply being nothrow copyable?

No. For example:

struct X {
    X(X&& ) = default;
    X(X const& ) = delete;
};

This type is trivially copyable, but not nothrow copyable... or even copyable at all.

However, given that a type is copyable† and trivially copyable, then it must be copyable without throwing (any potential exception would have to come from a non-trivial copy, which can't exist).

†Simply defaulting a copy constructor but marking it noexcept(false) defines it as deleted, so such a type would not be copyable.


问:
Notepad++ How do I find and replace part of a directory/file location string?
I'm trying to replace the middle of a directory string. I know the first two folders will always be the same but the middle is always different. Also the file names will always be different.

For example:

Finding: c:/Users/owner/someFolder/someOtherFolder/filename.png

Replacing with: c:/Users/owner/newFolder/filename.png

The amount of folders from owner to the file is varies. The file type will always be png and c:/Users/owner/ is constant.

答:
Just use regular expresion replace

for example :

replace this :
c:/Users/owner/someFolder/(.*)/filename.png     or what ever you want to use instead of (.*)

and replace with what ever you want

Make sure you check the option that says replace using regular expression on the find and replace window otherwise this wont work


问:
How to change value in list for calendar?
The goal of my function is to book a slot in that calendar corresponding to the parameters day and time  - booking is done by changing the value in the calendar to “X” (to indicate that day/time is booked). Here is the code I have so far:

```<code>def find_index(val, seq):
    for index in range(len(seq)):
        place = seq[index]
        if place == val:
            return index
        else:
            return int("-1")

def init_nested_list(size_outer, size_inner):
    cal = []
    for outer_index in range(size_outer):
        nested_list = []
        for inner_index in range(size_inner):
            nested_list.append("-")
        cal.append(nested_list)
    return cal

def book_slot(cal,days_labels, times_labels, day, time):
    pos1 = find_index(day, days_labels)
    desired_day = cal[pos1]
    pos2 = find_index(time, times_labels)
    desired_time = desired_day[pos2]
    if desired_day == "X":
        print("We are sorry - that time is not available. Please try again.")
    else:
        print("Appointment is booked.")

days_labels = ["Wednesday","Thursday","Friday"]
times_labels = ["9","10","11"]
cal = init_nested_list(len(days_labels), len(times_labels))
print("before" , cal)
book_slot(cal, days_labels, times_labels, "Friday", "10")
print("after" , cal)
</code>```

This is the output I'm getting:

```<code>before [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
Appointment is booked.
after [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
</code>```

This is the output I should be getting:

```<code>before [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
Appointment is booked.
after [['-', '-', '-'], ['-', '-', '-'], ['-', 'X', '-']]
We are sorry - that time is not available. Please try again.
</code>```

As you can see, the correct output books the second element in the nested list(Friday at 10), but for my code it is not. I know desired_day is the day in cal that the user wants to book, but I'm just unsure of how to properly obtain that, and assign it to the string "X" when it is booked by the user. I also know that there is a coding error in the book_slot function that is causing this, but once again, I'm just unsure what it is...help please?

答: Nowhere in book_slot do you assign X to anything.  I should think you could use pos1 and pos2 to identify the slot to assign to.

Body:
The goal of my function is to book a slot in that calendar corresponding to the parameters day and time  - booking is done by changing the value in the calendar to “X” (to indicate that day/time is booked). Here is the code I have so far:

def find_index(val, seq):
    for index in range(len(seq)):
        place = seq[index]
        if place == val:
            return index
        else:
            return int("-1")

def init_nested_list(size_outer, size_inner):
    cal = []
    for outer_index in range(size_outer):
        nested_list = []
        for inner_index in range(size_inner):
            nested_list.append("-")
        cal.append(nested_list)
    return cal

def book_slot(cal,days_labels, times_labels, day, time):
    pos1 = find_index(day, days_labels)
    desired_day = cal[pos1]
    pos2 = find_index(time, times_labels)
    desired_time = desired_day[pos2]
    if desired_day == "X":
        print("We are sorry - that time is not available. Please try again.")
    else:
        print("Appointment is booked.")

days_labels = ["Wednesday","Thursday","Friday"]
times_labels = ["9","10","11"]
cal = init_nested_list(len(days_labels), len(times_labels))
print("before" , cal)
book_slot(cal, days_labels, times_labels, "Friday", "10")
print("after" , cal)

This is the output I'm getting:

before [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
Appointment is booked.
after [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]

This is the output I should be getting:

before [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
Appointment is booked.
after [['-', '-', '-'], ['-', '-', '-'], ['-', 'X', '-']]
We are sorry - that time is not available. Please try again.

As you can see, the correct output books the second element in the nested list(Friday at 10), but for my code it is not. I know desired_day is the day in cal that the user wants to book, but I'm just unsure of how to properly obtain that, and assign it to the string "X" when it is booked by the user. I also know that there is a coding error in the book_slot function that is causing this, but once again, I'm just unsure what it is...help please?


问:
Functional pipes in python like %>% from R's magrittr
In R (thanks to magrittr) you can now perform operations with a more functional piping syntax via %>%. This means that instead of coding this:

```<code>> as.Date("2014-01-01")
> as.character((sqrt(12)^2)
</code>```

You could also do this:

```<code>> "2014-01-01" %>% as.Date
> 12 %>% sqrt %>% .^2 %>% as.character
</code>```

To me this is more readable and this extends to use cases beyond the dataframe. Does the python language have support for something similar?

答:
Adding my 2c. I personally use package fn for functional style programming. Your example translates into

```<code>from fn import F, _
from math import sqrt

(F(sqrt) >> _**2 >> str)(12)
</code>```

F is a wrapper class with functional-style syntactic sugar for partial application and composition. _ is a Scala-style constructor for anonymous functions (similar to Python's lambda); it represents a variable, hence you can combine several _ objects in one expression to get a function with more arguments (e.g. _ + _ is equivalent to lambda a, b: a + b). F(sqrt) >> _**2 >> str results in a Callable object that can be used as many times as you want.

ContentLicense: CC BY-SA 4.0

Body:
In R (thanks to magrittr) you can now perform operations with a more functional piping syntax via %>%. This means that instead of coding this:

> as.Date("2014-01-01")
> as.character((sqrt(12)^2)

You could also do this:

> "2014-01-01" %>% as.Date
> 12 %>% sqrt %>% .^2 %>% as.character

To me this is more readable and this extends to use cases beyond the dataframe. Does the python language have support for something similar?

Body:
Adding my 2c. I personally use package fn for functional style programming. Your example translates into

from fn import F, _
from math import sqrt

(F(sqrt) >> _**2 >> str)(12)

F is a wrapper class with functional-style syntactic sugar for partial application and composition. _ is a Scala-style constructor for anonymous functions (similar to Python's lambda); it represents a variable, hence you can combine several _ objects in one expression to get a function with more arguments (e.g. _ + _ is equivalent to lambda a, b: a + b). F(sqrt) >> _**2 >> str results in a Callable object that can be used as many times as you want.


问:
Flask-SocketIO + uWSGI. Emit with Mule worker
Recently I'm implementing WebSocket support in my Flask app.

Setup looks as follow:
    1. Python 2.7
    2. Flask + Flask-SocketIo
    3. SocketIO (Client side)
    4. NGINX as proxy
    5. uWSGI 2.0.13 + it's WebSocket with Gevent (Monkey-patched)

I've manage to enable socket connection but I'm struggling on synchronization of emits between UWSGI Workers, single mule especially.

I have dedicated UWSGI mule to monit some stuff and reports the state every 30 secs, broadcasting it to connected clients. If I allow my task to run on any available worker (not only mule dedicated) emit reaches only to client that was previously server by exact same process e.g:
Client request was served by Worker #6 with (400 PID) and established Socket connection.
Later one mule task was served by very the same Worker so client received the Emit) If any other worker processed that task, emit is not cached by Client.

With single worker mode everything works fine, but that is obviously not acceptable solution.

Here is some tech details:
uwsgi.ini

```<code>[uwsgi]
#application's base folder
base = /home/ubuntu/application_test

#python module to import
app = manage
module = %(app)

home = %(base)/venv
virtualenv = %(base)/venv
pythonpath = %(base)

#socket file's location
socket = %(base)/application_test.sock

#permissions for the socket file
chmod-socket = 666

#the variable that holds a flask application inside the module imported at
line #6
callable = app

#location of log files
logto = /var/log/uwsgi/%n.log

processes = 10

#WebSocket
http-websockets = true

gevent = 1000
enable-threads = true
die-on-therm = true

vacuum = true

mule=%(base)/application_test/uwsgi_mules/metrics_mule.py
</code>```

Flask App

```<code>(...)
from flask_socketio import SocketIO
app = Flask(__name__)
socketio = SocketIO(app,message_queue='redis://')
(...)
</code>```

Worker Emit Code

```<code>socket = SocketIO(message_queue='redis://')

def broad_cast_server_info(state, health):
    socket.emit('sys_state', health)
    socket.emit('system_snapshot', state)
</code>```

Client Side

```<code>        socket.on('sys_state', function(data){
            (...)
            }
        });
</code>```

If I use client side socket.emit with acknowledgment response, everything works fine.

When In mule I simply import socketio and call emit on it I face problem described above. However If I follow:
https://flask-socketio.readthedocs.io/en/latest/#emitting-from-an-external-process

I'm getting an redis error every time mule runs its job.

File "/home/ubuntu/application_test/venv/local/lib/python2.7/site-packages/flask_socketio/init.py", line 365, in emit
      skip_sid=skip_sid, callback=callback, **kwargs)
    File "/home/ubuntu/application_test/venv/local/lib/python2.7/site-packages/socketio/server.py", line 228, in emit
      **kwargs)
    File "/home/ubuntu/application_test/venv/local/lib/python2.7/site-packages/socketio/pubsub_manager.py", line 66, in emit
      'skip_sid': skip_sid, 'callback': callback})
    File "/home/ubuntu/application_test/venv/local/lib/python2.7/site-packages/socketio/redis_manager.py", line 62, in _publish
      return self.redis.publish(self.channel, pickle.dumps(data))
    File "/home/ubuntu/application_test/venv/local/lib/python2.7/site-packages/redis/client.py", line 2034, in publish
      return self.execute_command('PUBLISH', channel, message)
    File "/home/ubuntu/application_test/venv/local/lib/python2.7/site-packages/redis/client.py", line 673, in execute_command
      connection.send_command(*args)
    File "/home/ubuntu/application_test/venv/local/lib/python2.7/site-packages/redis/connection.py", line 610, in send_command
      self.send_packed_command(self.pack_command(*args))
    File "/home/ubuntu/application_test/venv/local/lib/python2.7/site-packages/redis/connection.py", line 585, in send_packed_command
      self.connect()
    File "/home/ubuntu/application_test/venv/local/lib/python2.7/site-packages/redis/connection.py", line 489, in connect
      raise ConnectionError(self._error_message(e))
  redis.exceptions.ConnectionError: Error -2 connecting to redispass:6379. Name or service not known.

PIP FREEZE:

```<code>alabaster==0.7.9
amqp==2.1.1
aniso8601==1.2.0
appdirs==1.4.3
astroid==1.4.8
Babel==2.3.4
beautifulsoup4==4.5.1
certifi==2017.11.5
chardet==3.0.4
click==6.7
decorator==4.0.11
defusedxml==0.5.0
dict2xml==1.5
dicttoxml==1.7.4
docopt==0.6.2
enum-compat==0.0.2
enum34==1.1.6
eventlet==0.21.0
Flask==0.12
Flask-Login==0.4.0
Flask-RESTful==0.3.5
flask-restful-swagger-2==0.33
Flask-Script==2.0.5
Flask-SocketIO==2.9.2
flask-swagger-ui==0.0.3
Flask-WTF==0.14.2
gevent==1.2.2
greenlet==0.4.12
html5lib==1.0b8
hurry.filesize==0.9
hypchat==0.21
idna==2.6
infinity==1.4
intervals==0.8.0
itsdangerous==0.24
Jinja2==2.9.5
jira==1.0.10
lazy-object-proxy==1.2.2
lxml==3.8.0
MarkupSafe==1.0
monotonic==1.4
oauthlib==2.0.2
olefile==0.44
ordereddict==1.1
packaging==16.8
pbr==3.0.1
pdfkit==0.6.1
Pillow==4.0.0
pql==0.4.3
psutil==5.4.1
py==1.4.34
pymongo==3.4.0
pyodbc==4.0.15
pyparsing==2.2.0
PyPDF2==1.26.0
pypyodbc==1.3.4
python-dateutil==2.6.0
python-engineio==2.0.1
python-memcached==1.58
python-socketio==1.8.3
pytz==2016.10
reportlab==3.4.0
requests==2.13.0
requests-oauthlib==0.8.0
requests-toolbelt==0.8.0
six==1.10.0
SQLAlchemy==1.1.6
SQLAlchemy-Utils==0.32.14
suds==0.4
urllib3==1.22
validators==0.11.3
vine==1.1.3
webencodings==0.5.1
Werkzeug==0.12
wrapt==1.10.10
WTForms==2.1
xmltodict==0.10.2
WTForms-Components==0.10.3
</code>```

I've red about following cases:
- monkey-patch Gevent
- early-monkey-patch Gevent via uwsgi (suppose to work on uWSGI 2.1)
- add Redis queue

Is there any other method to make Flask-SocketIO works in sync with uWSGI workers?

答:
it seems to be a problem with redis
have you installed and started it ?
run
redis-cli -h localhost -p 6379
to make sure flask-socketIO can connect to it

Body:
Recently I'm implementing WebSocket support in my Flask app.

Setup looks as follow:
    1. Python 2.7
    2. Flask + Flask-SocketIo
    3. SocketIO (Client side)
    4. NGINX as proxy
    5. uWSGI 2.0.13 + it's WebSocket with Gevent (Monkey-patched)

I've manage to enable socket connection but I'm struggling on synchronization of emits between UWSGI Workers, single mule especially.

I have dedicated UWSGI mule to monit some stuff and reports the state every 30 secs, broadcasting it to connected clients. If I allow my task to run on any available worker (not only mule dedicated) emit reaches only to client that was previously server by exact same process e.g:
Client request was served by Worker #6 with (400 PID) and established Socket connection.
Later one mule task was served by very the same Worker so client received the Emit) If any other worker processed that task, emit is not cached by Client.

With single worker mode everything works fine, but that is obviously not acceptable solution.

Here is some tech details:
uwsgi.ini

[uwsgi]
#application's base folder
base = /home/ubuntu/application_test

#python module to import
app = manage
module = %(app)

home = %(base)/venv
virtualenv = %(base)/venv
pythonpath = %(base)

#socket file's location
socket = %(base)/application_test.sock

#permissions for the socket file
chmod-socket = 666

#the variable that holds a flask application inside the module imported at
line #6
callable = app

#location of log files
logto = /var/log/uwsgi/%n.log

processes = 10

#WebSocket
http-websockets = true

gevent = 1000
enable-threads = true
die-on-therm = true

vacuum = true

mule=%(base)/application_test/uwsgi_mules/metrics_mule.py

Flask App

(...)
from flask_socketio import SocketIO
app = Flask(__name__)
socketio = SocketIO(app,message_queue='redis://')
(...)

Worker Emit Code

socket = SocketIO(message_queue='redis://')

def broad_cast_server_info(state, health):
    socket.emit('sys_state', health)
    socket.emit('system_snapshot', state)

Client Side

        socket.on('sys_state', function(data){
            (...)
            }
        });

If I use client side socket.emit with acknowledgment response, everything works fine.

When In mule I simply import socketio and call emit on it I face problem described above. However If I follow:
https://flask-socketio.readthedocs.io/en/latest/#emitting-from-an-external-process

I'm getting an redis error every time mule runs its job.

File "/home/ubuntu/application_test/venv/local/lib/python2.7/site-packages/flask_socketio/init.py", line 365, in emit
      skip_sid=skip_sid, callback=callback, **kwargs)
    File "/home/ubuntu/application_test/venv/local/lib/python2.7/site-packages/socketio/server.py", line 228, in emit
      **kwargs)
    File "/home/ubuntu/application_test/venv/local/lib/python2.7/site-packages/socketio/pubsub_manager.py", line 66, in emit
      'skip_sid': skip_sid, 'callback': callback})
    File "/home/ubuntu/application_test/venv/local/lib/python2.7/site-packages/socketio/redis_manager.py", line 62, in _publish
      return self.redis.publish(self.channel, pickle.dumps(data))
    File "/home/ubuntu/application_test/venv/local/lib/python2.7/site-packages/redis/client.py", line 2034, in publish
      return self.execute_command('PUBLISH', channel, message)
    File "/home/ubuntu/application_test/venv/local/lib/python2.7/site-packages/redis/client.py", line 673, in execute_command
      connection.send_command(*args)
    File "/home/ubuntu/application_test/venv/local/lib/python2.7/site-packages/redis/connection.py", line 610, in send_command
      self.send_packed_command(self.pack_command(*args))
    File "/home/ubuntu/application_test/venv/local/lib/python2.7/site-packages/redis/connection.py", line 585, in send_packed_command
      self.connect()
    File "/home/ubuntu/application_test/venv/local/lib/python2.7/site-packages/redis/connection.py", line 489, in connect
      raise ConnectionError(self._error_message(e))
  redis.exceptions.ConnectionError: Error -2 connecting to redispass:6379. Name or service not known.

PIP FREEZE:

alabaster==0.7.9
amqp==2.1.1
aniso8601==1.2.0
appdirs==1.4.3
astroid==1.4.8
Babel==2.3.4
beautifulsoup4==4.5.1
certifi==2017.11.5
chardet==3.0.4
click==6.7
decorator==4.0.11
defusedxml==0.5.0
dict2xml==1.5
dicttoxml==1.7.4
docopt==0.6.2
enum-compat==0.0.2
enum34==1.1.6
eventlet==0.21.0
Flask==0.12
Flask-Login==0.4.0
Flask-RESTful==0.3.5
flask-restful-swagger-2==0.33
Flask-Script==2.0.5
Flask-SocketIO==2.9.2
flask-swagger-ui==0.0.3
Flask-WTF==0.14.2
gevent==1.2.2
greenlet==0.4.12
html5lib==1.0b8
hurry.filesize==0.9
hypchat==0.21
idna==2.6
infinity==1.4
intervals==0.8.0
itsdangerous==0.24
Jinja2==2.9.5
jira==1.0.10
lazy-object-proxy==1.2.2
lxml==3.8.0
MarkupSafe==1.0
monotonic==1.4
oauthlib==2.0.2
olefile==0.44
ordereddict==1.1
packaging==16.8
pbr==3.0.1
pdfkit==0.6.1
Pillow==4.0.0
pql==0.4.3
psutil==5.4.1
py==1.4.34
pymongo==3.4.0
pyodbc==4.0.15
pyparsing==2.2.0
PyPDF2==1.26.0
pypyodbc==1.3.4
python-dateutil==2.6.0
python-engineio==2.0.1
python-memcached==1.58
python-socketio==1.8.3
pytz==2016.10
reportlab==3.4.0
requests==2.13.0
requests-oauthlib==0.8.0
requests-toolbelt==0.8.0
six==1.10.0
SQLAlchemy==1.1.6
SQLAlchemy-Utils==0.32.14
suds==0.4
urllib3==1.22
validators==0.11.3
vine==1.1.3
webencodings==0.5.1
Werkzeug==0.12
wrapt==1.10.10
WTForms==2.1
xmltodict==0.10.2
WTForms-Components==0.10.3

I've red about following cases:
- monkey-patch Gevent
- early-monkey-patch Gevent via uwsgi (suppose to work on uWSGI 2.1)
- add Redis queue

Is there any other method to make Flask-SocketIO works in sync with uWSGI workers?


问:
Android can't find any BLE devices
Here's he problem. I've developed an app for iOS to control an BLE LED device (and a few other things). Everything works fine and smooth. Now I wanted develop the same app for android and I already fail at the scanning of BLE devices. I have tried a few tutorials and sample codes but whatever I do I can't find any devices. I work on a Moto G4 Play. The bluetooth works and I can pair devices in the settings but it won't work with any sample code/tutorial I've tried.
For example this one:
https://github.com/kaviles/BLE_Tutorials

I build this app as it is and it can't find anything.

So I downloaded a BLE Scanner from the Playstore and that works fine to and finds all devices.

I know it's hard to say without any sample code but I've tried so many and I'm not sure if I miss something completely basic.

答:
For Xamarin, API>=24
I figured out how to make it work, it might not be intuitive that you need COARSE_LOCATION permission to get the Bluetooth to work. Go to the project on Xamarin > right click > Options > Check the boxes for Bluetooth, and location permissions > OK --> rebuild on device</p>

Title: Android can't find any BLE devices


问:
How to change the braces/parenthesis colors in Visual Studio
I am not talking about the highlight colors but the actual colors. I got a color scheme with light background color but the braces/parentheses are barely visible. Anyone knows how to change this?

Btw this is for C# because C++ seems to color braces/parentheses using operator color.

答:
You can change the Punctuation color in VS but it will actually change the color of all elements that fall in the Punctuation category.

If you want a solution which you can fine tune you can use the Semantic Highlighter Extension that we have developed. It can color different parts
 of code such as braces, brackets, parenthesis, angle brackets and even properties, fields, parameters, namespaces and more.

You can install it as a Visual Studio Extension. It is available in the gallery - just search for "Semantic Highlighter"

OwnerDisplayName: Joan Venge

LastEditorDisplayName: AnthonyWJones


问:
x86 Assembly with gas on linux: multiple definitions of 'main'
I'm starting out with programming in Assembly in x86 and I'm following a guide for that. I'm using gas to compile on a linux virtual machine.

I'm trying to run a simple empty program where main routine exits the program immediately. That's the first task in the guide I'm following. My code is saved in a file hello.s and it looks like this:

```<code>.global main

main:
  movq   %rsp, %rbp
  mov   $0, %rdi
  call   exit
</code>```

In the terminal I navigate to the directory of the file and try to run it like this:

```<code>gcc -o hello.o hello.s -no-pie ./hello.s
</code>```

I get an error saying:

```<code>/tmp/cc62hr1F.o: In function 'main':
(.text+0x0): multiple definition of 'main'
/tmp/ccwMutY1.o(.text+0x0): first defined here
collect2: error: ld returned 1 exit status
</code>```

What does this error mean and how to fix it? Thank you in advance.

答:
EDIT/SOLUTION: I figured out what was wrong. In the terminal I should run it like this:

```<code>gcc -o hello.o hello.s -no-pie
./hello.o
</code>```

These are two seperate commands. I wrote them in one line. And the file to run has to have the extensions .o not .s

Body:
I'm starting out with programming in Assembly in x86 and I'm following a guide for that. I'm using gas to compile on a linux virtual machine.

I'm trying to run a simple empty program where main routine exits the program immediately. That's the first task in the guide I'm following. My code is saved in a file hello.s and it looks like this:

.global main

main:
  movq   %rsp, %rbp
  mov   $0, %rdi
  call   exit

In the terminal I navigate to the directory of the file and try to run it like this:

gcc -o hello.o hello.s -no-pie ./hello.s

I get an error saying:

/tmp/cc62hr1F.o: In function 'main':
(.text+0x0): multiple definition of 'main'
/tmp/ccwMutY1.o(.text+0x0): first defined here
collect2: error: ld returned 1 exit status

What does this error mean and how to fix it? Thank you in advance.

Body:
EDIT/SOLUTION: I figured out what was wrong. In the terminal I should run it like this:

gcc -o hello.o hello.s -no-pie
./hello.o

These are two seperate commands. I wrote them in one line. And the file to run has to have the extensions .o not .s


问:
mirror prime generator python
I am currently enrolled in a Python programming course and last week we got a homework problem which was to Develop a program to generate all prime numbers less or equal to n whose mirror is also prime, I can't see where I am going wrong, please help!

```<code>import math

def mirror_prime(n):
    answer = True
    # Test 0 and 1
    if n==0 or n==1:
        answer = False
    # End if

    # Test even numbers
    if n != 2 and n%2==0:
        answer= False
    # End if

    # Test if there is a proper odd divisor
        for d in range (3, int(math.sqrt(n))+1, 2):
            if n%d==0:
                answer=False
            # End if
        # End for

    #Reverse n
    mirror_n = int(str(n)[::-1])
    mirror_answer = True

    # Test 0 and 1
    if mirror_n==0 or mirror_n==1:
        mirror_answer = False
    # End if

def mirror_prime_generator(n):
    for i in range(3, n+1):
        print (mirror_prime(i))
</code>```

I am expecting to get a list of all prime numbers whose mirror is also prime less or equal to n

The result i get when i put mirror_prime_generator(n) into the shell, it justs prints none however many times n is, so if n is 23 it will print none 23 times

答:
There were still some bugs. The indentation of for loops was wrong (they were inside the if) and you sometimes used n instead of mirror_n.

Your code

Here's a working code with the least amount of change:

```<code>import math

def mirror_prime(n):
    answer = True
    # Test 0 and 1
    if n==0 or n==1:
        answer = False
    # End if

    # Test even numbers
    if n != 2 and n%2==0:
        answer= False
    # End if

    # Test if there is a proper odd divisor
    for d in range (3, int(math.sqrt(n))+1, 2):
        if n%d==0:
            answer=False
        # End if

    # End for

    #Reverse n
    mirror_n = int(str(n)[::-1])
    mirror_answer = True

    # Test 0 and 1
    if mirror_n==0 or mirror_n==1:
        mirror_answer = False
    # End if
    # Test even numbers
    if mirror_n != 2 and mirror_n%2==0:
        mirror_answer= False
    # End if

    # Test if there is a proper odd divisor
    for d in range (3, int(math.sqrt(mirror_n))+1, 2):
        if mirror_n%d==0:
            mirror_answer=False
        # End if

    # End for

    if answer and mirror_answer==True:
        return n, mirror_n

def mirror_prime_generator(n):
    for i in range(3, n+1):
        if mirror_prime(i):
            print(i)

mirror_prime_generator(100)
# 3
# 5
# 7
# 11
# 13
# 17
# 31
# 37
# 71
# 73
# 79
# 97
</code>```

Shorter version

You should try to avoid using duplicate code. The test for n and mirror_n is exactly the same, so you could put it inside a function:

```<code>def is_prime(n):
    if n == 2:
        return True
    if n < 2 or n % 2 == 0:
        return False
    for d in range(3, int(n**0.5) + 1, 2):
        if n % d == 0:
            return False
    return True

def is_mirror_prime(n):
    mirror_n = int(str(n)[::-1])
    return mirror_n != n and is_prime(n) and is_prime(mirror_n)

print([n for n in range(1000) if is_mirror_prime(n)])
# [13, 17, 31, 37, 71, 73, 79, 97, 107, 113, 149, 157, 167, 179, 199, 311, 337, 347, 359, 389, 701, 709, 733, 739, 743, 751, 761, 769, 907, 937, 941, 953, 967, 971, 983, 991]
</code>```

Title: mirror prime generator python

Body:
I am currently enrolled in a Python programming course and last week we got a homework problem which was to Develop a program to generate all prime numbers less or equal to n whose mirror is also prime, I can't see where I am going wrong, please help!

import math

def mirror_prime(n):
    answer = True
    # Test 0 and 1
    if n==0 or n==1:
        answer = False
    # End if

    # Test even numbers
    if n != 2 and n%2==0:
        answer= False
    # End if

    # Test if there is a proper odd divisor
        for d in range (3, int(math.sqrt(n))+1, 2):
            if n%d==0:
                answer=False
            # End if
        # End for

    #Reverse n
    mirror_n = int(str(n)[::-1])
    mirror_answer = True

    # Test 0 and 1
    if mirror_n==0 or mirror_n==1:
        mirror_answer = False
    # End if

def mirror_prime_generator(n):
    for i in range(3, n+1):
        print (mirror_prime(i))

I am expecting to get a list of all prime numbers whose mirror is also prime less or equal to n

The result i get when i put mirror_prime_generator(n) into the shell, it justs prints none however many times n is, so if n is 23 it will print none 23 times

Body:
There were still some bugs. The indentation of for loops was wrong (they were inside the if) and you sometimes used n instead of mirror_n.

Your code

Here's a working code with the least amount of change:

import math

def mirror_prime(n):
    answer = True
    # Test 0 and 1
    if n==0 or n==1:
        answer = False
    # End if

    # Test even numbers
    if n != 2 and n%2==0:
        answer= False
    # End if

    # Test if there is a proper odd divisor
    for d in range (3, int(math.sqrt(n))+1, 2):
        if n%d==0:
            answer=False
        # End if

    # End for

    #Reverse n
    mirror_n = int(str(n)[::-1])
    mirror_answer = True

    # Test 0 and 1
    if mirror_n==0 or mirror_n==1:
        mirror_answer = False
    # End if
    # Test even numbers
    if mirror_n != 2 and mirror_n%2==0:
        mirror_answer= False
    # End if

    # Test if there is a proper odd divisor
    for d in range (3, int(math.sqrt(mirror_n))+1, 2):
        if mirror_n%d==0:
            mirror_answer=False
        # End if

    # End for

    if answer and mirror_answer==True:
        return n, mirror_n

def mirror_prime_generator(n):
    for i in range(3, n+1):
        if mirror_prime(i):
            print(i)

mirror_prime_generator(100)
# 3
# 5
# 7
# 11
# 13
# 17
# 31
# 37
# 71
# 73
# 79
# 97

Shorter version

You should try to avoid using duplicate code. The test for n and mirror_n is exactly the same, so you could put it inside a function:

def is_prime(n):
    if n == 2:
        return True
    if n < 2 or n % 2 == 0:
        return False
    for d in range(3, int(n**0.5) + 1, 2):
        if n % d == 0:
            return False
    return True

def is_mirror_prime(n):
    mirror_n = int(str(n)[::-1])
    return mirror_n != n and is_prime(n) and is_prime(mirror_n)

print([n for n in range(1000) if is_mirror_prime(n)])
# [13, 17, 31, 37, 71, 73, 79, 97, 107, 113, 149, 157, 167, 179, 199, 311, 337, 347, 359, 389, 701, 709, 733, 739, 743, 751, 761, 769, 907, 937, 941, 953, 967, 971, 983, 991]


问:
How to remove artifacting from text being drawn into a bitmap
I have a background bitmap if you will and I'm drawing another bitmap with font into the background bitmap. When just drawn on top of each other and zoomed in the level I'm needing they appear perfectly without artifacting and exactly how I want it. But for my purpose I'm needing to merge the font bitmap into the background bitmap so it essentially becomes one item. I obviously need it to be done at run-time and the solution I'm using is this....

```<code>canvas2 = new Canvas(backgroundBitmap);
canvas2.drawBitmap(fontBitmap.getBitmap(), null, rects.get(backgroundRectIndex), null);
invalidate();
</code>```

Now when I zoom into the level I'm needing the font has artifacting. I'm fairly new to graphics and have read several articles and questions about similar issues and I've tried playing with the dithering in the paint and using it in canvas2.drawBitmap instead of null, but nothing seems to be helping. I came across this...

This does not apply for the case that an application creates an in-memory bitmap internally and draws something on it, for later display on the screen. The platform auto-scales such bitmaps on the fly, at draw time. Other side effects of such a case might be that fonts drawn in such a bitmap will be scaled at the bitmap level, when the off-screen bitmap is finally rendered to the display, resulting in scaling artifacts.

link text

Which sounds like it might be my issue, but how do I resolve that? Any help would be much appreciated.

答:
If you're scaling the bitmap, make sure to set the filterBitmap flag off.

On the paint it should be:

```<code>paint.setFilterBitmap(false);
</code>```

Body:
I have a background bitmap if you will and I'm drawing another bitmap with font into the background bitmap. When just drawn on top of each other and zoomed in the level I'm needing they appear perfectly without artifacting and exactly how I want it. But for my purpose I'm needing to merge the font bitmap into the background bitmap so it essentially becomes one item. I obviously need it to be done at run-time and the solution I'm using is this....

canvas2 = new Canvas(backgroundBitmap);
canvas2.drawBitmap(fontBitmap.getBitmap(), null, rects.get(backgroundRectIndex), null);
invalidate();

Now when I zoom into the level I'm needing the font has artifacting. I'm fairly new to graphics and have read several articles and questions about similar issues and I've tried playing with the dithering in the paint and using it in canvas2.drawBitmap instead of null, but nothing seems to be helping. I came across this...

This does not apply for the case that an application creates an in-memory bitmap internally and draws something on it, for later display on the screen. The platform auto-scales such bitmaps on the fly, at draw time. Other side effects of such a case might be that fonts drawn in such a bitmap will be scaled at the bitmap level, when the off-screen bitmap is finally rendered to the display, resulting in scaling artifacts.

link text

Which sounds like it might be my issue, but how do I resolve that? Any help would be much appreciated.

Body:
If you're scaling the bitmap, make sure to set the filterBitmap flag off.

On the paint it should be:

paint.setFilterBitmap(false);


问:
Vertical table rows with fixed header and first column
I'm currently trying to create a table with fixed 1st top row and fixed 1st left column.

There are plenty of solutions to this for a traditional table, but this table must be laid out with vertically stacked rows because of the way the data is going to be injected. The table columns (vertical rows) must also be able to overflow the parent and scroll.

At a minimum I would like the leftmost column fixed, the header (Loc 1, 2, 3 ) etc would be a nice to have.  I've tried this with a position:absolute but that doesn't seem to work.

```<code><div style="postion:relative;">
<div class="table-responsive top-margin ">
    <table class="table table-striped table-hover">
        <tr class="heads-col">
            <th>Data Decriptors</th>
            <th>Data Description 1</th>
            <th>Data Description 2</th>
            <th>Data Description 3</th>
            <th>Data Description 4</th>
            <th>Data Description 5</th>
            <th>Data Description 6</th>
            <th>Data Description 7</th>
            <th>Data Description 8</th>
            <th>Data Description 9</th>
            <th>Data Description 10</th>
            <th>Data Description 11</th>
            <th>Data Description 12</th>
        </tr>
        <tr>
            <th>Location 1</th>
            <td>Entry First Line 1</td>
            <td>Entry First Line 2</td>
            <td>Entry First Line 3</td>
            <td>Entry First Line 4</td>
            <td>Entry First Line 1</td>
            <td>Entry First Line 2</td>
            <td>Entry First Line 3</td>
            <td>Entry First Line 4</td>
            <td>Entry First Line 1</td>
            <td>Entry First Line 2</td>
            <td>Entry First Line 3</td>
            <td>Entry First Line 4</td>
        </tr>
    </table>
    </div>
</div>
</code>```

http://jsfiddle.net/1xzb0x3s/3/

This solution was pretty much perfect: http://www.matts411.com/static/demos/grid/index.html

But I could not get it to work with vertical rows.

Any help much appreciated.

答:
If you set the cells in the leftmost column to "position:relative" and then update style.left with the scroll position of the container it will do the trick. I've added the class "fixed-row" and some JS, there's also a fiddle below.

```<code>var container = window.document.getElementById("container");
container.addEventListener("scroll", function(){
var rowHeader = window.document.getElementsByClassName("fixed-row");
    for(var i=0; i<rowHeader.length; i++) {
        rowHeader[i].style.left = (container.scrollLeft + "px");
    }
}, false);
</code>```

https://jsfiddle.net/jchaplin2/ftt64fxk/

Body:
I'm currently trying to create a table with fixed 1st top row and fixed 1st left column.

There are plenty of solutions to this for a traditional table, but this table must be laid out with vertically stacked rows because of the way the data is going to be injected. The table columns (vertical rows) must also be able to overflow the parent and scroll.

At a minimum I would like the leftmost column fixed, the header (Loc 1, 2, 3 ) etc would be a nice to have.  I've tried this with a position:absolute but that doesn't seem to work.

            Data Decriptors
            Data Description 1
            Data Description 2
            Data Description 3
            Data Description 4
            Data Description 5
            Data Description 6
            Data Description 7
            Data Description 8
            Data Description 9
            Data Description 10
            Data Description 11
            Data Description 12

            Location 1
            Entry First Line 1
            Entry First Line 2
            Entry First Line 3
            Entry First Line 4
            Entry First Line 1
            Entry First Line 2
            Entry First Line 3
            Entry First Line 4
            Entry First Line 1
            Entry First Line 2
            Entry First Line 3
            Entry First Line 4

http://jsfiddle.net/1xzb0x3s/3/

This solution was pretty much perfect: http://www.matts411.com/static/demos/grid/index.html

But I could not get it to work with vertical rows.

Any help much appreciated.

Body:
If you set the cells in the leftmost column to "position:relative" and then update style.left with the scroll position of the container it will do the trick. I've added the class "fixed-row" and some JS, there's also a fiddle below.

var container = window.document.getElementById("container");
container.addEventListener("scroll", function(){
var rowHeader = window.document.getElementsByClassName("fixed-row");
    for(var i=0; i<rowHeader.length; i++) {
        rowHeader[i].style.left = (container.scrollLeft + "px");
    }
}, false);

https://jsfiddle.net/jchaplin2/ftt64fxk/


问:
Return list of values c#
I'm new in Asp and I develop all querys with stored procedures:

I have a method like this:

```<code>  Filler.Fill(new PeriodoLogic().lstConsultaParcial(tabla).ConvertAll(o => (object)o), ref this.radcmbPeriodo, "nPeriodo", "nPeriodo", true);
</code>```

lstConsultaParcial Method:

```<code> public List<object> lstConsultaParcial(object Entidad)
        {
            return new PeriodoData().lstConsultaParcial(Entidad);
        }
</code>```

View:

```<code><td><telerik:RadComboBox runat="server" ID="radcmbPeriodo" Width="200px" MarkFirstMatch="true" Filter="Contains" DropDownAutoWidth="Enabled"
                    EmptyMessage="Seleccionar" ></telerik:RadComboBox></td>
                     <td><asp:RequiredFieldValidator ID="rfv" runat="server" ErrorMessage="<b class='red'>Requerido</b>" ControlToValidate="radcmbPeriodo"></asp:RequiredFieldValidator></td>
</code>```

It fills radcombobox, consulting a simple stored procedure, it receive values, 1,2,3,4,5,6,7,8,9,10,11,12 as:

Image

as you can see it returns values 1 to 12, so I think I dont need consult stored procedure, how can I send simple a list of 1 to 12 instead call stored procedure?

答:
Answer is simple. You don't want to call that function which goes to call the SP.

Using LINQ below, you can quickly generate a list of numbers from 1 to 12.

```<code>List<int> myList = Enumerable.Range(1, 12).ToList();
return myList;
</code>```

This is what you need to return from the method that your Kendo control calls.

Title: Return list of values c#

Body:
I'm new in Asp and I develop all querys with stored procedures:

I have a method like this:

  Filler.Fill(new PeriodoLogic().lstConsultaParcial(tabla).ConvertAll(o => (object)o), ref this.radcmbPeriodo, "nPeriodo", "nPeriodo", true);

lstConsultaParcial Method:

 public List<object> lstConsultaParcial(object Entidad)
        {
            return new PeriodoData().lstConsultaParcial(Entidad);
        }

View:

<telerik:RadComboBox runat="server" ID="radcmbPeriodo" Width="200px" MarkFirstMatch="true" Filter="Contains" DropDownAutoWidth="Enabled"
                    EmptyMessage="Seleccionar" ></telerik:RadComboBox>
                     <asp:RequiredFieldValidator ID="rfv" runat="server" ErrorMessage="Requerido" ControlToValidate="radcmbPeriodo"></asp:RequiredFieldValidator>

It fills radcombobox, consulting a simple stored procedure, it receive values, 1,2,3,4,5,6,7,8,9,10,11,12 as:

Image

as you can see it returns values 1 to 12, so I think I dont need consult stored procedure, how can I send simple a list of 1 to 12 instead call stored procedure?

Body:
Answer is simple. You don't want to call that function which goes to call the SP.

Using LINQ below, you can quickly generate a list of numbers from 1 to 12.

List<int> myList = Enumerable.Range(1, 12).ToList();
return myList;

This is what you need to return from the method that your Kendo control calls.


问:
Python: iterating over tuples in list
right now I have code that is giving me this output:

```[('KOR', [3, 1, 0]), ('ITA', [1, 0, 0]), ('TPE', [0, 1, 1]), ('CHN', [0, 1, 0]), ('JPN', [0, 1, 0]), ('AUS', [0, 0, 1]), ('GBR', [0, 0, 1]), ('UKR', [0, 0, 1])]```

but it needs to be in this form:

```['KOR 3 1 0', 'ITA 1 0 0', 'TPE 0 1 1', 'CHN 0 1 0', 'JPN 0 1 0', 'AUS 0 0 1', 'GBR 0 0 1', 'UKR 0 0 1']```

How do I change the data into the correct form? I have been trying to iterate through the elements, but the closest I've gotten is

```['KOR', 3, 1, 0, 'ITA', 1, 0, 0, 'TPE', 0, 1, 1, 'CHN', 0, 1, 0, 'JPN', 0, 1, 0, 'AUS', 0, 0, 1, 'GBR', 0, 0, 1, 'UKR', 0, 0, 1]```

by using this code

```<code>for item in alist:
    for x in item:
        answer.append(x)

for item in answer:
    if type(item)==str:
        answer2.append(item)
    else:
        for f in item:
            answer2.append(f)
return answer2
</code>```

Thank you in advance!

答:
Provided the same structure, you can easily unwrap it within list comprehension by joining the two indices of each inner list:</p>

```<code>data = [('KOR', [3, 1, 0]), ('ITA', [1, 0, 0]), ('TPE', [0, 1, 1]), ('CHN', [0, 1, 0]),
        ('JPN', [0, 1, 0]), ('AUS', [0, 0, 1]), ('GBR', [0, 0, 1]), ('UKR', [0, 0, 1])]

flattened = [" ".join(str(e) for e in [item[0]] + item[1]) for item in data]
# ['KOR 3 1 0', 'ITA 1 0 0', 'TPE 0 1 1', 'CHN 0 1 0', 'JPN 0 1 0', 'AUS 0 0 1',
#  'GBR 0 0 1', 'UKR 0 0 1']
</code>```

Title: Python: iterating over tuples in list

Body:
right now I have code that is giving me this output:

[('KOR', [3, 1, 0]), ('ITA', [1, 0, 0]), ('TPE', [0, 1, 1]), ('CHN', [0, 1, 0]), ('JPN', [0, 1, 0]), ('AUS', [0, 0, 1]), ('GBR', [0, 0, 1]), ('UKR', [0, 0, 1])]

but it needs to be in this form:

['KOR 3 1 0', 'ITA 1 0 0', 'TPE 0 1 1', 'CHN 0 1 0', 'JPN 0 1 0', 'AUS 0 0 1', 'GBR 0 0 1', 'UKR 0 0 1']

How do I change the data into the correct form? I have been trying to iterate through the elements, but the closest I've gotten is

['KOR', 3, 1, 0, 'ITA', 1, 0, 0, 'TPE', 0, 1, 1, 'CHN', 0, 1, 0, 'JPN', 0, 1, 0, 'AUS', 0, 0, 1, 'GBR', 0, 0, 1, 'UKR', 0, 0, 1]

by using this code

for item in alist:
    for x in item:
        answer.append(x)

for item in answer:
    if type(item)==str:
        answer2.append(item)
    else:
        for f in item:
            answer2.append(f)
return answer2

Thank you in advance!

Body:
Provided the same structure, you can easily unwrap it within list comprehension by joining the two indices of each inner list:

data = [('KOR', [3, 1, 0]), ('ITA', [1, 0, 0]), ('TPE', [0, 1, 1]), ('CHN', [0, 1, 0]),
        ('JPN', [0, 1, 0]), ('AUS', [0, 0, 1]), ('GBR', [0, 0, 1]), ('UKR', [0, 0, 1])]

flattened = [" ".join(str(e) for e in [item[0]] + item[1]) for item in data]
# ['KOR 3 1 0', 'ITA 1 0 0', 'TPE 0 1 1', 'CHN 0 1 0', 'JPN 0 1 0', 'AUS 0 0 1',
#  'GBR 0 0 1', 'UKR 0 0 1']


问:
Python Interactive Shell Type Application
I want to create an interactive shell type application. For example:

```<code>> ./app.py

Enter a command to do something. eg `create name price`.
For to get help, enter "help" (without quotes)

> create item1 10
Created "item1", cost $10

> del item1
Deleted item1

> exit
...
</code>```

I could of course use a infinte loop getting user input, splitting the line to get the individual parts of the command, but is there a better way? Even in PHP (Symfony 2 Console) they allow you to create console commands to help setup web applications for example. Is there something like that in Python (I am using Python 3)

答:
Another approach to building interactive applications like this is by using the cmd module.

```<code># app.py
from cmd import Cmd

class MyCmd(Cmd):

    prompt = "> "

    def do_create(self, args):
        name, cost = args.rsplit(" ", 1) # args is string of input after create
        print('Created "{}", cost ${}'.format(name, cost))

    def do_del(self, name):
        print('Deleted {}'.format(name))

    def do_exit(self, args):
        raise SystemExit()

if __name__ == "__main__":

    app = MyCmd()
    app.cmdloop('Enter a command to do something. eg `create name price`.')
</code>```

And here is the output of running the above code (if the above code was in a file named app.py):

```<code>$ python app.py
Enter a command to do something. eg `create name price`.
> create item1 10
Created "item1", cost $10
> del item1
Deleted item1
> exit
$
</code>```

Body:
I want to create an interactive shell type application. For example:

> ./app.py

Enter a command to do something. eg `create name price`.
For to get help, enter "help" (without quotes)

> create item1 10
Created "item1", cost $10

> del item1
Deleted item1

> exit
...

I could of course use a infinte loop getting user input, splitting the line to get the individual parts of the command, but is there a better way? Even in PHP (Symfony 2 Console) they allow you to create console commands to help setup web applications for example. Is there something like that in Python (I am using Python 3)

Body:
Another approach to building interactive applications like this is by using the cmd module.

# app.py
from cmd import Cmd

class MyCmd(Cmd):

    prompt = "> "

    def do_create(self, args):
        name, cost = args.rsplit(" ", 1) # args is string of input after create
        print('Created "{}", cost ${}'.format(name, cost))

    def do_del(self, name):
        print('Deleted {}'.format(name))

    def do_exit(self, args):
        raise SystemExit()

if __name__ == "__main__":

    app = MyCmd()
    app.cmdloop('Enter a command to do something. eg `create name price`.')

And here is the output of running the above code (if the above code was in a file named app.py):

$ python app.py
Enter a command to do something. eg `create name price`.
> create item1 10
Created "item1", cost $10
> del item1
Deleted item1
> exit
$