问:
Return list with n'th values of a list of lists - Python
This is my first question here. I just started coding in Python, and trying to finish an assignment for my study in Python (it is actually supposed to be made in STATA but I want to learn Python).

So I want to do the following (note that the final_list consists of 15000 rows, this is just a small example):

```<code>final_list = [[2.0, 1.0, 5.0, 11.0, 50612.0, 0.38875884563387036, 0.5924978852272034, 8.400468826293945, 516.0, 0.0, 0.0, 0.0, 2003.0], [2.0, 1.0, 5.0, 11.0, 50612.0, 0.38875884563387036, 0.5924978852272034, 8.400468826293945, 517.0, 0.0, 0.0, 0.0, 2003.0], [2.0, 1.0, 5.0, 11.0, 50612.0, 0.38875884563387036, 0.5924978852272034, 8.400468826293945, 518.0, 0.0, 0.0, 0.0, 2003.0]
</code>```

to

```<code>treshold = [11.0, 11.0, 11.0]
</code>```

Now what I've tried is this:

```<code>treshold = []
for sublist in final_list:
    treshold_lst = sublist[3]
    treshold.append(treshold_lst)
print(treshold)
</code>```

I receive the following error:

```<code>IndexError: list index out of range
</code>```

Does anyone see what I'm doing wrong?

答:
Try list comprehension:

```<code>final_list = [[1,2,3,4],[1,2,3,5],[1,3,4,6]]
treshold = [sub[-1] for sub in final_list]
</code>```

Body:
This is my first question here. I just started coding in Python, and trying to finish an assignment for my study in Python (it is actually supposed to be made in STATA but I want to learn Python).

So I want to do the following (note that the final_list consists of 15000 rows, this is just a small example):

final_list = [[2.0, 1.0, 5.0, 11.0, 50612.0, 0.38875884563387036, 0.5924978852272034, 8.400468826293945, 516.0, 0.0, 0.0, 0.0, 2003.0], [2.0, 1.0, 5.0, 11.0, 50612.0, 0.38875884563387036, 0.5924978852272034, 8.400468826293945, 517.0, 0.0, 0.0, 0.0, 2003.0], [2.0, 1.0, 5.0, 11.0, 50612.0, 0.38875884563387036, 0.5924978852272034, 8.400468826293945, 518.0, 0.0, 0.0, 0.0, 2003.0]

to

treshold = [11.0, 11.0, 11.0]

Now what I've tried is this:

treshold = []
for sublist in final_list:
    treshold_lst = sublist[3]
    treshold.append(treshold_lst)
print(treshold)

I receive the following error:

IndexError: list index out of range

Does anyone see what I'm doing wrong?

Body:
Try list comprehension:

final_list = [[1,2,3,4],[1,2,3,5],[1,3,4,6]]
treshold = [sub[-1] for sub in final_list]


来源: stackexchange

问:
Restrict input type="number" to its min or max if it is out of range
I have the below code

```<code><form:input type="number" min="1" max="4" size="5" value="1" path="n" name='n' placeholder="<5" style="height:25px;width:60px"></form:input>
</code>```

if a user enters a value in the textbox out of range then it should reset to its nearest min or max value, for example if user enters in textbox as less than 1 then it should get reset to 1, if he enters more than 4 then it should get reset to 4.

Please advice if we have any other tag instead of using input tag to restrict

There is a solution already which is not working for me

答: Actually input type=number only handles and not allows user to submit the form if the entered number is not in range</p>

ContentLicense: CC BY-SA 3.0

Body:
I have the below code

<form:input type="number" min="1" max="4" size="5" value="1" path="n" name='n' placeholder="<5" style="height:25px;width:60px"></form:input>

if a user enters a value in the textbox out of range then it should reset to its nearest min or max value, for example if user enters in textbox as less than 1 then it should get reset to 1, if he enters more than 4 then it should get reset to 4.

Please advice if we have any other tag instead of using input tag to restrict

There is a solution already which is not working for me


问:
Sorting XML file with XSLT or Python based on attribute of child element
I have a number of XML-files with a structure like this:

```<code><titles>
  <title mode="example" name="name_example">
    <titleselect>
      <attribute_a>attrib_a</attribute_a>
      <attribute_b>attrib_b</attribute_b>
      <attribute_c>attrib_c</attribute_c>
      <sort_attribute>New York</sort_attribute>
    </titleselect>
  </title>
  <title mode="another_example" name="another_name">
    <titleselect>
      <attribute_a>attrib_a</attribute_a>
      <attribute_b>attrib_b</attribute_b>
      <attribute_c>attrib_c</attribute_c>
      <sort_attribute>Boston</sort_attribute>
    </titleselect>
  </title>
  <title mode="final_example" name="final_name">
    <titleselect>
      <attribute_a>attrib_a</attribute_a>
      <attribute_b>attrib_b</attribute_b>
      <attribute_c>attrib_c</attribute_c>
      <sort_attribute>Chicago</sort_attribute>
    </titleselect>
  </title>
</titles>
</code>```

I am trying to sort the "titles" alphabetically by the "sort_attribute". My desired output is like this:

```<code><titles>
      <title mode="another_example" name="another_name">
        <titleselect>
          <attribute_a>attrib_a</attribute_a>
          <attribute_b>attrib_b</attribute_b>
          <attribute_c>attrib_c</attribute_c>
          <sort_attribute>Boston</sort_attribute>
        </titleselect>
      </title>
      <title mode="final_example" name="final_name">
        <titleselect>
          <attribute_a>attrib_a</attribute_a>
          <attribute_b>attrib_b</attribute_b>
          <attribute_c>attrib_c</attribute_c>
          <sort_attribute>Chicago</sort_attribute>
        </titleselect>
      </title>
      <title mode="example" name="name_example">
        <titleselect>
          <attribute_a>attrib_a</attribute_a>
          <attribute_b>attrib_b</attribute_b>
          <attribute_c>attrib_c</attribute_c>
          <sort_attribute>New York</sort_attribute>
        </titleselect>
      </title>
    </titles>
</code>```

Is there anyway to achieve this, preferably using XSLT or Python?
I am completely new to the world of XSLT, but I have tried applying a number of solutions from other relevant questions e.g. XSLT sort parent element based on child element attribute
to no avail.

答:
As an XSLT alternative, as per Tomalek's comment, this is fairly straightforward using a template capturing the parent titles and then sorting by the required sort_attribute (actually, an element), and copying the inner title content:

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

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

  <xsl:template match="titles">
    <xsl:copy>
      <xsl:apply-templates select="title">
        <xsl:sort select="titleselect/sort_attribute" data-type="text" order="ascending"/>
      </xsl:apply-templates>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>
</code>```

Body:
I have a number of XML-files with a structure like this:

<titles>
  <title mode="example" name="name_example">
    <titleselect>
      <attribute_a>attrib_a</attribute_a>
      <attribute_b>attrib_b</attribute_b>
      <attribute_c>attrib_c</attribute_c>
      <sort_attribute>New York</sort_attribute>
    </titleselect>
  </title>
  <title mode="another_example" name="another_name">
    <titleselect>
      <attribute_a>attrib_a</attribute_a>
      <attribute_b>attrib_b</attribute_b>
      <attribute_c>attrib_c</attribute_c>
      <sort_attribute>Boston</sort_attribute>
    </titleselect>
  </title>
  <title mode="final_example" name="final_name">
    <titleselect>
      <attribute_a>attrib_a</attribute_a>
      <attribute_b>attrib_b</attribute_b>
      <attribute_c>attrib_c</attribute_c>
      <sort_attribute>Chicago</sort_attribute>
    </titleselect>
  </title>
</titles>

I am trying to sort the "titles" alphabetically by the "sort_attribute". My desired output is like this:

<titles>
      <title mode="another_example" name="another_name">
        <titleselect>
          <attribute_a>attrib_a</attribute_a>
          <attribute_b>attrib_b</attribute_b>
          <attribute_c>attrib_c</attribute_c>
          <sort_attribute>Boston</sort_attribute>
        </titleselect>
      </title>
      <title mode="final_example" name="final_name">
        <titleselect>
          <attribute_a>attrib_a</attribute_a>
          <attribute_b>attrib_b</attribute_b>
          <attribute_c>attrib_c</attribute_c>
          <sort_attribute>Chicago</sort_attribute>
        </titleselect>
      </title>
      <title mode="example" name="name_example">
        <titleselect>
          <attribute_a>attrib_a</attribute_a>
          <attribute_b>attrib_b</attribute_b>
          <attribute_c>attrib_c</attribute_c>
          <sort_attribute>New York</sort_attribute>
        </titleselect>
      </title>
    </titles>

Is there anyway to achieve this, preferably using XSLT or Python?
I am completely new to the world of XSLT, but I have tried applying a number of solutions from other relevant questions e.g. XSLT sort parent element based on child element attribute
to no avail.

Body:
As an XSLT alternative, as per Tomalek's comment, this is fairly straightforward using a template capturing the parent titles and then sorting by the required sort_attribute (actually, an element), and copying the inner title content:

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

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

  <xsl:template match="titles">
    <xsl:copy>
      <xsl:apply-templates select="title">
        <xsl:sort select="titleselect/sort_attribute" data-type="text" order="ascending"/>
      </xsl:apply-templates>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>


问:
SQL query does not executes because of escaped characters
let's say i have sql query like this:

```<code>SELECT column_name FROM table WHERE columnid <= 5
</code>```

defined in orm.xml like this:

```<code><named-query>
  <query>
    sql query
  </query>
</named-query>
</code>```

Environment said that the xml is not well formed, because of < character. So then i googled for explanation and i found, that i have to escape characters as in the following example

```<code>< = &lt , > = &gt
</code>```

But when i excaped these characters, the query doesn't execute. It's not valid, because of the escaping. Do you please have any idea how to fix this or any workaround?

答:
Don't know if this is still open, but - at least - it is unanswered:

You should not think of XML as a string with fancy extra characters. Putting content into the XML has some rules and reading values from within XML has some rules too. You can easily create something which looks like XML on string level, but - if your xml ist not valid - you'll get into troubles.

The most important exceptions are - obviously! - <, > and &, which would disturb the markup, if not escaped.

```<code>DECLARE @xml XML=N'<root>SELECT column_name FROM table WHERE columnid <= 5</root>';
SELECT @xml.value(N'(/root/text())[1]',N'nvarchar(max)');
</code>```

You'll find, that the escaped character is re-converted implicitly. But you must read the XML with an appropriate tool!. If you read the XML with string methods (like substring), you'll have to ensure the re-escaping yourself.

There is a - not recommended - workaround: You can use a CDATA-section like here:

```<code>DECLARE @xml XML=N'<root><![CDATA[SELECT column_name FROM table WHERE columnid <= 5]]></root>';
SELECT @xml.value(N'(/root/text())[1]',N'nvarchar(max)');
</code>```

This allows you to place text into the XML which will be take as-is. But this is outdated and not supported directly in SQL-Server (Well, there is FOR XML EXPLICIT, which is outdated by itself). SQL-Server will actually store the above without CDATA as escaped string automatically. Semantically  it's the same...

Body:
let's say i have sql query like this:

SELECT column_name FROM table WHERE columnid <= 5

defined in orm.xml like this:

<named-query>
  <query>
    sql query
  </query>
</named-query>

Environment said that the xml is not well formed, because of < character. So then i googled for explanation and i found, that i have to escape characters as in the following example

< = &lt , > = &gt

But when i excaped these characters, the query doesn't execute. It's not valid, because of the escaping. Do you please have any idea how to fix this or any workaround?

Body:
Don't know if this is still open, but - at least - it is unanswered:

You should not think of XML as a string with fancy extra characters. Putting content into the XML has some rules and reading values from within XML has some rules too. You can easily create something which looks like XML on string level, but - if your xml ist not valid - you'll get into troubles.

The most important exceptions are - obviously! - <, > and &, which would disturb the markup, if not escaped.

DECLARE @xml XML=N'<root>SELECT column_name FROM table WHERE columnid &lt;= 5</root>';
SELECT @xml.value(N'(/root/text())[1]',N'nvarchar(max)');

You'll find, that the escaped character is re-converted implicitly. But you must read the XML with an appropriate tool!. If you read the XML with string methods (like substring), you'll have to ensure the re-escaping yourself.

There is a - not recommended - workaround: You can use a CDATA-section like here:

DECLARE @xml XML=N'<root><![CDATA[SELECT column_name FROM table WHERE columnid <= 5]]></root>';
SELECT @xml.value(N'(/root/text())[1]',N'nvarchar(max)');

This allows you to place text into the XML which will be take as-is. But this is outdated and not supported directly in SQL-Server (Well, there is FOR XML EXPLICIT, which is outdated by itself). SQL-Server will actually store the above without CDATA as escaped string automatically. Semantically  it's the same...


问:
How can one make two instances of this Singleton Class?
This code should be enough for restricting only one instance of singleton class. How can we make two instances of this object?</p>

```<code>class Singleton
{
private:
    Singleton()
    {}
    ~Singleton()
    {}
    static Singleton * ptr;
public:
    static Singleton * CreateObject()
    {
        if (!ptr)
            ptr = new Singleton;
        return ptr;
    }
    static void freeObject()
    {
        if (ptr)
        {
            delete ptr;
            ptr = 0;
        }
    }
};
Singleton * Singleton::ptr = 0;
</code>```

答:
The singleton pattern is about not having two instances of a class.

The easiest way to get rid of that constraint... is to remove the singleton pattern:

```<code>class Singleton
{
};

Singleton one = new Singleton();
Singleton two = new Singleton();
</code>```

As a side-effect, you just made your code cleaner, too, as Singleton is considered an anti-pattern by many.

Body:
This code should be enough for restricting only one instance of singleton class. How can we make two instances of this object?

class Singleton
{
private:
    Singleton()
    {}
    ~Singleton()
    {}
    static Singleton * ptr;
public:
    static Singleton * CreateObject()
    {
        if (!ptr)
            ptr = new Singleton;
        return ptr;
    }
    static void freeObject()
    {
        if (ptr)
        {
            delete ptr;
            ptr = 0;
        }
    }
};
Singleton * Singleton::ptr = 0;

Body:
The singleton pattern is about not having two instances of a class.

The easiest way to get rid of that constraint... is to remove the singleton pattern:

class Singleton
{
};

Singleton one = new Singleton();
Singleton two = new Singleton();

As a side-effect, you just made your code cleaner, too, as Singleton is considered an anti-pattern by many.


问:
From Logstash log4j input to beats
Please, I was using log4j input of logstash, it was allowing me to skip log parsing (grok ...).

```<code>`input {
   log4j {
      mode => "server"
      host => "0.0.0.0"
      port => 8090
     }
   }`
</code>```

Elastic now, in version 5.4.1, is tagging this input as deprecated, and the alternative now is filebeats, which listen on log files directly.

The problem is that you need to parse your log files again via grok filter...is there any possible way to use beats for log4j without parsing log lines again, exactly like the old log4j socketAppender ?

Thank you

答: You can use logstash-logback-encoder, it provides a LogstashSocketAppender, which implement SocketAppender, and using RSysLog to send log in json format to elasticsearch.

Title: From Logstash log4j input to beats

Body:
Please, I was using log4j input of logstash, it was allowing me to skip log parsing (grok ...).

`input {
   log4j {
      mode => "server"
      host => "0.0.0.0"
      port => 8090
     }
   }`

Elastic now, in version 5.4.1, is tagging this input as deprecated, and the alternative now is filebeats, which listen on log files directly.

The problem is that you need to parse your log files again via grok filter...is there any possible way to use beats for log4j without parsing log lines again, exactly like the old log4j socketAppender ?

Thank you


问:
Access state inside a function to dynamically set drawer width
I want to dynamically change the drawer width when the device orientation changes. This is my code

```<code>updateWidth = (width) => {
    this.setState({drawerWidth: width/2 });
  }
</code>```

I call updateWidth when componentDidMount and onLayout functions are called.

In the drawerNavigator declaration, I set drawerWidth: this.state.drawerWidth . Here I get an error telling me that drawerWidth: this.state.drawerWidth  is undefined. How can I solve this issue?

Edit:
This is the component code overview

```<code>const { width } = Dimensions.get('window');

const AppDrawer = DrawerNavigator(
{
  Category: {
    path: '/bla',
    screen: bla,
  },
},
{
  drawerWidth: this.state.drawerWidth ,
  contentComponent: test,
  initialRouteName: 'tets',
  contentOptions: {
    activeTintColor: '#fd67d3',
  },
}
);

const AppNavigator = StackNavigator({
...
})

class RootContainer extends Component {
 constructor(props) {
  super(props);
  this.state = {
      drawerWidth: 30
  }
}

  onLayout(e) {
    const {width, height} = Dimensions.get('window')
    this.updateWidth(width);
  }

  updateWidth = (width) => {
    this.setState({drawerWidth: width/2 });
  }

  componentDidMount() {
    this.updateWidth(width);
}
</code>```

答:
You need to initialize your state in the constructor and use a stateful component.</p>

```<code>class AppDrawer extends Component {
  constructor(props) {
      super(props);
      this.state = {
          drawerWidth: 0 //or any other number
      }
  }
</code>```

Body:
I want to dynamically change the drawer width when the device orientation changes. This is my code

updateWidth = (width) => {
    this.setState({drawerWidth: width/2 });
  }

I call updateWidth when componentDidMount and onLayout functions are called.

In the drawerNavigator declaration, I set drawerWidth: this.state.drawerWidth . Here I get an error telling me that drawerWidth: this.state.drawerWidth  is undefined. How can I solve this issue?

Edit:
This is the component code overview

const { width } = Dimensions.get('window');

const AppDrawer = DrawerNavigator(
{
  Category: {
    path: '/bla',
    screen: bla,
  },
},
{
  drawerWidth: this.state.drawerWidth ,
  contentComponent: test,
  initialRouteName: 'tets',
  contentOptions: {
    activeTintColor: '#fd67d3',
  },
}
);

const AppNavigator = StackNavigator({
...
})

class RootContainer extends Component {
 constructor(props) {
  super(props);
  this.state = {
      drawerWidth: 30
  }
}

  onLayout(e) {
    const {width, height} = Dimensions.get('window')
    this.updateWidth(width);
  }

  updateWidth = (width) => {
    this.setState({drawerWidth: width/2 });
  }

  componentDidMount() {
    this.updateWidth(width);
}

Body:
You need to initialize your state in the constructor and use a stateful component.

class AppDrawer extends Component {
  constructor(props) {
      super(props);
      this.state = {
          drawerWidth: 0 //or any other number
      }
  }


问:
How to mock a function call while initializing a variable in @Tested testObject in junit
I have a class A which has a private integer member b. Here is the structure of the class:

```<code>public class A {

    private int b= Integer.parseInt(C.getValue(anyString));

    public int getB() {
       return b;
    }

    public void setB(int b) {
       this.b= b;
    }

}
</code>```

I am testing some method of this class using jmockit with junit4 `

```<code>public class ATest {

    @Tested
    A a;

    @BeforeClass
    public void setUp() {
       //mock C.getValue
    }

    @Test public void test1() {
       //some test code
    }
}
</code>```

but I am unable to mock the call (C.getValue(anyString)) thus the test fails while building the project. I have tried using @Before and @BeforeClass but none of those executed even once. Please suggest a way out.
Considering I can't change the main class A.

答:
The root cause is that you code violates the Single Responsibility/Separation of Concerns principle. It is also a case of the work in constructor code smell.

Your class A pretty much looks like a Data Transfer Object (DTO) Its only responsibility is to carry data. Fetching the data from the database should be done by some framework outside the class and the data should be passed in from the outside.

Body:
I have a class A which has a private integer member b. Here is the structure of the class:

public class A {

    private int b= Integer.parseInt(C.getValue(anyString));

    public int getB() {
       return b;
    }

    public void setB(int b) {
       this.b= b;
    }

}

I am testing some method of this class using jmockit with junit4 `

public class ATest {

    @Tested
    A a;

    @BeforeClass
    public void setUp() {
       //mock C.getValue
    }

    @Test public void test1() {
       //some test code
    }
}

but I am unable to mock the call (C.getValue(anyString)) thus the test fails while building the project. I have tried using @Before and @BeforeClass but none of those executed even once. Please suggest a way out.
Considering I can't change the main class A.


问:
how to put background image path from remote web site?
I need grab images from Imgur to My web page background image

```<code> <div style="background-image:url(); width:100%; height:100%;" class="zoom" >
</code>```

My image path is https://imgur.com/a/NbUpX

then how can I put this image to my background image url?

答:
Open your image path, after that right click on the image and click "Copy image address".
And then paste address on your code.</p>

```<code><div style="background-image:url(https://i.imgur.com/QdMWFHZ.jpg); width:100%; height:100%;" class="zoom" >
</code>```

Body:
I need grab images from Imgur to My web page background image

My image path is https://imgur.com/a/NbUpX

then how can I put this image to my background image url?

Body:
Open your image path, after that right click on the image and click "Copy image address".
And then paste address on your code.

<div style="background-image:url(https://i.imgur.com/QdMWFHZ.jpg); width:100%; height:100%;" class="zoom" >


问:
Recover default style when modified with JavaScript
In a JS function, I've set the background color of a text field like this:

```<code>document.getElementsByName(formId)[0].title.style.backgroundColor = "#7FB75E";
</code>```

In another function, I want to reset the background color to the default value defined in my style sheet. How can I do this?

答:
Just set the value on the "style" object to the empty string.

```<code>document.getElementsByName(formId)[0].title.style.backgroundColor = "";
</code>```

edit — note that if your element had an inline style, you'd have to explicitly save that somewhere or else you won't be able to get it back.

Body:
In a JS function, I've set the background color of a text field like this:

document.getElementsByName(formId)[0].title.style.backgroundColor = "#7FB75E";

In another function, I want to reset the background color to the default value defined in my style sheet. How can I do this?

Body:
Just set the value on the "style" object to the empty string.

document.getElementsByName(formId)[0].title.style.backgroundColor = "";

edit — note that if your element had an inline style, you'd have to explicitly save that somewhere or else you won't be able to get it back.


问:
sql query with two joins and a simple logic
Please find the fiddle
http://sqlfiddle.com/#!9/4a4aff/7

Friends_list Table

```<code> | id | user_id | Friend_id | status
 |  1 |   1     |    24     |   P
 |  2 |   18    |    26     |   P
</code>```

User Table

```<code>| ID | email   | password  |  ..N
 |  1 |   xx    |    xx     |   xx
 |  2 |   xx    |    xx     |   xx
</code>```

from those both table i want to get all the users listed without the users whose status was P or B in friends list table it seems to be simple using joins but in wordpress this code is not working and the query is as below.

```<code>select DISTINCT u.ID, u.user_nicename from wp_users u
LEFT JOIN friends_list f ON f.friend_id=u.ID
WHERE f.status  NOT IN ('P', 'B')
</code>```

答:
From what I understand you want ALL user except the those who has P or B as status. To get those users that don't have a value in the friends_list table at all you can add a null check to your query.

```<code>select DISTINCT u.ID, u.user_nicename from wp_users u
LEFT JOIN friends_list f ON f.friend_id=u.ID
WHERE f.status NOT IN ('P', 'B') OR f.status IS NULL
</code>```

I'm also unsure if you're joining on the right column? Should it be user_id instead of friend_id?

Body:
Please find the fiddle
http://sqlfiddle.com/#!9/4a4aff/7

Friends_list Table

 | id | user_id | Friend_id | status
 |  1 |   1     |    24     |   P
 |  2 |   18    |    26     |   P

User Table

| ID | email   | password  |  ..N
 |  1 |   xx    |    xx     |   xx
 |  2 |   xx    |    xx     |   xx

from those both table i want to get all the users listed without the users whose status was P or B in friends list table it seems to be simple using joins but in wordpress this code is not working and the query is as below.

select DISTINCT u.ID, u.user_nicename from wp_users u
LEFT JOIN friends_list f ON f.friend_id=u.ID
WHERE f.status  NOT IN ('P', 'B')

Body:
From what I understand you want ALL user except the those who has P or B as status. To get those users that don't have a value in the friends_list table at all you can add a null check to your query.

select DISTINCT u.ID, u.user_nicename from wp_users u
LEFT JOIN friends_list f ON f.friend_id=u.ID
WHERE f.status NOT IN ('P', 'B') OR f.status IS NULL

I'm also unsure if you're joining on the right column? Should it be user_id instead of friend_id?


问:
Replace newlines in ByteString
I'd like a function that takes a ByteString and replaces newlines \n and \n\r with commas, but can't think of a nice way to do it.

```<code>import qualified Data.ByteString as BS
import Data.Char (ord)
import Data.Word (Word8)

endlWord8 = fromIntegral $ ord '\n' :: Word8

replace :: BS.ByteString -> BS.ByteString
</code>```

I thought of using BS.map but can't see how since I can't pattern match on Word8's. Another option would be BS.split and then join with Word8 commas, but that sounds slow and inelegant. Any ideas?

答:
Use Data.ByteString.Char8 to get rid of the nasty Word8, Char conversions you otherwise have to do. According to Data.ByteString.Char8 first sentence performance shouldn't be altered.

Additionally use B.span instead of B.split as you want to replace also \n\r combinations and not only \n.

My own (probably clumsy) attempt to do so:

```<code>module Test where

import Data.Monoid ((<>))
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Builder as Build
import qualified Data.ByteString.Lazy as LB

eatNewline :: ByteString -> (Maybe Char, ByteString)
eatNewline string
  | B.null string = (Nothing, string)
  | B.head string == '\n' && B.null (B.tail string) = (Just ',', B.empty)
  | B.head string == '\n' && B.head (B.tail string) /= '\r' = (Just ',', B.drop 1 string)
  | B.head string == '\n' && B.head (B.tail string) == '\r' = (Just ',', B.drop 2 string)
  | otherwise = (Nothing, string)

replaceNewlines :: ByteString -> ByteString
replaceNewlines = LB.toStrict . Build.toLazyByteString . go mempty
  where
    go :: Build.Builder -> ByteString -> Build.Builder
    go builder string = let (chunk, rest) = B.span (/= '\n') string
                            (c, rest1)    = eatNewline rest
                            maybeComma    = maybe mempty Build.char8 c
                        in if B.null rest1 then
                             builder <> Build.byteString chunk <> maybeComma
                           else
                             go (builder <> Build.byteString chunk <> maybeComma) rest1
</code>```

Hopefully the mappend for Data.ByteString.Builder isn't linear in the number of times mappend was already used for one of its operands, otherwise, there would be a quadratic alogrithm here.

Title: Replace newlines in ByteString

Body:
I'd like a function that takes a ByteString and replaces newlines \n and \n\r with commas, but can't think of a nice way to do it.

import qualified Data.ByteString as BS
import Data.Char (ord)
import Data.Word (Word8)

endlWord8 = fromIntegral $ ord '\n' :: Word8

replace :: BS.ByteString -> BS.ByteString

I thought of using BS.map but can't see how since I can't pattern match on Word8's. Another option would be BS.split and then join with Word8 commas, but that sounds slow and inelegant. Any ideas?

Body:
Use Data.ByteString.Char8 to get rid of the nasty Word8, Char conversions you otherwise have to do. According to Data.ByteString.Char8 first sentence performance shouldn't be altered.

Additionally use B.span instead of B.split as you want to replace also \n\r combinations and not only \n.

My own (probably clumsy) attempt to do so:

module Test where

import Data.Monoid ((<>))
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Builder as Build
import qualified Data.ByteString.Lazy as LB

eatNewline :: ByteString -> (Maybe Char, ByteString)
eatNewline string
  | B.null string = (Nothing, string)
  | B.head string == '\n' && B.null (B.tail string) = (Just ',', B.empty)
  | B.head string == '\n' && B.head (B.tail string) /= '\r' = (Just ',', B.drop 1 string)
  | B.head string == '\n' && B.head (B.tail string) == '\r' = (Just ',', B.drop 2 string)
  | otherwise = (Nothing, string)

replaceNewlines :: ByteString -> ByteString
replaceNewlines = LB.toStrict . Build.toLazyByteString . go mempty
  where
    go :: Build.Builder -> ByteString -> Build.Builder
    go builder string = let (chunk, rest) = B.span (/= '\n') string
                            (c, rest1)    = eatNewline rest
                            maybeComma    = maybe mempty Build.char8 c
                        in if B.null rest1 then
                             builder <> Build.byteString chunk <> maybeComma
                           else
                             go (builder <> Build.byteString chunk <> maybeComma) rest1

Hopefully the mappend for Data.ByteString.Builder isn't linear in the number of times mappend was already used for one of its operands, otherwise, there would be a quadratic alogrithm here.


问:
curl command with certificates to php SoapClient (BankID)
Based on https://www.bankid.com/assets/bankid/rp/bankid-relying-party-guidelines-v2.13.pdf

I have working curl command:

```<code>curl https://appapi.test.bankid.com/rp/v4?wsdl -E --cacert /path/to/BankID_SSL_Root_Certification_Authority_TEST.pem --cert /path/to/ServerCertificate.cer --key /path/to/PrivateKey.key
</code>```

ServerCertificate.cer and PrivateKey.key were extracted from PFX certificate (https://www.bankid.com/assets/bankid/rp/FPTestcert2_20150818_102329.pfx) with openssl command.

But I can't make it work with PHP SoapClient:

```<code>SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://appapi.test.bankid.com/rp/v4?wsdl' : failed to load external entity "https://appapi.test.bankid.com/rp/v4?wsdl"
</code>```

I will appreciate any help here.

答:
Just for future people finding themselves with the same BankID problem, Dmitry gave a very good tutorial on how to get the correct certificate, but the code that worked for me required a few more parameters:</p>

```<code>try {
    $client = new SoapClient('https://appapi2.test.bankid.com/rp/v4?wsdl',
        ["local_cert" => "certname.pem",
         "stream_context" => [
             "ssl" => [
                 "verify_peer" => false,
                 "verify_peer_name" => false,
                 "allow_self_signed" => true
             ]
         ]
     ]);
} catch (Exception $e) {
    return json_encode( array( "result" => false, "reason" => $e->getMessage() ) );
}
</code>```

Body:
Based on https://www.bankid.com/assets/bankid/rp/bankid-relying-party-guidelines-v2.13.pdf

I have working curl command:

curl https://appapi.test.bankid.com/rp/v4?wsdl -E --cacert /path/to/BankID_SSL_Root_Certification_Authority_TEST.pem --cert /path/to/ServerCertificate.cer --key /path/to/PrivateKey.key

ServerCertificate.cer and PrivateKey.key were extracted from PFX certificate (https://www.bankid.com/assets/bankid/rp/FPTestcert2_20150818_102329.pfx) with openssl command.

But I can't make it work with PHP SoapClient:

SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://appapi.test.bankid.com/rp/v4?wsdl' : failed to load external entity "https://appapi.test.bankid.com/rp/v4?wsdl"

I will appreciate any help here.

Body:
Just for future people finding themselves with the same BankID problem, Dmitry gave a very good tutorial on how to get the correct certificate, but the code that worked for me required a few more parameters:

try {
    $client = new SoapClient('https://appapi2.test.bankid.com/rp/v4?wsdl',
        ["local_cert" => "certname.pem",
         "stream_context" => [
             "ssl" => [
                 "verify_peer" => false,
                 "verify_peer_name" => false,
                 "allow_self_signed" => true
             ]
         ]
     ]);
} catch (Exception $e) {
    return json_encode( array( "result" => false, "reason" => $e->getMessage() ) );
}


问:
Pandas: mapping with dict using more than 1 column
I got basic DataFrame:

```<code>df = pd.DataFrame([[1, 2],[3, 4],[5, 6],[7, 8]],
                  index=['A','B','C','D'], columns=['X','Y'])
</code>```

I would like the map function to work on columns X & Y and obtain this:

```<code>   X  Y  Chk
A  1  2  found A
B  3  4  found B
C  5  6  found C
D  7  8  found D
</code>```

For this, I created a dict for 2 keys:

```<code>mapped = {1:{2:'found A'}, 3:{4:'found B'},5:{6:'found C'}, 7:{8:'found D'}}
</code>```

And used the applymap method on the DataFrame:

```<code>df['Chk'] = df[['X','Y']].applymap(mapped)
</code>```

Unfortunately, I got an error message:

```<code>TypeError: ("'dict' object is not callable", 'occurred at index X')
</code>```

Is the code wrong, or is it the dict-based mapping that simply does not support more than 1 column ?

答:
Create DataFrame and then Series with MultiIndex by stack first and then join:

```<code>s = pd.DataFrame(mapped).stack().rename('Chk')
print (s)
2  1    found A
4  3    found B
6  5    found C
8  7    found D
Name: Chk, dtype: object

df = df.join(s, on=['Y','X'])
print (df)
   X  Y      Chk
A  1  2  found A
B  3  4  found B
C  5  6  found C
D  7  8  found D
</code>```

If possible create DataFrame for mapping and then use merge:

```<code>mapped = {'X': [1, 3, 5, 7],
         'Chk': ['found A', 'found B', 'found C', 'found D'],
         'Y': [2, 4, 6, 8]}

df1 = pd.DataFrame(mapped)
print (df1)
       Chk  X  Y
0  found A  1  2
1  found B  3  4
2  found C  5  6
3  found D  7  8

df = pd.merge(df, df1, how='left', on=['X','Y'])
print (df)
   X  Y      Chk
0  1  2  found A
1  3  4  found B
2  5  6  found C
3  7  8  found D
</code>```

Body:
I got basic DataFrame:

df = pd.DataFrame([[1, 2],[3, 4],[5, 6],[7, 8]],
                  index=['A','B','C','D'], columns=['X','Y'])

I would like the map function to work on columns X & Y and obtain this:

   X  Y  Chk
A  1  2  found A
B  3  4  found B
C  5  6  found C
D  7  8  found D

For this, I created a dict for 2 keys:

mapped = {1:{2:'found A'}, 3:{4:'found B'},5:{6:'found C'}, 7:{8:'found D'}}

And used the applymap method on the DataFrame:

df['Chk'] = df[['X','Y']].applymap(mapped)

Unfortunately, I got an error message:

TypeError: ("'dict' object is not callable", 'occurred at index X')

Is the code wrong, or is it the dict-based mapping that simply does not support more than 1 column ?

Body:
Create DataFrame and then Series with MultiIndex by stack first and then join:

s = pd.DataFrame(mapped).stack().rename('Chk')
print (s)
2  1    found A
4  3    found B
6  5    found C
8  7    found D
Name: Chk, dtype: object

df = df.join(s, on=['Y','X'])
print (df)
   X  Y      Chk
A  1  2  found A
B  3  4  found B
C  5  6  found C
D  7  8  found D

If possible create DataFrame for mapping and then use merge:

mapped = {'X': [1, 3, 5, 7],
         'Chk': ['found A', 'found B', 'found C', 'found D'],
         'Y': [2, 4, 6, 8]}

df1 = pd.DataFrame(mapped)
print (df1)
       Chk  X  Y
0  found A  1  2
1  found B  3  4
2  found C  5  6
3  found D  7  8

df = pd.merge(df, df1, how='left', on=['X','Y'])
print (df)
   X  Y      Chk
0  1  2  found A
1  3  4  found B
2  5  6  found C
3  7  8  found D


问:
?Why is my CSS not applying?
For some reason, my CSS is not applying to my HTML.

HTML:

```<code><textarea class="overlay-display-hide preview-caption" placeholder="Add Your Caption here..."></textarea>
</code>```

CSS:

```<code>.overlay-display-hide {
    display: hide !important;
}
.preview-caption {
    position: absolute;
    width: 360px;
    height: 260px;
    background-color:transparent;
    border-style: none;
    color: white;
    font-size: 14px;
    padding: 20px;
    resize: none;
    overflow: hidden;
}
</code>```

And for some reason, the "overlay-display-hide" class does not show up in the element when inspecting. Do you have any ideas? I bet I just oversaw something.

答:
Does not exist display: hide. Read all properties from this site

For example, if you want to hide element use display: none or visibility: hidden

```<code>.overlay-display-hide {
    display: none !important;
}
</code>```

Title: ?Why is my CSS not applying?

Body:
For some reason, my CSS is not applying to my HTML.

HTML:

<textarea class="overlay-display-hide preview-caption" placeholder="Add Your Caption here..."></textarea>

CSS:

.overlay-display-hide {
    display: hide !important;
}
.preview-caption {
    position: absolute;
    width: 360px;
    height: 260px;
    background-color:transparent;
    border-style: none;
    color: white;
    font-size: 14px;
    padding: 20px;
    resize: none;
    overflow: hidden;
}

And for some reason, the "overlay-display-hide" class does not show up in the element when inspecting. Do you have any ideas? I bet I just oversaw something.

Body:
Does not exist display: hide. Read all properties from this site

For example, if you want to hide element use display: none or visibility: hidden

.overlay-display-hide {
    display: none !important;
}


问:
Rails - Using true and false
I have the following in my controller:

```<code>if params[:archive] == 'true'
  @archived_new_status = true
else
  @archived_new_status = false
end
</code>```

Then later in create.je.erb do:

```<code><% if !@archived_new_status.nil? %>
   xxx.myfuncthatNeedsTrueOrFalse(<%=@archived_new_status%>);
<% end %>
</code>```

That only works when @archived_new_status is true, when it's false that seems to not be getting set as false. When I do a Rails.logger.info on @archived_new_status for false it outputs nothing, if I inspect it, I get false.

Any thoughts?

答:
You could do:

```<code>if params[:archive] && !params[:archive].blank?
    @archived_new_status = params[:archive]
end
</code>```

But you may want to put validation in the model or raise application exceptions. See Rails form validation

ContentLicense: CC BY-SA 2.5

Title: Rails - Using true and false

Body:
I have the following in my controller:

if params[:archive] == 'true'
  @archived_new_status = true
else
  @archived_new_status = false
end

Then later in create.je.erb do:

<% if !@archived_new_status.nil? %>
   xxx.myfuncthatNeedsTrueOrFalse(<%=@archived_new_status%>);
<% end %>

That only works when @archived_new_status is true, when it's false that seems to not be getting set as false. When I do a Rails.logger.info on @archived_new_status for false it outputs nothing, if I inspect it, I get false.

Any thoughts?

Body:
You could do:

if params[:archive] && !params[:archive].blank?
    @archived_new_status = params[:archive]
end

But you may want to put validation in the model or raise application exceptions. See Rails form validation


问:
swift 3 removing bulk of text from textFiled
I'm working for mobile application will send pdf for selected contact, so the user will found add contact button to open table view that have all contact list. after that the user will click on done button.there is another view that have textFiled to display the contacts that user select. I need if the user start to remove name from textFiled by backspace,

to be removed the all name and remove also the id from array that will send the id's to server.
my code is

```<code>let idArray = ["1","2","3","4"]
let valueArray = ["Ahmad","ali","jean","sara"]
let StringVar = ""

//*Here I send the array to string to append "," to be showed in textFiled*
for item in valueArray {
            print("Found \(item)")
            StringVar = StringVar + item + ","
        }

textFiled?.text = StringVar
</code>```

any help please ??

答:
I think it may be a string parsing headache for this type of work.
Maybe you might consider using instead:
A horizontal UICollectionView for your person list. This collectionView's cell include a borderles UITextView (or if it readonly then it can be UILabel) and small UIButton with close(x) icon for delete action for every single person.

Designer looks like this:

this view will work in a way that is compatible with your array.

Here are the things you should pay attention to:

1- Bind collectionView with your array as if it was UITableView

```<code>extension YourViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.personList.count
}

public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = personCollectionView.dequeueReusableCell(withReuseIdentifier: "personNameCell", for: indexPath) as! personNameCell
...
}
</code>```

2- Don't forget reload collectionView after deletion

```<code>func personDeleteButtonPressed(sender: UIButton!) {
    //remove item from your list
    ...
    ...
    personCollectionView.reloadData()
}
</code>```

3- Set dimensions of cells dynamically

```<code>func collectionView(_ collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    sizeForItemAt indexPath: IndexPath) -> CGSize {
...
</code>```

Body:
I'm working for mobile application will send pdf for selected contact, so the user will found add contact button to open table view that have all contact list. after that the user will click on done button.there is another view that have textFiled to display the contacts that user select. I need if the user start to remove name from textFiled by backspace,

to be removed the all name and remove also the id from array that will send the id's to server.
my code is

let idArray = ["1","2","3","4"]
let valueArray = ["Ahmad","ali","jean","sara"]
let StringVar = ""

//*Here I send the array to string to append "," to be showed in textFiled*
for item in valueArray {
            print("Found \(item)")
            StringVar = StringVar + item + ","
        }

textFiled?.text = StringVar

any help please ??

Body:
I think it may be a string parsing headache for this type of work.
Maybe you might consider using instead:
A horizontal UICollectionView for your person list. This collectionView's cell include a borderles UITextView (or if it readonly then it can be UILabel) and small UIButton with close(x) icon for delete action for every single person.

Designer looks like this:

this view will work in a way that is compatible with your array.

Here are the things you should pay attention to:

1- Bind collectionView with your array as if it was UITableView

extension YourViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.personList.count
}

public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = personCollectionView.dequeueReusableCell(withReuseIdentifier: "personNameCell", for: indexPath) as! personNameCell
...
}

2- Don't forget reload collectionView after deletion

func personDeleteButtonPressed(sender: UIButton!) {
    //remove item from your list
    ...
    ...
    personCollectionView.reloadData()
}

3- Set dimensions of cells dynamically

func collectionView(_ collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    sizeForItemAt indexPath: IndexPath) -> CGSize {
...


问:
tabs container property change using jquery
I want to change the property of inpected code

```<code><li id="SR_R1_tab" class="t-Tabs-item a-Tabs-selected is-active" aria-controls="SR_R1" role="tab" aria-selected="false">
  <a class="t-Tabs-link" href="#SR_R1" role="presentation" tabindex="-1">
    <span>1<span>
  </a>
</li>

<div id="SR_R1" class="a-Tabs-panel a-Tabs-before" data-label="1" role="tabpanel" aria-labelledby="SR_R1_tab" aria-hidden="true" style="display: block;" >
</code>```

into

```<code><li id="SR_R1_tab" class="t-Tabs-item a-Tabs-before a-Tabs-selected is-active" aria-controls="SR_R1" role="tab" aria-selected="true">
<a class="t-Tabs-link" href="#SR_R1" role="presentation" >
    <span>1<span>
  </a>
</li>

<div id="SR_R1"  class="a-Tabs-panel a-Tabs-before a-Tabs-element-selected" data-label="1" role="tabpanel" aria-labelledby="SR_R1_tab" aria-hidden="false" style="display: block;" >
</code>```

using js function or jquery. I am using oracle apex. I have less knowledge in jquery and js . How can I do this?

答:
you can use the following method to set/change property in js

```<code>document.getElementById('yourElementId').setAttribute("propertyName","propertyValue");
</code>```

for example :

```<code> document.getElementById('SR_R1_tab').setAttribute("class","t-Tabs-item a-Tabs-before a-Tabs-selected is-active");
</code>```

Body:
I want to change the property of inpected code

    1

into

    1

using js function or jquery. I am using oracle apex. I have less knowledge in jquery and js . How can I do this?

Body:
you can use the following method to set/change property in js

document.getElementById('yourElementId').setAttribute("propertyName","propertyValue");

for example :

 document.getElementById('SR_R1_tab').setAttribute("class","t-Tabs-item a-Tabs-before a-Tabs-selected is-active");


问:
play videos from my youtube channel in android
I am making an application where I need to list the playlists of a corresponding YouTube channel. I have a working YouTube player. Now what I need is to get the list of playlists of the channel with its video thumbnail and also all the video IDs. How can I implement this? </p>

答:
This question is very old, however it will helpful for those developers who is looking for youtube channel integration in Android App. I am presenting a rough idea. You can follow this tutorial Youtube channel integration in Android Follow these steps:-

Find youtube channel id.

Genrete SHA1 key

Get API Key for Youtube Data API v3 and paste SHA1 key in restriction of use

Get Channel video list and description with thumbnail image in JSON format from this link by clicking on Load in APIs Explorer. Put your channel id in ChannelId textfield you will get JSON format data of videos.

Add internet permission in AndroidManifest file.

Download the YoutubePlayerApi.jar file in your library of Android projects and volley library in build.gradle file.

Create a Channel Activity and use JSON parsing to parse the Video list.

Pass the videoId from yourAdapter to another Activity by intent.putExtra().

Get the videoId in another Activity by getExtra().

show video by using cueVideo().


问:
Thrown off by functor syntax in Effective C++
In Item 15 of Effective C++ 3rd edition an RAII class Font contains as its resource a FontHandle.
The item shows how the Font class can offer an implicit conversion function to its FontHandle thus:

```<code>operator FontHandle() const
    {return f;}
</code>```

What is the difference between this code and:

```<code>FontHandle operator()() const
    {return f;}
</code>```

If there is no difference, is it an unusual and not commonly used syntax?

答:
The first, operator FontHandle, is a conversion operator.  It allows an instance of this class type to be implicitly converted to a FontHandle object, so you could write:

```<code>Font myFont;
FontHandle handle = myFont;
</code>```

More commonly, conversion operators are used to allow you to use an object of one type as if it were another type in an expression.  For example,

```<code>void f(FontHandle fh);

Font myFont;
f(myFont); // converts myFont to a FontHandle via the conversion operator
</code>```

The second, operator(), is an overload of the function call operator.  It allows an instance of your class type to be used as if it were a function taking no arguments:

```<code>Font myFont;
myFont();
</code>```

Implicit conversion operators are less common than operator() overloads (or, they should be less common).  In many cases they can be very error prone because you have no control over when the operator is used (in C++0x, you'll be able to make conversion operators explicit to ensure they are only usable in a few select circumstances).  Whether you want a conversion operator or an operator() overload depends on the circumstances, though.

Body:
In Item 15 of Effective C++ 3rd edition an RAII class Font contains as its resource a FontHandle.
The item shows how the Font class can offer an implicit conversion function to its FontHandle thus:

operator FontHandle() const
    {return f;}

What is the difference between this code and:

FontHandle operator()() const
    {return f;}

If there is no difference, is it an unusual and not commonly used syntax?

Body:
The first, operator FontHandle, is a conversion operator.  It allows an instance of this class type to be implicitly converted to a FontHandle object, so you could write:

Font myFont;
FontHandle handle = myFont;

More commonly, conversion operators are used to allow you to use an object of one type as if it were another type in an expression.  For example,

void f(FontHandle fh);

Font myFont;
f(myFont); // converts myFont to a FontHandle via the conversion operator

The second, operator(), is an overload of the function call operator.  It allows an instance of your class type to be used as if it were a function taking no arguments:

Font myFont;
myFont();

Implicit conversion operators are less common than operator() overloads (or, they should be less common).  In many cases they can be very error prone because you have no control over when the operator is used (in C++0x, you'll be able to make conversion operators explicit to ensure they are only usable in a few select circumstances).  Whether you want a conversion operator or an operator() overload depends on the circumstances, though.


问:
Use Word Macro to Determine last character of Paragraph
I have been using this code to Bold-Underline all the headers in my word doc:

```<code>Sub Underline_Headers()
Dim p As Paragraph
For Each p In ActiveDocument.Paragraphs
    If Len(p.Range.Text) < 70 Then
        p.Range.Font.Underline = True
        p.Range.Font.Bold = True
    End If
Next p
End Sub
</code>```

This works great - as long as every header is less than 70 characters long, and the paragraph underneath it is 70 or more characters.

But many times the header can be longer than 70 characters, and the paragraph under the header can be less than 70 characters.

However, the headers always never end with any punctuation, like a "." but the paragraphs underneath them always do.

I am trying to fix the code above to look for all paragraphs not ending in a "." and then Bold-Underline them. In other words, I want to change the rule.

I tried the only thing that made sense to me. The code did not break, but it ended up bold-underline the entire document:

```<code>Sub Underline_Headers()
Dim p As Paragraph
For Each p In ActiveDocument.Paragraphs
    If Right(p.Range.Text,1) <> "." Then
        p.Range.Font.Underline = True
        p.Range.Font.Bold = True
    End If
Next p
End Sub
</code>```

This supposedly looks for all paragraphs where the last character is not ".", which if that worked, would isolate all the headers and only bold-underline them, but obviously that doesn't work.

答:
The last character in every paragraph is a carriage return, Chr(13). The text ends one character before that. The code below also considers the possibility that someone ended a paragraph's text with one or more blank spaces. It takes the "cleaned" string and looks for the last character in a string of possible exceptions, like .?!. You can reduce this string to a single full stop or extend it to include more cnadidates for exception.

```<code>Private Sub UnderlineTitles()

    Dim Para As Paragraph
    Dim Txt As String

    Application.ScreenUpdating = False
    For Each Para In ActiveDocument.Paragraphs
        Txt = Para.Range.Text
        Txt = RTrim(Left(Txt, Len(Txt) - 1))
        ' you can extend the list to include characters like ")]}"
        If InStr(".?!", Right(Txt, 1)) = 0 Then
            ' to choose a different style of underline, remove
            ' "= wdUnderlineSingle", type "=" and select from the dropdown
            Para.Range.Font.Underline = wdUnderlineSingle
        End If
    Next Para
    Application.ScreenUpdating = True
End Sub
</code>```

Body:
I have been using this code to Bold-Underline all the headers in my word doc:

Sub Underline_Headers()
Dim p As Paragraph
For Each p In ActiveDocument.Paragraphs
    If Len(p.Range.Text) < 70 Then
        p.Range.Font.Underline = True
        p.Range.Font.Bold = True
    End If
Next p
End Sub

This works great - as long as every header is less than 70 characters long, and the paragraph underneath it is 70 or more characters.

But many times the header can be longer than 70 characters, and the paragraph under the header can be less than 70 characters.

However, the headers always never end with any punctuation, like a "." but the paragraphs underneath them always do.

I am trying to fix the code above to look for all paragraphs not ending in a "." and then Bold-Underline them. In other words, I want to change the rule.

I tried the only thing that made sense to me. The code did not break, but it ended up bold-underline the entire document:

Sub Underline_Headers()
Dim p As Paragraph
For Each p In ActiveDocument.Paragraphs
    If Right(p.Range.Text,1) <> "." Then
        p.Range.Font.Underline = True
        p.Range.Font.Bold = True
    End If
Next p
End Sub

This supposedly looks for all paragraphs where the last character is not ".", which if that worked, would isolate all the headers and only bold-underline them, but obviously that doesn't work.

Body:
The last character in every paragraph is a carriage return, Chr(13). The text ends one character before that. The code below also considers the possibility that someone ended a paragraph's text with one or more blank spaces. It takes the "cleaned" string and looks for the last character in a string of possible exceptions, like .?!. You can reduce this string to a single full stop or extend it to include more cnadidates for exception.

Private Sub UnderlineTitles()

    Dim Para As Paragraph
    Dim Txt As String

    Application.ScreenUpdating = False
    For Each Para In ActiveDocument.Paragraphs
        Txt = Para.Range.Text
        Txt = RTrim(Left(Txt, Len(Txt) - 1))
        ' you can extend the list to include characters like ")]}"
        If InStr(".?!", Right(Txt, 1)) = 0 Then
            ' to choose a different style of underline, remove
            ' "= wdUnderlineSingle", type "=" and select from the dropdown
            Para.Range.Font.Underline = wdUnderlineSingle
        End If
    Next Para
    Application.ScreenUpdating = True
End Sub


问:
Wordpress init hook called multiple times
I did a fresh installation of wordpress 3.0.4 and attempted to write a simple theme for just the sake of trying.

In functions.php, I created a function called my_setup and hooked it up to init. I noticed that my_setup() is called multiple times and I tried to use a global flag variable to control the execution of the function but to no avail. How do I ensure that my function is only called once?

```<code>       <?php
       // global variables
       $setup_run_before = 0;
       ?>

      <?php

      function my_setup() {
              global $setup_run_before, $a;
              if($setup_run_before == 0) {
                      $setup_run_before = 1;
// this section is always called even with global variable.
              }
      }

      ?>

      <?php
      add_action('init', 'my_setup');

      ?>
</code>```

Regards,
John Doe

答:
```<code>  function my_setup() {
         echo 123 . '<br />';
  }
  add_action('init', 'my_setup');
</code>```

I see 123 appear once only. Init should not run more than once, and does not on my installation.

However i think you'll find the clue you're looking for in Rob's Answer to Wordpress why is the init hook invoked multiple times.

Hope that helps.

Body:
I did a fresh installation of wordpress 3.0.4 and attempted to write a simple theme for just the sake of trying.

In functions.php, I created a function called my_setup and hooked it up to init. I noticed that my_setup() is called multiple times and I tried to use a global flag variable to control the execution of the function but to no avail. How do I ensure that my function is only called once?

       <?php
       // global variables
       $setup_run_before = 0;
       ?>

      <?php

      function my_setup() {
              global $setup_run_before, $a;
              if($setup_run_before == 0) {
                      $setup_run_before = 1;
// this section is always called even with global variable.
              }
      }

      ?>

      <?php
      add_action('init', 'my_setup');

      ?>

Regards,
John Doe

Body:
  function my_setup() {
         echo 123 . '<br />';
  }
  add_action('init', 'my_setup');

I see 123 appear once only. Init should not run more than once, and does not on my installation.

However i think you'll find the clue you're looking for in Rob's Answer to Wordpress why is the init hook invoked multiple times.

Hope that helps.


问:
Converting HTMLCanvasElement to a object
I'm using a image cropper library to crop an image. I want to upload the cropped image using a function i have written. The issue is the image cropper returns the cropped image as HTMLCanvasElement . i want to convert it to a object to use in my function. I have tried passing a image file taken using FileReader to my function and it's working perfectly. The issue i''m facing is when trying to pass the cropped image which is a HTMLCanvasElement. How can i solve this?

This is the cropper library i'm using

https://github.com/mosch/react-avatar-editor

This is the function which i get the cropped image.

```<code>handleSave = () => {

    const img = this.editor.getImage();

    console.log("Type of image "+typeof img);

    this.props.croppedImage(img);

}
</code>```

In my second component i'm accessing the croppedImage function

```<code><CropperTest croppedImage={this.getCroppedImg}/>
</code>```

getCroppedImg function

```<code>  getCroppedImg(img) {

        console.log("typeofNEW"+typeof event,img);

        this.props.onImageImgPoll(img);

    }
</code>```

From here i'm passing the cropped image to a function called onImageImgPoll which is in another component

```<code>  onImageImgPoll(event) {

        this.setState({

            croppedImage:event

        })

        let array = this.state.filepoll.slice();
        let unq_file = event;

            let reader = new FileReader();
            reader.onloadend = (e) => {

                array.push(unq_file);
            };

    }
</code>```

And the files i'm passing to the array should get uploaded using other functions. But in this case it won't happen because the passed image is in the form of HTMLCanvasElement . How can i fix this?

答:
You can save it as data url and then use it again in another function.
Btw. You cannot upload via javascript. You can do it with this function via ajax (base64 string) and then upload it by php for example.</p>

```<code>canvas.toDataURL();
</code>```

Body:
I'm using a image cropper library to crop an image. I want to upload the cropped image using a function i have written. The issue is the image cropper returns the cropped image as HTMLCanvasElement . i want to convert it to a object to use in my function. I have tried passing a image file taken using FileReader to my function and it's working perfectly. The issue i''m facing is when trying to pass the cropped image which is a HTMLCanvasElement. How can i solve this?

This is the cropper library i'm using

https://github.com/mosch/react-avatar-editor

This is the function which i get the cropped image.

handleSave = () => {

    const img = this.editor.getImage();

    console.log("Type of image "+typeof img);

    this.props.croppedImage(img);

}

In my second component i'm accessing the croppedImage function

<CropperTest croppedImage={this.getCroppedImg}/>

getCroppedImg function

  getCroppedImg(img) {

        console.log("typeofNEW"+typeof event,img);

        this.props.onImageImgPoll(img);

    }

From here i'm passing the cropped image to a function called onImageImgPoll which is in another component

  onImageImgPoll(event) {

        this.setState({

            croppedImage:event

        })

        let array = this.state.filepoll.slice();
        let unq_file = event;

            let reader = new FileReader();
            reader.onloadend = (e) => {

                array.push(unq_file);
            };

    }

And the files i'm passing to the array should get uploaded using other functions. But in this case it won't happen because the passed image is in the form of HTMLCanvasElement . How can i fix this?

Body:
You can save it as data url and then use it again in another function.
Btw. You cannot upload via javascript. You can do it with this function via ajax (base64 string) and then upload it by php for example.

canvas.toDataURL();


问:
closure return function doesn't changes scoped variable
```<code>function testLet(){
    var x=9;
    return{
        y:x,
        getX: function(){
            return ++x;
        },
    }
}

var obj = new testLet();
console.log(obj.y); //9 as expected
console.log(obj.getX()); //10 as expected
console.log(obj.getX()); //11 as expected
console.log(obj.y); //I expect it 11.. but it stays 9
</code>```

<p>Why the last line returns 9 instead of 11 as x is in the same scope? </p>

答:
y:x means "Copy the current value of x to the property y".

The value, at the time, is 9.

Subsequent changes to the value of x won't change the value of y.

You can either change your getX function to modify this.y, or you can change the y property to be a getter function which reads the current value of x.

Body:
function testLet(){
    var x=9;
    return{
        y:x,
        getX: function(){
            return ++x;
        },
    }
}

var obj = new testLet();
console.log(obj.y); //9 as expected
console.log(obj.getX()); //10 as expected
console.log(obj.getX()); //11 as expected
console.log(obj.y); //I expect it 11.. but it stays 9

Why the last line returns 9 instead of 11 as x is in the same scope?


问:
Add product to cart outside of magento (external script)
I have to add a product through an external page into the cart under the same URL.

The difference between these pages is that e.g. test.de is running TYPO3 and test.de/Shop is running Magento and test.de/productpage is running an external script through TYPO3.

From the product page, I have to add a product to the Magento cart to proceed the checkout.

The key problem is to start the session outside of Magento.
If I call test.de/Shop/checkout/cart before I go totest.de/productpage and add a product to the cart, it works flawlessly.
But if I go the normal way (site -> productpage -> cart) I cant get Magento to listen to the session on the product page.

I have something like this to call

```<code>function addToBasket()
    {

        require_once('../app/Mage.php');
        ob_start();
        session_start();
        umask(0);
        session_write_close();
        Mage::app()->setCurrentStore(33);

        $session = Mage::getSingleton('core/session', array('name'=>'frontend'));

        $productId = !isset($_GET['activeProdId']) ? '' : $_GET['activeProdId'];
        $qty = !isset($_GET['qty']) ? '1' : $_GET['qty'];

        if(empty($productId)) {
            return "no product-id found";
        }

        $request = Mage::app()->getRequest();

        $product = Mage::getModel('catalog/product')->load($productId);

        $cart = Mage::helper('checkout/cart')->getCart();

        $cart->addProduct($product, array('qty' => $qty));

        $session->setLastAddedProductId($product->getId());
        $session->setCartWasUpdated(true);

        $cart->save();

        return true;

   }
</code>```

The addToBasket is called through ajax.

So the question is: How do I start the session outside of the Magento-scope and put products into the cart?

答:
once you include Mage.php you will need to initialize Magento with

```<code>Mage::app("default");
</code>```

(first param is store code)

after that...

```<code>Mage::getSingleton('core/session', array('name'=>'frontend'));
</code>```

...will work as it should.

Body:
I have to add a product through an external page into the cart under the same URL.

The difference between these pages is that e.g. test.de is running TYPO3 and test.de/Shop is running Magento and test.de/productpage is running an external script through TYPO3.

From the product page, I have to add a product to the Magento cart to proceed the checkout.

The key problem is to start the session outside of Magento.
If I call test.de/Shop/checkout/cart before I go totest.de/productpage and add a product to the cart, it works flawlessly.
But if I go the normal way (site -> productpage -> cart) I cant get Magento to listen to the session on the product page.

I have something like this to call

function addToBasket()
    {

        require_once('../app/Mage.php');
        ob_start();
        session_start();
        umask(0);
        session_write_close();
        Mage::app()->setCurrentStore(33);

        $session = Mage::getSingleton('core/session', array('name'=>'frontend'));

        $productId = !isset($_GET['activeProdId']) ? '' : $_GET['activeProdId'];
        $qty = !isset($_GET['qty']) ? '1' : $_GET['qty'];

        if(empty($productId)) {
            return "no product-id found";
        }

        $request = Mage::app()->getRequest();

        $product = Mage::getModel('catalog/product')->load($productId);

        $cart = Mage::helper('checkout/cart')->getCart();

        $cart->addProduct($product, array('qty' => $qty));

        $session->setLastAddedProductId($product->getId());
        $session->setCartWasUpdated(true);

        $cart->save();

        return true;

   }

The addToBasket is called through ajax.

So the question is: How do I start the session outside of the Magento-scope and put products into the cart?

Body:
once you include Mage.php you will need to initialize Magento with

Mage::app("default");

(first param is store code)

after that...

Mage::getSingleton('core/session', array('name'=>'frontend'));

...will work as it should.


问:
Swift: Recursively cycle through all subviews to find a specific class and append to an array
Having a devil of a time trying to figure this out. I asked a similar question here: Swift: Get all subviews of a specific type and add to an array

While this works, I realized there are many subviews and sub-sub views, and so I need a function that starts at the main UIView, cycles through all the subviews (and their subviews until there aren't any left) and adds it to an array for a custom button class which I have named CheckCircle.

Essentially I'd like to end up with an array of CheckCircles which constitute all the CheckCircles added to that view programmatically.

Any ideas? Here's what I've been working on. It doesn't seem to be appending any Checkcircles to the array:

```<code>    func getSubviewsOfView(v:UIView) -> [CheckCircle] {
        var circleArray = [CheckCircle]()
        // Get the subviews of the view

        var subviews = v.subviews

        if subviews.count == 0 {
            return circleArray
        }

        for subview : AnyObject in subviews{
  if let viewToAppend = subview as? CheckCircle {
        circleArray.append(viewToAppend as CheckCircle)
      }
            getSubviewsOfView(subview as! UIView)
        }
        return circleArray
    }
</code>```

答:
Based on Aaron Brager and ullstrm answers

Details

Xcode 9.1, Swift 4,

Xcode Version 10.3 (10G8), Swift 5

Solution

```<code>extension UIView {

    class func getAllSubviews<T: UIView>(from parenView: UIView) -> [T] {
        return parenView.subviews.flatMap { subView -> [T] in
            var result = getAllSubviews(from: subView) as [T]
            if let view = subView as? T { result.append(view) }
            return result
        }
    }

    class func getAllSubviews(from parenView: UIView, types: [UIView.Type]) -> [UIView] {
        return parenView.subviews.flatMap { subView -> [UIView] in
            var result = getAllSubviews(from: subView) as [UIView]
            for type in types {
                if subView.classForCoder == type {
                    result.append(subView)
                    return result
                }
            }
            return result
        }
    }

    func getAllSubviews<T: UIView>() -> [T] { return UIView.getAllSubviews(from: self) as [T] }
    func get<T: UIView>(all type: T.Type) -> [T] { return UIView.getAllSubviews(from: self) as [T] }
    func get(all types: [UIView.Type]) -> [UIView] { return UIView.getAllSubviews(from: self, types: types) }
}
</code>```

Usage sample

```<code>var allViews = UIView.getAllSubviews(from: simpleView)
func printResult(with text: String) {
    print("\n==============================================")
    print("\(text):\n\(allViews.map { $0.classForCoder } )")
}
printResult(with: "UIView.getAllSubviews(from: simpleView)")

allViews = UIView.getAllSubviews(from: simpleView) as [UILabel]
printResult(with: "UIView.getAllSubviews(from: simpleView) as [UILabel]")

allViews = UIView.getAllSubviews(from: simpleView, types: [UIStackView.self, UILabel.self])
printResult(with: "UIView.getAllSubviews(from: simpleView, types: [UIStackView.self, UILabel.self])")

allViews = simpleView.getAllSubviews()
printResult(with: "simpleView.getAllSubviews()")

allViews = simpleView.getAllSubviews() as [UILabel]
printResult(with: "simpleView.getAllSubviews() as [UILabel]")

allViews = simpleView.get(all: UILabel.self)
printResult(with: "simpleView.get(all: UILabel.self)")

allViews = simpleView.get(all: [UIStackView.self, UILabel.self])
printResult(with: "simpleView.get(all: [UIStackView.self, UILabel.self])")
</code>```

Output of the sample

```<code>==============================================
UIView.getAllSubviews(from: simpleView):
[UILabel, UIButton, UILabel, UILabel, UILabel, UIStackView]

==============================================
UIView.getAllSubviews(from: simpleView) as [UILabel]:
[UILabel, UILabel, UILabel, UILabel]

==============================================
UIView.getAllSubviews(from: simpleView, types: [UIStackView.self, UILabel.self]):
[UILabel, UILabel, UILabel, UILabel, UIStackView]

==============================================
simpleView.getAllSubviews():
[UILabel, UIButton, UILabel, UILabel, UILabel, UIStackView]

==============================================
simpleView.getAllSubviews() as [UILabel]:
[UILabel, UILabel, UILabel, UILabel]

==============================================
simpleView.get(all: UILabel.self):
[UILabel, UILabel, UILabel, UILabel]

==============================================
simpleView.get(all: [UIStackView.self, UILabel.self]):
[UILabel, UILabel, UILabel, UILabel, UIStackView]
</code>```

Storyboard of the sample

Other info

Also, I suggest to work with weak references. Array with weak references to objects

Body:
Having a devil of a time trying to figure this out. I asked a similar question here: Swift: Get all subviews of a specific type and add to an array

While this works, I realized there are many subviews and sub-sub views, and so I need a function that starts at the main UIView, cycles through all the subviews (and their subviews until there aren't any left) and adds it to an array for a custom button class which I have named CheckCircle.

Essentially I'd like to end up with an array of CheckCircles which constitute all the CheckCircles added to that view programmatically.

Any ideas? Here's what I've been working on. It doesn't seem to be appending any Checkcircles to the array:

    func getSubviewsOfView(v:UIView) -> [CheckCircle] {
        var circleArray = [CheckCircle]()
        // Get the subviews of the view

        var subviews = v.subviews

        if subviews.count == 0 {
            return circleArray
        }

        for subview : AnyObject in subviews{
  if let viewToAppend = subview as? CheckCircle {
        circleArray.append(viewToAppend as CheckCircle)
      }
            getSubviewsOfView(subview as! UIView)
        }
        return circleArray
    }

Body:
Based on Aaron Brager and ullstrm answers

Details

Xcode 9.1, Swift 4,

Xcode Version 10.3 (10G8), Swift 5

Solution

extension UIView {

    class func getAllSubviews<T: UIView>(from parenView: UIView) -> [T] {
        return parenView.subviews.flatMap { subView -> [T] in
            var result = getAllSubviews(from: subView) as [T]
            if let view = subView as? T { result.append(view) }
            return result
        }
    }

    class func getAllSubviews(from parenView: UIView, types: [UIView.Type]) -> [UIView] {
        return parenView.subviews.flatMap { subView -> [UIView] in
            var result = getAllSubviews(from: subView) as [UIView]
            for type in types {
                if subView.classForCoder == type {
                    result.append(subView)
                    return result
                }
            }
            return result
        }
    }

    func getAllSubviews<T: UIView>() -> [T] { return UIView.getAllSubviews(from: self) as [T] }
    func get<T: UIView>(all type: T.Type) -> [T] { return UIView.getAllSubviews(from: self) as [T] }
    func get(all types: [UIView.Type]) -> [UIView] { return UIView.getAllSubviews(from: self, types: types) }
}

Usage sample

var allViews = UIView.getAllSubviews(from: simpleView)
func printResult(with text: String) {
    print("\n==============================================")
    print("\(text):\n\(allViews.map { $0.classForCoder } )")
}
printResult(with: "UIView.getAllSubviews(from: simpleView)")

allViews = UIView.getAllSubviews(from: simpleView) as [UILabel]
printResult(with: "UIView.getAllSubviews(from: simpleView) as [UILabel]")

allViews = UIView.getAllSubviews(from: simpleView, types: [UIStackView.self, UILabel.self])
printResult(with: "UIView.getAllSubviews(from: simpleView, types: [UIStackView.self, UILabel.self])")

allViews = simpleView.getAllSubviews()
printResult(with: "simpleView.getAllSubviews()")

allViews = simpleView.getAllSubviews() as [UILabel]
printResult(with: "simpleView.getAllSubviews() as [UILabel]")

allViews = simpleView.get(all: UILabel.self)
printResult(with: "simpleView.get(all: UILabel.self)")

allViews = simpleView.get(all: [UIStackView.self, UILabel.self])
printResult(with: "simpleView.get(all: [UIStackView.self, UILabel.self])")

Output of the sample

==============================================
UIView.getAllSubviews(from: simpleView):
[UILabel, UIButton, UILabel, UILabel, UILabel, UIStackView]

==============================================
UIView.getAllSubviews(from: simpleView) as [UILabel]:
[UILabel, UILabel, UILabel, UILabel]

==============================================
UIView.getAllSubviews(from: simpleView, types: [UIStackView.self, UILabel.self]):
[UILabel, UILabel, UILabel, UILabel, UIStackView]

==============================================
simpleView.getAllSubviews():
[UILabel, UIButton, UILabel, UILabel, UILabel, UIStackView]

==============================================
simpleView.getAllSubviews() as [UILabel]:
[UILabel, UILabel, UILabel, UILabel]

==============================================
simpleView.get(all: UILabel.self):
[UILabel, UILabel, UILabel, UILabel]

==============================================
simpleView.get(all: [UIStackView.self, UILabel.self]):
[UILabel, UILabel, UILabel, UILabel, UIStackView]

Storyboard of the sample

Other info

Also, I suggest to work with weak references. Array with weak references to objects

ContentLicense: CC BY-SA 4.0


问:
C# How to delete items in the listbox(loaded from textfile)
How do I delete selected item from the listbox. The content of the listbox is from a text File and I use StreamReader to read all content in the textfile and display in the listbox. And If i delete it, will it update the textfile ?

Populate listbox

```<code>        public void Outbound_load()
    {
        Listbox1.Items.Clear();
        using (StreamReader sr = new StreamReader("C:\\Users\\jason\\Desktop\\Outbound.txt"))
        {
            string line;
            // Read and display lines from the file until the end of
            // the file is reached.
            while ((line = sr.ReadLine()) != null)
            {
                Listbox1.Items.Add(line);
            }
            sr.Close();
        }
    }
</code>```

答:
Keep it simple:</p>

```<code>public void Save(string filePath)
{
    File.WriteAllLines(filePath, listBox.Items.Cast<string>().ToArray());
}
</code>```

Body:
How do I delete selected item from the listbox. The content of the listbox is from a text File and I use StreamReader to read all content in the textfile and display in the listbox. And If i delete it, will it update the textfile ?

Populate listbox

        public void Outbound_load()
    {
        Listbox1.Items.Clear();
        using (StreamReader sr = new StreamReader("C:\\Users\\jason\\Desktop\\Outbound.txt"))
        {
            string line;
            // Read and display lines from the file until the end of
            // the file is reached.
            while ((line = sr.ReadLine()) != null)
            {
                Listbox1.Items.Add(line);
            }
            sr.Close();
        }
    }

Body:
Keep it simple:

public void Save(string filePath)
{
    File.WriteAllLines(filePath, listBox.Items.Cast<string>().ToArray());
}


问:
T-SQL: Convert datatime2 to datetime for all columns of type datetime2
I've got a database full of datetime2 columns than needs to be moved to a SQL 2005 database. So, I need to convert all these datetime2(7) columns to datetime.

How can I go about doing this?

Right now I've managed to select the table name and column name for all columns with the datetime2 datatype like this:

```<code>SELECT t.name, c.name, i.DATA_TYPE
FROM sys.tables AS t
JOIN sys.columns c ON t.object_id = c.object_id
JOIN information_schema.columns i ON i.TABLE_NAME = t.name AND i.COLUMN_NAME = c.name
WHERE i.data_type = 'datetime2'
</code>```

I just don't know how to do the rest.

答:
Improved the above answer to cater for schemas </p>

```<code>DECLARE @SQL AS NVARCHAR(1024)
DECLARE @TBL AS NVARCHAR(255)
DECLARE @COL AS NVARCHAR(255)
DECLARE @SCH AS NVARCHAR(255)
DECLARE @NUL AS BIT
DECLARE CUR CURSOR FAST_FORWARD FOR
    SELECT  t.name AS TableName, c.name ColumnName, s.name AS SchemaName, c.is_nullable
    FROM    sys.tables AS t
    JOIN    sys.columns c ON t.object_id = c.object_id
    JOIN    information_schema.columns AS i ON i.TABLE_NAME = t.name AND i.COLUMN_NAME = c.name
    JOIN    sys.schemas AS s on t.schema_id = s.schema_id
    WHERE   i.data_type = 'datetime2'
    ORDER BY t.name, c.name

OPEN CUR
FETCH NEXT FROM CUR INTO @TBL, @COL, @SCH, @NUL
WHILE @@FETCH_STATUS = 0
BEGIN
    SELECT @SQL = 'ALTER TABLE ['+@SCH+'].[' + @TBL + '] ALTER COLUMN [' + @COL + '] datetime' + (CASE WHEN @NUL=1 THEN '' ELSE ' NOT' END) + ' NULL;'
    EXEC sp_executesql @SQL
    FETCH NEXT FROM CUR INTO @TBL, @COL,@SCH, @NUL
END

CLOSE CUR;
DEALLOCATE CUR;
</code>```

Body:
I've got a database full of datetime2 columns than needs to be moved to a SQL 2005 database. So, I need to convert all these datetime2(7) columns to datetime.

How can I go about doing this?

Right now I've managed to select the table name and column name for all columns with the datetime2 datatype like this:

SELECT t.name, c.name, i.DATA_TYPE
FROM sys.tables AS t
JOIN sys.columns c ON t.object_id = c.object_id
JOIN information_schema.columns i ON i.TABLE_NAME = t.name AND i.COLUMN_NAME = c.name
WHERE i.data_type = 'datetime2'

I just don't know how to do the rest.

Body:
Improved the above answer to cater for schemas

DECLARE @SQL AS NVARCHAR(1024)
DECLARE @TBL AS NVARCHAR(255)
DECLARE @COL AS NVARCHAR(255)
DECLARE @SCH AS NVARCHAR(255)
DECLARE @NUL AS BIT
DECLARE CUR CURSOR FAST_FORWARD FOR
    SELECT  t.name AS TableName, c.name ColumnName, s.name AS SchemaName, c.is_nullable
    FROM    sys.tables AS t
    JOIN    sys.columns c ON t.object_id = c.object_id
    JOIN    information_schema.columns AS i ON i.TABLE_NAME = t.name AND i.COLUMN_NAME = c.name
    JOIN    sys.schemas AS s on t.schema_id = s.schema_id
    WHERE   i.data_type = 'datetime2'
    ORDER BY t.name, c.name

OPEN CUR
FETCH NEXT FROM CUR INTO @TBL, @COL, @SCH, @NUL
WHILE @@FETCH_STATUS = 0
BEGIN
    SELECT @SQL = 'ALTER TABLE ['+@SCH+'].[' + @TBL + '] ALTER COLUMN [' + @COL + '] datetime' + (CASE WHEN @NUL=1 THEN '' ELSE ' NOT' END) + ' NULL;'
    EXEC sp_executesql @SQL
    FETCH NEXT FROM CUR INTO @TBL, @COL,@SCH, @NUL
END

CLOSE CUR;
DEALLOCATE CUR;


问:
GDB pid changes when connected automatically and quit
I am trying to attach an existing process, run some commands and print the required information. However, when I do it, I see that the PID of the process is changed (with killed) command being displayed.

Code

```<code>     1  #include <iostream>
     2  #include <unistd.h>
     3  using namespace std;
     4
     5
     6  int main()
     7  {
     8      do
     9      {
    10          static int s = 100;
    11          s = s+1;
    12          sleep (3);
    13      } while(1);
    14      return 0;
    15  }
    16
</code>```

GDB commands

```<code>> cat /tmp/command.txt
set pagination off
set logging file /home/testgrp/gdb.txt
set logging on
b sample.cc:11
commands 1
    p s
end
run 1
quit
</code>```

Output

```<code>root@198.18.81.198:/desktop/user1/workspace# ps -eaf | grep out
root     16724  8877  0 08:25 pts/1    00:00:00 grep --color=auto out
root@198.18.81.198:/desktop/user1/workspace# cat /home/testgrp/gdb.txt
cat: /home/testgrp/gdb.txt: No such file or directory
root@198.18.81.198:/desktop/user1/workspace# ./a.out &
[1] 16762
root@198.18.81.198:/desktop/user1/workspace# gdb --batch-silent -x=/tmp/command.txt -p 16762
[1]+  Killed                  ./a.out
root@198.18.81.198:/desktop/user1/workspace# ps -eaf | grep out
root     16805     1  0 08:25 pts/1    00:00:00 /desktop/user1/workspace/a.out 1
root     16823  8877  0 08:25 pts/1    00:00:00 grep --color=auto out
root@198.18.81.198:/desktop/user1/workspace# cat /home/testgrp/gdb.txt
Breakpoint 1 at 0x400711: file sample.cc, line 11.
$1 = 100
A debugging session is active.

    Inferior 1 [process 16805] will be detached.

Quit anyway? (y or n) [answered Y; input not from terminal]
</code>```

Question

How do I get the required information without changing the PID of the process?

More importantly, why does the pid change and previous PID is killed

Appendix

GDB version

```<code>GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2aka8.0.1) 7.7.1
Copyright (C) 2014 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
</code>```

答:
in the last two lines of your gdb scripts

```<code>run 1
quit
</code>```

"run 1" will restart the program it is debugging with argument "1". by default, it should ask you to confirm restart or not.But you have an argument "--batch-silent" when you starting gdb. so your process restart without message.

delete "--batch-silent" and last 2 lines of your gdb script then you can break and debug.
"b sample.cc:11" will stop in system function sleep, you can change it to other line if you feel confuse . (I recommend you to read some simpler demos before using gdb,so many cmd will let beginner feel confuse)

Body:
I am trying to attach an existing process, run some commands and print the required information. However, when I do it, I see that the PID of the process is changed (with killed) command being displayed.

Code

     1  #include <iostream>
     2  #include <unistd.h>
     3  using namespace std;
     4
     5
     6  int main()
     7  {
     8      do
     9      {
    10          static int s = 100;
    11          s = s+1;
    12          sleep (3);
    13      } while(1);
    14      return 0;
    15  }
    16

GDB commands

> cat /tmp/command.txt
set pagination off
set logging file /home/testgrp/gdb.txt
set logging on
b sample.cc:11
commands 1
    p s
end
run 1
quit

Output

root@198.18.81.198:/desktop/user1/workspace# ps -eaf | grep out
root     16724  8877  0 08:25 pts/1    00:00:00 grep --color=auto out
root@198.18.81.198:/desktop/user1/workspace# cat /home/testgrp/gdb.txt
cat: /home/testgrp/gdb.txt: No such file or directory
root@198.18.81.198:/desktop/user1/workspace# ./a.out &
[1] 16762
root@198.18.81.198:/desktop/user1/workspace# gdb --batch-silent -x=/tmp/command.txt -p 16762
[1]+  Killed                  ./a.out
root@198.18.81.198:/desktop/user1/workspace# ps -eaf | grep out
root     16805     1  0 08:25 pts/1    00:00:00 /desktop/user1/workspace/a.out 1
root     16823  8877  0 08:25 pts/1    00:00:00 grep --color=auto out
root@198.18.81.198:/desktop/user1/workspace# cat /home/testgrp/gdb.txt
Breakpoint 1 at 0x400711: file sample.cc, line 11.
$1 = 100
A debugging session is active.

    Inferior 1 [process 16805] will be detached.

Quit anyway? (y or n) [answered Y; input not from terminal]

Question

How do I get the required information without changing the PID of the process?

More importantly, why does the pid change and previous PID is killed

Appendix

GDB version

GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2aka8.0.1) 7.7.1
Copyright (C) 2014 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".

Body:
in the last two lines of your gdb scripts

run 1
quit

"run 1" will restart the program it is debugging with argument "1". by default, it should ask you to confirm restart or not.But you have an argument "--batch-silent" when you starting gdb. so your process restart without message.

delete "--batch-silent" and last 2 lines of your gdb script then you can break and debug.
"b sample.cc:11" will stop in system function sleep, you can change it to other line if you feel confuse . (I recommend you to read some simpler demos before using gdb,so many cmd will let beginner feel confuse)


问:
Encoding parameters in Symfony path twig function
In my application, I'm using the Symfony Twig extension function path to create a link to another route. That route accepts a parameter, so I wrote my path function like this:

```<code><a href="{{ path('r', {p: p}) }}">...</a>
</code>```

In some cases, the given value p contains a slash and Symfony fails with the error:

"Parameter "p" for route "r" must match "[^/]++" (".../..." given) to generate a corresponding URL.")

I would expect Symfony to deal with this and automatically URL encode these values, but apparently not (or I'm doing something wrong).

Anyway, I managed to fix that with the url_encode Twig filter, like so:

```<code><a href="{{ path('r', {p: p|url_encode}) }}">...</a>
</code>```

Now in my controller, I accept this parameter like so:

```<code>/**
 * @Route("/a/b/{p}", name="r")
 **/
public function someAction($p) {
   // ...
}
</code>```

And apparently Symfony does not automatically URL decode this value $p, which I'd expect as well.

Am I doing something wrong here, or is it really necessary to handle URL encoding/decoding yourself? In the Symfony docs I don't find any details about this at all.

答:
Apparently the default parameter restrictions don't allow forward slashes. After "loosening" them it worked:</p>

```<code>/**
 * @Route("/a/b/{p}", name="r", requirements={"diagramResourceId"=".+"})
 **/
public function someAction($p) {
   // ...
}
</code>```

Body:
In my application, I'm using the Symfony Twig extension function path to create a link to another route. That route accepts a parameter, so I wrote my path function like this:

...

In some cases, the given value p contains a slash and Symfony fails with the error:

"Parameter "p" for route "r" must match "[^/]++" (".../..." given) to generate a corresponding URL.")

I would expect Symfony to deal with this and automatically URL encode these values, but apparently not (or I'm doing something wrong).

Anyway, I managed to fix that with the url_encode Twig filter, like so:

...

Now in my controller, I accept this parameter like so:

/**
 * @Route("/a/b/{p}", name="r")
 **/
public function someAction($p) {
   // ...
}

And apparently Symfony does not automatically URL decode this value $p, which I'd expect as well.

Am I doing something wrong here, or is it really necessary to handle URL encoding/decoding yourself? In the Symfony docs I don't find any details about this at all.

Body:
Apparently the default parameter restrictions don't allow forward slashes. After "loosening" them it worked:

/**
 * @Route("/a/b/{p}", name="r", requirements={"diagramResourceId"=".+"})
 **/
public function someAction($p) {
   // ...
}


问:
Google Drive php API V3: Can't search folder with cyrillic name
9 months ago a I wrote a little project and one of it's features was to search a specific folder in google drive's root or inner folder and return its id. The folder name can be Latin or Cyrillic. Until July or August 2017 everything worked fine, but since two months it started to return empty array when I trying to search folders with Cyrillic names and created recently (younger 2 months). If I create folder with Latin name - all works fine.

This is my old code for searching in drive's root:

```<code>$driveService->files->listFiles([
                'q' => "mimeType='application/vnd.google-apps.folder' and 'root' in parents and name = 'Новая Папка' and trashed = false"
            ]);
</code>```

This doesn't work. If I create folder named 'New Folder' everything works fine without changes.

But if I change 'name =' to 'name contains'

```<code>$driveService->files->listFiles([
                'q' => "mimeType='application/vnd.google-apps.folder' and 'root' in parents and name contains 'Новая Папка' and trashed = false"
            ]);
</code>```

Everything works perfectly. But this code is dangerous - I expect, that code will return only one folder, but if near this folder will be created folders with names 'Новая папка 1', 'Новая папка 2', 'Новая папка 10' etc..

Google API V3 docs says to use 'name =' to search exact name, so I'm stumped.

答:
As it turns out this is a known bug in the Google Drive APIs documented here.

For now the workaround is to use the contains filter and manually look for the correct result afterwards like this:

```<code>getFileByName(name) {
  files = GoogleDriveAPI.searchFiles('title contains "%name"')
  for(file in files) {
    if(file.getName() === name)
        return file
  }
  return null
}
</code>```

Body:
9 months ago a I wrote a little project and one of it's features was to search a specific folder in google drive's root or inner folder and return its id. The folder name can be Latin or Cyrillic. Until July or August 2017 everything worked fine, but since two months it started to return empty array when I trying to search folders with Cyrillic names and created recently (younger 2 months). If I create folder with Latin name - all works fine.

This is my old code for searching in drive's root:

$driveService->files->listFiles([
                'q' => "mimeType='application/vnd.google-apps.folder' and 'root' in parents and name = 'Новая Папка' and trashed = false"
            ]);

This doesn't work. If I create folder named 'New Folder' everything works fine without changes.

But if I change 'name =' to 'name contains'

$driveService->files->listFiles([
                'q' => "mimeType='application/vnd.google-apps.folder' and 'root' in parents and name contains 'Новая Папка' and trashed = false"
            ]);

Everything works perfectly. But this code is dangerous - I expect, that code will return only one folder, but if near this folder will be created folders with names 'Новая папка 1', 'Новая папка 2', 'Новая папка 10' etc..

Google API V3 docs says to use 'name =' to search exact name, so I'm stumped.

Body:
As it turns out this is a known bug in the Google Drive APIs documented here.

For now the workaround is to use the contains filter and manually look for the correct result afterwards like this:

getFileByName(name) {
  files = GoogleDriveAPI.searchFiles('title contains "%name"')
  for(file in files) {
    if(file.getName() === name)
        return file
  }
  return null
}


问:
Recover default style when modified with JavaScript
In a JS function, I've set the background color of a text field like this:

```<code>document.getElementsByName(formId)[0].title.style.backgroundColor = "#7FB75E";
</code>```

In another function, I want to reset the background color to the default value defined in my style sheet. How can I do this?

答:
Before setting the background color to the new value, store it as a property on that element for later retrieval like so.</p>

```<code>var el = document.getElementsByName(formId)[0].title;
el._originalBackgroundColor = el.style.backgroundColor;

// Set the new color
el.style.backgroundColor = "#7FB75E";

// Set it back to original
el.style.backgroundColor = el._originalBackgroundColor;
</code>```

Body:
In a JS function, I've set the background color of a text field like this:

document.getElementsByName(formId)[0].title.style.backgroundColor = "#7FB75E";

In another function, I want to reset the background color to the default value defined in my style sheet. How can I do this?

Body:
Before setting the background color to the new value, store it as a property on that element for later retrieval like so.

var el = document.getElementsByName(formId)[0].title;
el._originalBackgroundColor = el.style.backgroundColor;

// Set the new color
el.style.backgroundColor = "#7FB75E";

// Set it back to original
el.style.backgroundColor = el._originalBackgroundColor;


问:
array values with where condition in laravel query
I have an array called assetIDs as below

```<code>$assetIDs = Collection {#505 ▼
  #items: array:2 [▼
    0 => 4
    1 => 7
  ]
}
</code>```

and I have the data in the table as below shown

and I'm doing query on the above table using this

$supplier_id = SupplierAsset::whereIn('asset_id',$asset_ids)->pluck('supplier_id');

and result for the above query is below

```<code>Collection {#510 ▼
  #items: array:3 [▼
    0 => 1
    1 => 1
    2 => 2
  ]
}
</code>```

here whereIn is returning all the possible rows which satisfies the condition. Actually I need to get the result as like which supplier_id has both the values of assetIDs array.In my table supplier_id=1 has the both values 4 and 7 Just like below collection.

```<code>Collection {#510 ▼
  #items: array:3 [▼
    0 => 1
    1 => 1
  ]
}
</code>```

Can anybody suggest me the solution for this please?

答:
Here is the mysql you should do :

1- get all the id who have more than 1 supplier_id :

```<code>SELECT supplier_id, Count(distinct asset_id) as dist_asst
 FROM Table
 GROUP BY supplier_id
 HAVING dist_asst > 1
</code>```

2- then doing a join :

```<code>SELECT t1.supplier_id
FROM Table t1
INNER JOIN (SELECT supplier_id, Count(distinct asset_id) as dist_asst
     FROM Table
     GROUP BY supplier_id
     HAVING dist_asst > 1) t2 on t2.supplier_id = t1.supplier_id
</code>```

Body:
I have an array called assetIDs as below

$assetIDs = Collection {#505 ▼
  #items: array:2 [▼
    0 => 4
    1 => 7
  ]
}

and I have the data in the table as below shown

and I'm doing query on the above table using this

$supplier_id = SupplierAsset::whereIn('asset_id',$asset_ids)->pluck('supplier_id');

and result for the above query is below

Collection {#510 ▼
  #items: array:3 [▼
    0 => 1
    1 => 1
    2 => 2
  ]
}

here whereIn is returning all the possible rows which satisfies the condition. Actually I need to get the result as like which supplier_id has both the values of assetIDs array.In my table supplier_id=1 has the both values 4 and 7 Just like below collection.

Collection {#510 ▼
  #items: array:3 [▼
    0 => 1
    1 => 1
  ]
}

Can anybody suggest me the solution for this please?

Body:
Here is the mysql you should do :

1- get all the id who have more than 1 supplier_id :

SELECT supplier_id, Count(distinct asset_id) as dist_asst
 FROM Table
 GROUP BY supplier_id
 HAVING dist_asst > 1

2- then doing a join :

SELECT t1.supplier_id
FROM Table t1
INNER JOIN (SELECT supplier_id, Count(distinct asset_id) as dist_asst
     FROM Table
     GROUP BY supplier_id
     HAVING dist_asst > 1) t2 on t2.supplier_id = t1.supplier_id