问:
Custom Shape in Silverlight (porting app from WPF)
I'm converting a WPF app to Silverlight.

The app includes a class which inherits from Shape. It overrides the DefiningGeometry property to return a Path object. However, the Silverlight Shape class doesn't have a DefiningGeometry property.

Reading on the internet I've found others with this same problem. The solution seems to involve inheriting from Control directly, and setting the Content property to the path. However, I also want to retain my event handlers (MouseEnter, MouseLeave, GotFocus, LostFocus) plus I would like it to keep it's position and resize proportionally to the rest of the application.

I'm mainly a back-end developer, so this isn't my forte - I'd appreciate it if anyone could give me an outline sample of how to achieve this.

答:
You will not be able to produce a class that works in the same way because Silverlight does not support the creation of custom elements that derive from the Shape base class.

The reason it's impossible to create a custom shape in Silveright is that Silverlight does not share WPF's "visual layer". If you want to understand fully why what you're trying is impossible, you need to understand how Silverlight is very different from WPF here. (And if you don't care, skip the next 2 paragraphs.)

In WPF, you can work at two completely different levels: the visual layer, or the framework layer. The visual layer's services are provided by WindowsBase.dll and PresentationCore.dll. This provides basic rendering and input services. But if you want things like styling, data binding, layout, templating and so on, you need the framework services, and these are provided by PresentationFramework.dll. The shape types - Rectangle, Path, and so on - are all framework types - they derive from FrameworkElement and they support data binding, layout, animation and so on. But they are implemented on top of the visual layer - if you look at any of the Shape types in Reflector or ILDASM you'll see they all override the OnRender method, and that's where the code that defines the actual shape lives. (OnRender is a visual layer function.) And because the visual layer is a fully supported and documented API, you're free to write your own shapes in WPF - you can write exactly the same sort of code as you'll find in the built-in shape classes.

Silverlight doesn't make this visual/framework distinction - in Silverlight, WPF's visual layer has essentially collapsed into the framework layer. So if you look at the shape types in Reflector or ILDASM, you'll see that they contain no OnRender method, and they're almost empty. That's because in Silverlight, the shapes are all intrinsics - the plugin has built-in special handling for Ellipse, Path, and all the other shapes. So the set of shapes is not open to extension in Silverilght. There is no OnRender method to override in Silverlight. So you simply cannot write your own custom class that derives from Shape in Silverlight.

So, either a custom Control or a UserControl will be the way to go, I'm afraid. This shouldn't stop the MouseEnter and MouseLeave from working though. Have you actually found that those don't work? Or are you just assuming that they won't work?


来源: stackexchange

问:
Pushing an object with unique_ptr into vector in C++
I have a simple class structure modelling a discrete simulation, with a vector of States, which each contain a number of Transitions, held as a vector of smart pointers. I've used smart pointers to hold the transitions as in my full application I need polymorphism.

```<code>#include <vector>
#include <memory>

class Transition {
    public:
        Transition() {}
};

class State {
    public:
        State(int num) : num(num), transitions() {}
        void add_transition(std::unique_ptr<Transition> trans) {
            transitions.push_back(std::move(trans));
        }

    private:
        int num;
        std::vector<std::unique_ptr<Transition>> transitions;
};

int main() {
    std::vector<State> states;
    for (int i = 0; i < 10; i++) {
        State nstate = State(i);
        for (int j = 0; j < 2; j++) {
            nstate.add_transition(std::move(std::unique_ptr<Transition>(new Transition())));
        }
        // This line causes compiler errors
        states.push_back(nstate);
    }
}
</code>```

I get compiler errors when adding the new state object to the vector:

```<code>Error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Transition; _Dp = std::default_delete<Transition>]’
 { ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
</code>```

I imagine this is due to vector making a copy of the State object which is also trying to make a copy of the vector of unique_ptrs which isn't allowed. I've seen that emplace_back doesn't make copies like push_back does but I still get the same error.

Adding the State object directly into the vector works, but I'd prefer to avoid this workaround as in my actual code I do more work with the State object rather than just adding transitions and don't want to keep accessing the vector.

```<code>int main() {
    std::vector<State> states;
    for (int i = 0; i < 10; i++) {
        states.push_back(State(i));
        for (int j = 0; j < 2; j++) {
            states[i].add_transition(std::move(std::unique_ptr<Transition>(new Transition())));
        }
    }
}
</code>```

答:
You need to implement a move constructor for your State and call std::move to move the object

```<code>class State {
public:
    // default if you just want it to move the members one by one
    State(State&& s) = default;
};

states.push_back(std::move(nstate));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a simple class structure modelling a discrete simulation, with a vector of States, which each contain a number of Transitions, held as a vector of smart pointers. I've used smart pointers to hold the transitions as in my full application I need polymorphism.

#include <vector>
#include <memory>

class Transition {
    public:
        Transition() {}
};

class State {
    public:
        State(int num) : num(num), transitions() {}
        void add_transition(std::unique_ptr<Transition> trans) {
            transitions.push_back(std::move(trans));
        }

    private:
        int num;
        std::vector<std::unique_ptr<Transition>> transitions;
};

int main() {
    std::vector<State> states;
    for (int i = 0; i < 10; i++) {
        State nstate = State(i);
        for (int j = 0; j < 2; j++) {
            nstate.add_transition(std::move(std::unique_ptr<Transition>(new Transition())));
        }
        // This line causes compiler errors
        states.push_back(nstate);
    }
}

I get compiler errors when adding the new state object to the vector:

Error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Transition; _Dp = std::default_delete<Transition>]’
 { ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }

I imagine this is due to vector making a copy of the State object which is also trying to make a copy of the vector of unique_ptrs which isn't allowed. I've seen that emplace_back doesn't make copies like push_back does but I still get the same error.

Adding the State object directly into the vector works, but I'd prefer to avoid this workaround as in my actual code I do more work with the State object rather than just adding transitions and don't want to keep accessing the vector.

int main() {
    std::vector<State> states;
    for (int i = 0; i < 10; i++) {
        states.push_back(State(i));
        for (int j = 0; j < 2; j++) {
            states[i].add_transition(std::move(std::unique_ptr<Transition>(new Transition())));
        }
    }
}

Body:
You need to implement a move constructor for your State and call std::move to move the object

class State {
public:
    // default if you just want it to move the members one by one
    State(State&& s) = default;
};

states.push_back(std::move(nstate));


问:
Copy Excel cell formats to range very slow
I use the following code to copy one Excel row format (template row) to a range of rows filled with data, but it gets incredibly slow with more rows (current test with about 33000 lines as target range).

The line slowing down the whole process is Range.PasteSpecial(...);, without the line it would take a few seconds, with it it takes minutes.

```<code>range = worksheet.Range[worksheet.Cells[9, 1], worksheet.Cells[9, 44]];
range.Copy();
range = worksheet.Range[worksheet.Cells[10, 1], worksheet.Cells[iRow + 8, 44]];
range.PasteSpecial(XlPasteType.xlPasteFormats, XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false);
excel.CutCopyMode = 0;
</code>```

Is there a different approach to retreive a range format and set it to another range, possibly faster (also within seconds)?

答: Interop is inherently slow because of the multiple layers, but the trick with speeding up Format operations is to do them in as large a block as possible - do the format copy once and then apply it using PasteSpecial to as large a range of cells as possible.</p>

Body:
I use the following code to copy one Excel row format (template row) to a range of rows filled with data, but it gets incredibly slow with more rows (current test with about 33000 lines as target range).

The line slowing down the whole process is Range.PasteSpecial(...);, without the line it would take a few seconds, with it it takes minutes.

range = worksheet.Range[worksheet.Cells[9, 1], worksheet.Cells[9, 44]];
range.Copy();
range = worksheet.Range[worksheet.Cells[10, 1], worksheet.Cells[iRow + 8, 44]];
range.PasteSpecial(XlPasteType.xlPasteFormats, XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false);
excel.CutCopyMode = 0;

Is there a different approach to retreive a range format and set it to another range, possibly faster (also within seconds)?


问:
How to explain the reverse of a sequence by slice notation a[::-1]
From the python.org tutorial

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

```<code>>>> a = "hello"
>>> print(a[::-1])
olleh
</code>```

As the tutorial says a[::-1] should equals to a[0:5:-1]

but a[0:5:-1] is empty as follows:

```<code>>>> print(len(a[0:5:-1]))
0
</code>```

The question is not a duplicate of explain-slice-notation. That question is about the general use of slicing in python.

答:
You are confused with the behavior of the stepping. To get the same result, what you can do is:

```<code>a[0:5][::-1]
'olleh'
</code>```

Indeed, stepping wants to 'circle' around backwards in your case, but you are limiting it's movement by calling a[0:5:-1].

Body:
From the python.org tutorial

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

>>> a = "hello"
>>> print(a[::-1])
olleh

As the tutorial says a[::-1] should equals to a[0:5:-1]

but a[0:5:-1] is empty as follows:

>>> print(len(a[0:5:-1]))
0

The question is not a duplicate of explain-slice-notation. That question is about the general use of slicing in python.

Body:
You are confused with the behavior of the stepping. To get the same result, what you can do is:

a[0:5][::-1]
'olleh'

Indeed, stepping wants to 'circle' around backwards in your case, but you are limiting it's movement by calling a[0:5:-1].


问:
Determine the fastest unsigned integer type for basic arithmetic calculations
I'm writing some code for calculating with arbitrarily large unsigned integers. This is just for fun and training, otherwise I'd use libgmp. My representation uses an array of unsigned integers and for chosing the "base type", I use a typedef:

```<code>#include <limits.h>
#include <stdint.h>

typedef unsigned int hugeint_Uint;

typedef struct hugeint hugeint;

#define HUGEINT_ELEMENT_BITS (CHAR_BIT * sizeof(hugeint_Uint))
#define HUGEINT_INITIAL_ELEMENTS (256 / HUGEINT_ELEMENT_BITS)

struct hugeint
{
    size_t s;         // <- maximum number of elements
    size_t n;         // <- number of significant elements
    hugeint_Uint e[]; // <- elements of the number starting with least significant
};
</code>```

The code is working fine, so I only show the part relevant to my question here.

I would like to pick a better "base type" than unsigned int, so the calculations are the fastest possible on the target system (e.g. a 64bit type when targeting x86_64, a 32bit type when targeting i686, an 8bit type when targeting avr_attiny, ...)

I thought that uint_fast8_t should do what I want. But I found out it doesn't, see e.g. here the relevant part of stdint.h from MinGW:

```<code>/*  7.18.1.3  Fastest minimum-width integer types
 *  Not actually guaranteed to be fastest for all purposes
 *  Here we use the exact-width types for 8 and 16-bit ints.
 */
typedef signed char int_fast8_t;
typedef unsigned char uint_fast8_t;
</code>```

The comment is interesting: for which purpose would an unsigned char be faster than an unsigned int on win32? Well, the important thing is: uint_fast8_t will not do what I want.

So is there some good and portable way to find the fastest unsigned integer type?

答:
It's a good idea to start your code with the largest integer type the platform has, uintmax_t. As has already been pointed out, this is not necessarily, but rather most probably the fastest. I'd rather say there are exceptions where this is not the case, but as a default, it is probably your best bet.

Be very careful to build the size granularity into expressions that the compiler can resolve at compile type, rather than runtime for speed.

It is most probably a good idea to define the base type as something like

```<code>#define LGINT_BASETYPE uintmax_t
#define LGINT_GRANUL   sizeof(LGINT_BASETYPE)
</code>```

This will allow you to change the base type in one single place and adapt to different platforms quickly. That results in code that is easily moved to a new platform, but still can be adapted to the exception cases where the largest int type is not the most performant one (after you have proven that by measurement)

As always, it does not make a lot of sense to think about optimal performance when designing your code - Start with a reasonable balance of "designed for optimization" and "design for maintainability" - You might easily find out that the choice of base type is not really the most CPU-eating part of your code. In my experience, I was nearly always in for some surprises when comparing my guesses on where CPU is spent to my measurements. Don't fall into the premature optimization trap.

Body:
I'm writing some code for calculating with arbitrarily large unsigned integers. This is just for fun and training, otherwise I'd use libgmp. My representation uses an array of unsigned integers and for chosing the "base type", I use a typedef:

#include <limits.h>
#include <stdint.h>

typedef unsigned int hugeint_Uint;

typedef struct hugeint hugeint;

#define HUGEINT_ELEMENT_BITS (CHAR_BIT * sizeof(hugeint_Uint))
#define HUGEINT_INITIAL_ELEMENTS (256 / HUGEINT_ELEMENT_BITS)

struct hugeint
{
    size_t s;         // <- maximum number of elements
    size_t n;         // <- number of significant elements
    hugeint_Uint e[]; // <- elements of the number starting with least significant
};

The code is working fine, so I only show the part relevant to my question here.

I would like to pick a better "base type" than unsigned int, so the calculations are the fastest possible on the target system (e.g. a 64bit type when targeting x86_64, a 32bit type when targeting i686, an 8bit type when targeting avr_attiny, ...)

I thought that uint_fast8_t should do what I want. But I found out it doesn't, see e.g. here the relevant part of stdint.h from MinGW:

/*  7.18.1.3  Fastest minimum-width integer types
 *  Not actually guaranteed to be fastest for all purposes
 *  Here we use the exact-width types for 8 and 16-bit ints.
 */
typedef signed char int_fast8_t;
typedef unsigned char uint_fast8_t;

The comment is interesting: for which purpose would an unsigned char be faster than an unsigned int on win32? Well, the important thing is: uint_fast8_t will not do what I want.

So is there some good and portable way to find the fastest unsigned integer type?

Body:
It's a good idea to start your code with the largest integer type the platform has, uintmax_t. As has already been pointed out, this is not necessarily, but rather most probably the fastest. I'd rather say there are exceptions where this is not the case, but as a default, it is probably your best bet.

Be very careful to build the size granularity into expressions that the compiler can resolve at compile type, rather than runtime for speed.

It is most probably a good idea to define the base type as something like

#define LGINT_BASETYPE uintmax_t
#define LGINT_GRANUL   sizeof(LGINT_BASETYPE)

This will allow you to change the base type in one single place and adapt to different platforms quickly. That results in code that is easily moved to a new platform, but still can be adapted to the exception cases where the largest int type is not the most performant one (after you have proven that by measurement)

As always, it does not make a lot of sense to think about optimal performance when designing your code - Start with a reasonable balance of "designed for optimization" and "design for maintainability" - You might easily find out that the choice of base type is not really the most CPU-eating part of your code. In my experience, I was nearly always in for some surprises when comparing my guesses on where CPU is spent to my measurements. Don't fall into the premature optimization trap.


问:
onchange dropdown show checkbox is checked in php
code:

```<code><script>
  $(document).ready(function(){
    $(".menu").click(function(){
      ids = $('.menu:checked').map(function() {
              return this.id;
              }).get().join(',');
              console.log(ids);
        $("#ids").val(ids);
    });
  });
</script>

<?php
if(isset($_POST['submit']))
{
  $adminid = $_POST['admin'];
  $menuids = explode(",", $_POST['ids']);
    foreach ($menuids as $idd)
    {
      $sql = "update menu set admin_id = concat(admin_id,'$adminid',',') where id = '$idd'";
      $result = mysqli_query($link,$sql);
    }
    if($result == true)
      {
        $msg .= "<p style='color:green'>successfull</p>";
      }
      else
      {
        $msg .= "<p style='color:red'>error!</p>";
      }
}
?>

<form method="post">
  <select name="admin" id="admin">
    <option value="">---Select Admin---</option>
    <?php
      $sql = "select * from admin";
      $result = mysqli_query($link,$sql);
      while ($row = mysqli_fetch_array($result))
      {
    ?>
     <option value="<?php echo $row['id']; ?>"><?php echo $row['firstname']?></option>
    <?php
      }
    ?>
  </select>
  <table>
    <tr>
      <th>Share</th>
      <th>Menu Name</th>
    </tr>
    <?php
      $query = "select * from menu";
      $results = mysqli_query($link,$query);
      while ($fetch = mysqli_fetch_array($results))
      {
    ?>
        <tr>
          <td>
            <input type="checkbox" class="menu" id="<?php echo $fetch['id']; ?>" name="menuid" />
          </td>

          <td>
            <?php echo $fetch['menu_name']; ?>
          </td>
        </tr>
    <?php
      }
    ?>
  </table>
  <input type="text" name="ids" id="ids" value=""/>
  <input type="submit" name="submit" id="submit" />
</form>
</code>```

In this code I am update a table having name menu in database. Now, I want to check only those checkbox where admin_id like ,1, or ,2, which is update by query. How can I fix this issue ?please please help.

Thank You

答:
```<code>   while ($fetch = mysqli_fetch_array($results))
  {
   ?>
    <tr>
      <td>
        <input type="checkbox" class="menu" value="<?php if($fetch['id']==1 or
           $fetch['id']==2 ) { echo "checked";} else{} ?>" name="menuid" />
      </td>

      <td>
        <?php echo $fetch['menu_name']; ?>
      </td>
    </tr>
<?php
  }
?>
</code>```

Body:
code:

<?php
if(isset($_POST['submit']))
{
  $adminid = $_POST['admin'];
  $menuids = explode(",", $_POST['ids']);
    foreach ($menuids as $idd)
    {
      $sql = "update menu set admin_id = concat(admin_id,'$adminid',',') where id = '$idd'";
      $result = mysqli_query($link,$sql);
    }
    if($result == true)
      {
        $msg .= "
successfull
";
      }
      else
      {
        $msg .= "
error!
";
      }
}
?>

<form method="post">
  <select name="admin" id="admin">
    <option value="">---Select Admin---</option>
    <?php
      $sql = "select * from admin";
      $result = mysqli_query($link,$sql);
      while ($row = mysqli_fetch_array($result))
      {
    ?>
     <option value="<?php echo $row['id']; ?>"><?php echo $row['firstname']?></option>
    <?php
      }
    ?>
  </select>

      Share
      Menu Name

    <?php
      $query = "select * from menu";
      $results = mysqli_query($link,$query);
      while ($fetch = mysqli_fetch_array($results))
      {
    ?>

            <input type="checkbox" class="menu" id="<?php echo $fetch['id']; ?>" name="menuid" />

            <?php echo $fetch['menu_name']; ?>

    <?php
      }
    ?>

  <input type="text" name="ids" id="ids" value=""/>
  <input type="submit" name="submit" id="submit" />
</form>

In this code I am update a table having name menu in database. Now, I want to check only those checkbox where admin_id like ,1, or ,2, which is update by query. How can I fix this issue ?please please help.

Thank You


问:
add sender's name in the from field of the email in python
I am trying to send email with below code.

```<code>import smtplib
from email.mime.text import MIMEText

sender = 'sender@sender.com'

def mail_me(cont, receiver):
    msg = MIMEText(cont, 'html')
    recipients = ",".join(receiver)
    msg['Subject'] = 'Test-email'
    msg['From'] = "XYZ ABC"
    msg['To'] = recipients
    # Send the message via our own SMTP server.
    try:
        s = smtplib.SMTP('localhost')
        s.sendmail(sender, receiver, msg.as_string())
        print "Successfully sent email"
    except SMTPException:
        print "Error: unable to send email"
    finally:
        s.quit()

cont = """\
   <html>
     <head></head>
     <body>
       <p>Hi!<br>
          How are you?<br>
          Here is the <a href="http://www.google.com">link</a> you wanted.
       </p>
     </body>
   </html>
   """
mail_me(cont,['xyz@xyzcom'])
</code>```

I want "XYZ ABC" to appear as the sender's name when the email is received and its email address as 'sender@sender.com'. but when i receive email i am receiving weird details in "from" fields of the email message.

```<code>[![from:    XYZ@<machine-hostname-appearing-here>
reply-to:   XYZ@<machine-hostname-appearing-here>,
ABC@<machine-hostname-appearing-here>][1]][1]
</code>```

I have attached a screenshot of the email that i receive.

how can i fix this according to my need.

答:
```<code>import smtplib
from email.mime.text import MIMEText

def send_email(to=['example@example.com'], f_host='example.example.com', f_port=587, f_user='example@example.com', f_passwd='example-pass', subject='default subject', message='content message'):
    smtpserver = smtplib.SMTP(f_host, f_port)
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.ehlo
    smtpserver.login(f_user, f_passwd) # from email credential
    msg = MIMEText(message, 'html')
    msg['Subject'] = 'My custom Subject'
    msg['From'] = "Admin"
    msg['To'] = ','.join(to)
    for t in to:
        smtpserver.sendmail(f_user, t, msg.as_string())  # you just need to add this in for loop in your code.
        smtpserver.close()
    print('Mail is sent successfully!!')

cont = """\
   <html>
     <head></head>
     <body>
       <p>Hi!<br>
          How are you?<br>
          Here is the <a href="http://www.google.com">link</a> you wanted.
       </p>
     </body>
   </html>
   """
try:
    send_email(message=cont)
except:
    print('Mail could not be sent')
</code>```

above method I have tried to send mail which is worked for me even I am able to send mail to my gmail account(in spam folder).
Let me know if you face any other related problem.

Body:
I am trying to send email with below code.

import smtplib
from email.mime.text import MIMEText

sender = 'sender@sender.com'

def mail_me(cont, receiver):
    msg = MIMEText(cont, 'html')
    recipients = ",".join(receiver)
    msg['Subject'] = 'Test-email'
    msg['From'] = "XYZ ABC"
    msg['To'] = recipients
    # Send the message via our own SMTP server.
    try:
        s = smtplib.SMTP('localhost')
        s.sendmail(sender, receiver, msg.as_string())
        print "Successfully sent email"
    except SMTPException:
        print "Error: unable to send email"
    finally:
        s.quit()

cont = """\

Hi!

          How are you?

          Here is the link you wanted.

   """
mail_me(cont,['xyz@xyzcom'])

I want "XYZ ABC" to appear as the sender's name when the email is received and its email address as 'sender@sender.com'. but when i receive email i am receiving weird details in "from" fields of the email message.

[![from:    XYZ@<machine-hostname-appearing-here>
reply-to:   XYZ@<machine-hostname-appearing-here>,
ABC@<machine-hostname-appearing-here>][1]][1]

I have attached a screenshot of the email that i receive.

how can i fix this according to my need.

Body:
import smtplib
from email.mime.text import MIMEText

def send_email(to=['example@example.com'], f_host='example.example.com', f_port=587, f_user='example@example.com', f_passwd='example-pass', subject='default subject', message='content message'):
    smtpserver = smtplib.SMTP(f_host, f_port)
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.ehlo
    smtpserver.login(f_user, f_passwd) # from email credential
    msg = MIMEText(message, 'html')
    msg['Subject'] = 'My custom Subject'
    msg['From'] = "Admin"
    msg['To'] = ','.join(to)
    for t in to:
        smtpserver.sendmail(f_user, t, msg.as_string())  # you just need to add this in for loop in your code.
        smtpserver.close()
    print('Mail is sent successfully!!')

cont = """\
   <html>
     <head></head>
     <body>
       <p>Hi!<br>
          How are you?<br>
          Here is the <a href="http://www.google.com">link</a> you wanted.
       </p>
     </body>
   </html>
   """
try:
    send_email(message=cont)
except:
    print('Mail could not be sent')

above method I have tried to send mail which is worked for me even I am able to send mail to my gmail account(in spam folder).
Let me know if you face any other related problem.


问:
Append HTML data jQuery
This time I wrote html in controller when I check a checkbox I get data in console but I want to get it in the form.

I have checkbox in foreach loop

```<code><input type='checkbox' value='{$student['id']}' name='student_ids[]' id='chkbx' required> {$student['name']}
</code>```

when click on checkboxes data load accordingly

its my html

```<code>    $str .= '<div class="form-group">
    <label class="control-label col-md-3">
    Student
    </label>
    <div class="col-md-4">
        <select id="students-clicked" class="form-control select2-multiple" multiple name="students[]">
            <option value=""></option>';
            foreach ($students as $students) {
                $str .= "<option value='{$student->id}'>{$student->name}</option>";
            }

$str .=         '</select>
    </div>
</div>';
</code>```

Jquery Method is as

```<code>    $('body').on('click', "#chkbx", function() {
    var class = $('input:checkbox:checked').map(function() {
        return this.value;
    }).get();
    $.ajax({
            url: '/trigger/studentsData',
            type: 'POST',
            data: {'trigger_type': 'click' , ids: class},
            success: function(result) {

            }
        });
});
</code>```

Except jQuery everything is written in controller this time I am getting HTML data in console how can I append it in my html form it should also update according to checkbox selection

答:
Try this :-

```<code><input type='checkbox' value='{$student['id']}' name='student_ids[]' id='chkbx' required/> {$student['name']}
<div id="appendata">
 //your ajax data
</div>
</code>```

Now in Success Function

```<code>success: function(result) {
    $("#appendata").html(result); // this will replace when you select the checkbox
         or
    $("#appendata").append(result); // this will append when you select again from checkbox
}
</code>```

Hope it helps

Title: Append HTML data jQuery

Body:
This time I wrote html in controller when I check a checkbox I get data in console but I want to get it in the form.

I have checkbox in foreach loop

<input type='checkbox' value='{$student['id']}' name='student_ids[]' id='chkbx' required> {$student['name']}

when click on checkboxes data load accordingly

its my html

    $str .= '

    Student

        <select id="students-clicked" class="form-control select2-multiple" multiple name="students[]">
            <option value=""></option>';
            foreach ($students as $students) {
                $str .= "<option value='{$student->id}'>{$student->name}</option>";
            }

$str .=         '</select>

';

Jquery Method is as

    $('body').on('click', "#chkbx", function() {
    var class = $('input:checkbox:checked').map(function() {
        return this.value;
    }).get();
    $.ajax({
            url: '/trigger/studentsData',
            type: 'POST',
            data: {'trigger_type': 'click' , ids: class},
            success: function(result) {

            }
        });
});

Except jQuery everything is written in controller this time I am getting HTML data in console how can I append it in my html form it should also update according to checkbox selection

Body:
Try this :-

<input type='checkbox' value='{$student['id']}' name='student_ids[]' id='chkbx' required/> {$student['name']}
<div id="appendata">
 //your ajax data
</div>

Now in Success Function

success: function(result) {
    $("#appendata").html(result); // this will replace when you select the checkbox
         or
    $("#appendata").append(result); // this will append when you select again from checkbox
}

Hope it helps


问:
"No space left on device" error when compiling
In Xcode, when I tried to run my app on my device (iPhone), I get "no space left on device". The app was working on iPhone yesterday, but today I got this error.

Anyone know how to fix this problem?

答: Maybe need to check storage on your Mac. I have the same problem with Xcode8.3.2 with 2Gb available of SSD on MacBook, after delete somethings then it worked.

ContentLicense: CC BY-SA 4.0


问:
Running Struts 1 & Struts 2
I'm trying to get an application running using both Struts1 and Struts2. Reason being it's being migrated but there is a lot of Struts1 which we want to do bit by bit not big bang... I know this can be done

Anyhow I cannot get my S2 filter to pick up my URL and no errors are being given when I access a *.action URL ! All S1 pages still work fine. My web XML contains the S2 config...

```<code><filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>*.action</url-pattern>
</filter-mapping>
</code>```

and the S1 servlet

```<code><servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <load-on-startup>2</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>
</code>```

I've also set up a simple TestStruts2Action class extending Action that literally just had a syso in it to prove it reached the action. XMLconfig'

```<code>  <package name="main" extends="struts-default">
      <action name="testStruts2" class="com.myclass.TestStruts2Action">
         <result name="success">test/testStruts2.jsp</result>
      </action>
  </package>
</code>```

All I get is the applications 404 page when hitting the URL /MyApp/testStruts2.action

My JSP is literally just a HelloWorld example and held under test/testStruts2.jsp

Any ideas ? With no errors during start or logged when I hit the URLs I'm at a loss as to what to try next...

Attempted adding namespaces

答:
Ok figured what I was doing wrong...

My struts.xml file was placed alongside the old struts-config file in WEB-INF and the new filter was not reading it. I used this post to figure that one out and amended my declaration of my filter in web.xml too

```<code><filter>
  <filter-name>struts2</filter-name>
  <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
  <init-param>
    <param-name>config</param-name>
    <param-value>struts-default.xml,struts-plugin.xml,struts.xml</param-value>
  </init-param>
</code>```

However this took my attention

@AleksandrM

'Also the order in which you define xml files is important as well. E.g. You cannot extend struts-default package (from struts-default.xml) in your struts.xml if it isn't loaded yet.'

@AleksandrM Do you mean if you move the struts.xml location you can't extend the struts-default within the package declarations ??

Title: Running Struts 1 & Struts 2

Body:
I'm trying to get an application running using both Struts1 and Struts2. Reason being it's being migrated but there is a lot of Struts1 which we want to do bit by bit not big bang... I know this can be done

Anyhow I cannot get my S2 filter to pick up my URL and no errors are being given when I access a *.action URL ! All S1 pages still work fine. My web XML contains the S2 config...

<filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>*.action</url-pattern>
</filter-mapping>

and the S1 servlet

<servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <load-on-startup>2</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>

I've also set up a simple TestStruts2Action class extending Action that literally just had a syso in it to prove it reached the action. XMLconfig'

  <package name="main" extends="struts-default">
      <action name="testStruts2" class="com.myclass.TestStruts2Action">
         <result name="success">test/testStruts2.jsp</result>
      </action>
  </package>

All I get is the applications 404 page when hitting the URL /MyApp/testStruts2.action

My JSP is literally just a HelloWorld example and held under test/testStruts2.jsp

Any ideas ? With no errors during start or logged when I hit the URLs I'm at a loss as to what to try next...

Attempted adding namespaces

Body:
Ok figured what I was doing wrong...

My struts.xml file was placed alongside the old struts-config file in WEB-INF and the new filter was not reading it. I used this post to figure that one out and amended my declaration of my filter in web.xml too

<filter>
  <filter-name>struts2</filter-name>
  <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
  <init-param>
    <param-name>config</param-name>
    <param-value>struts-default.xml,struts-plugin.xml,struts.xml</param-value>
  </init-param>

However this took my attention

@AleksandrM

'Also the order in which you define xml files is important as well. E.g. You cannot extend struts-default package (from struts-default.xml) in your struts.xml if it isn't loaded yet.'

@AleksandrM Do you mean if you move the struts.xml location you can't extend the struts-default within the package declarations ??


问:
Make a global dict object in python which can access and edit from any py files
I want keep some global data which can access and edit from any python files. I tried with python classes but it is not working across the files the code is given below.(Note :I am not interested to do any file operations)</p>

```<code>class Settings(object):
    """docstring for Settings"""
    device = None
    def __init__(self, *args, **kwargs):
        if Settings.device is None:
            Settings.device = DeviceSettings()

class DeviceSettings(object):
    def __init__(self, *args, **kwargs):
        self.mode = None
        self.ops = []
        self.phyops = None

Settings()
Settings.device
</code>```

答:
You can achieve that by making the class Settings a Singleton
Note that in order to access device you need to do self.device instead of Settings.device

```<code>def singleton(cls):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance

class DeviceSettings(object):
    def __init__(self, *args, **kwargs):
        self.mode = None
        self.ops = []
        self.phyops = None

@singleton
class Settings(object):
    """docstring for Settings"""
    device = None
    def __init__(self, *args, **kwargs):
        if self.device is None:
            self.device = DeviceSettings()

x = Settings()
print x.device

# In an another file y.device will return the last device value.
x.device = "Another device"
y = Settings()
print y.device
</code>```

Body:
I want keep some global data which can access and edit from any python files. I tried with python classes but it is not working across the files the code is given below.(Note :I am not interested to do any file operations)

class Settings(object):
    """docstring for Settings"""
    device = None
    def __init__(self, *args, **kwargs):
        if Settings.device is None:
            Settings.device = DeviceSettings()

class DeviceSettings(object):
    def __init__(self, *args, **kwargs):
        self.mode = None
        self.ops = []
        self.phyops = None

Settings()
Settings.device

Body:
You can achieve that by making the class Settings a Singleton
Note that in order to access device you need to do self.device instead of Settings.device

def singleton(cls):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance

class DeviceSettings(object):
    def __init__(self, *args, **kwargs):
        self.mode = None
        self.ops = []
        self.phyops = None

@singleton
class Settings(object):
    """docstring for Settings"""
    device = None
    def __init__(self, *args, **kwargs):
        if self.device is None:
            self.device = DeviceSettings()

x = Settings()
print x.device

# In an another file y.device will return the last device value.
x.device = "Another device"
y = Settings()
print y.device


问:
Validator.TryValidateObject always returns true
I am writing a simple model validator to check data read from configuration files, I'm using System.ComponentModel.DataAnnotations

When I call

```<code>bool isValid = Validator.TryValidateObject(model, validationContext, results);
</code>```

It always returns true. I've tried [StringLength(5)] and [MaxLength(5)].

答:
Try this:

```<code>bool isValid = Validator.TryValidateObject(model, validationContext, results, true);
</code>```

Note: validateAllProperties = true

Documentation says:

true to validate all properties; if false, only required attributes
  are validated..

Brilliant design.

Body:
I am writing a simple model validator to check data read from configuration files, I'm using System.ComponentModel.DataAnnotations

When I call

bool isValid = Validator.TryValidateObject(model, validationContext, results);

It always returns true. I've tried [StringLength(5)] and [MaxLength(5)].

Body:
Try this:

bool isValid = Validator.TryValidateObject(model, validationContext, results, true);

Note: validateAllProperties = true

Documentation says:

true to validate all properties; if false, only required attributes
  are validated..

Brilliant design.


问:
Is there any method in Kotlin which allow me to translate a value from a range into another range?
I have a value inside a range of numbers (for instance 0..100) which I want to translate it into another range, (for instance to 0..9). So the result would be:

50 -> 4 or 100 -> 9, ...

Is there any method in Kotlin which helps me in this regard?

答:
Calculate the ratio of the number within the original range.
Multiply it by the second range.

```<code>fun convert(number: Int, original: IntRange, target: IntRange): Int {
    val ratio = number.toFloat() / (original.endInclusive - original.start)
    return (ratio * (target.endInclusive - target.start)).toInt()
}
</code>```

As an extension function

```<code>fun IntRange.convert(number: Int, target: IntRange): Int {
    val ratio = number.toFloat() / (endInclusive - start)
    return (ratio * (target.endInclusive - target.start)).toInt()
}

val result =  (0..100).convert(50, 0..9)
</code>```

Body:
Calculate the ratio of the number within the original range.
Multiply it by the second range.

fun convert(number: Int, original: IntRange, target: IntRange): Int {
    val ratio = number.toFloat() / (original.endInclusive - original.start)
    return (ratio * (target.endInclusive - target.start)).toInt()
}

As an extension function

fun IntRange.convert(number: Int, target: IntRange): Int {
    val ratio = number.toFloat() / (endInclusive - start)
    return (ratio * (target.endInclusive - target.start)).toInt()
}

val result =  (0..100).convert(50, 0..9)


问:
htaccess rewrite all with document_general_info in the url
I need to be able to rewrite all urls that have document_general_info in the url.
Example urls would be like:

```<code>www.mysite.com/index.php?main_page=document_general_info&cPath=2371_2377_2407_2606&products_id=27990

www.mysite.com/index.php?main_page=document_general_info&cPath=2371_2373&products_id=23055
</code>```

I need to redirect them to index.php as they are historical links for content that no longer exists and will give me over 3000 404 errors

Thanks

答:
Try this :

```<code>RewriteEngine on

RewriteCond %{THE_REQUEST} \?.*document_general_info [NC]
RewriteRule ^ /index.php? [L,R]
</code>```

Change R to R=301 (Permanent redirect) when you are sure the rule is working ok.

Body:
I need to be able to rewrite all urls that have document_general_info in the url.
Example urls would be like:

www.mysite.com/index.php?main_page=document_general_info&cPath=2371_2377_2407_2606&products_id=27990

www.mysite.com/index.php?main_page=document_general_info&cPath=2371_2373&products_id=23055

I need to redirect them to index.php as they are historical links for content that no longer exists and will give me over 3000 404 errors

Thanks

Body:
Try this :

RewriteEngine on

RewriteCond %{THE_REQUEST} \?.*document_general_info [NC]
RewriteRule ^ /index.php? [L,R]

Change R to R=301 (Permanent redirect) when you are sure the rule is working ok.


问:
How to disable "Save Password" notification in any browser programatically?
I have used multiple permutation and combination to disable Save Password notification in Browser one of them is autocomplete="off". But it doesn't work in my system. Please, suggest me !!! </p>

答:
Unfortunately this is still not possible :(
Users have to manually turn this off...

But you can stop the popup from showing up:
How?
Don't use type="password"

Use

```<code>type="text"
</code>```

Instead

Body:
Unfortunately this is still not possible :(
Users have to manually turn this off...

But you can stop the popup from showing up:
How?
Don't use type="password"

Use

type="text"

Instead


问:
Changing the color of toolbar OnsenUi
I'm using OnsenUi framework for my webapp. and i need to know Is there any way to change the colour of toolbar based on the colour of the page. In other words, like Android 5 toolbar color effect.

If it possible, can you share me a snippet on how to do it?

If it's not, can you tell me where to change the color code manually, so that i can mimic that effect. What i found was, i can change the color of the toolbar in .navigation-bar background color, but it makes the toolbar to display only one color in every page. Can anybody tell me where to modify to get different color for different pages?

Update #1

i tried a simple method

```<code><ons-toolbar style="background-color:#B1797A;>
</code>```

but this breaks my navigation !!

Any help would be appreciated. Thanks guys.

答:
You could try this:

Go to the directory /lib/onsenui/css from the root of your project

Open onsen-css-components.css

Search for the class .toolbar--material

Modify the background-color property of the class to a color of your choice

This method worked for me.

Title: Changing the color of toolbar OnsenUi

Body:
I'm using OnsenUi framework for my webapp. and i need to know Is there any way to change the colour of toolbar based on the colour of the page. In other words, like Android 5 toolbar color effect.

If it possible, can you share me a snippet on how to do it?

If it's not, can you tell me where to change the color code manually, so that i can mimic that effect. What i found was, i can change the color of the toolbar in .navigation-bar background color, but it makes the toolbar to display only one color in every page. Can anybody tell me where to modify to get different color for different pages?

Update #1

i tried a simple method

<ons-toolbar style="background-color:#B1797A;>

but this breaks my navigation !!

Any help would be appreciated. Thanks guys.


问:
Creating a shared library with main()
In glibc (and also EGLIBC I believe), the libc.so library has a main() method:

```<code>$ /lib/i386-linux-gnu/libc.so.6
GNU C Library (Debian GLIBC 2.19-18+deb8u1) stable release version 2.19, by Roland McGrath et al.
Copyright (C) 2014 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.
Compiled by GNU CC version 4.8.4.
Compiled on a Linux 3.16.7 system on 2015-08-30.
Available extensions:
        crypt add-on version 2.1 by Michael Glad and others
        GNU Libidn by Simon Josefsson
        Native POSIX Threads Library by Ulrich Drepper et al
        BIND-8.2.3-T5B
libc ABIs: UNIQUE IFUNC
For bug reporting instructions, please see:
<http://www.debian.org/Bugs/>.
</code>```

Now I want to do the same with the following minimalistic example (i. e. I want my own SO to also have a main()):

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

int main(int argc, char *argv[]) {
        printf("Hello, World!\n");
        return 0;
}
</code>```

Linking as a regular executable:

```<code>$ gcc -g -O0 -Wall -c test.c
$ gcc -o test test.o
$ ./test
Hello, World!
</code>```

Now linking as a shared object:

```<code>$ gcc -g -O0 -Wall -c test.c
$ gcc -shared -o libtest.so test.o
$ ./libtest.so
Segmentation fault
</code>```

nm shows that main symbol is present (000004f5 T main)

When debugging, gdb doesn't show any meaningful backtrace.

Adding -fpic or -fPIC to the gcc command line doesn't help.

What am I doing wrong?

答:
the libc.so library has a main() method

No, the implementation of C library of gcc has an entry point not a main symbol.

You can find an example of how to do this here.

Title: Creating a shared library with main()

Body:
In glibc (and also EGLIBC I believe), the libc.so library has a main() method:

$ /lib/i386-linux-gnu/libc.so.6
GNU C Library (Debian GLIBC 2.19-18+deb8u1) stable release version 2.19, by Roland McGrath et al.
Copyright (C) 2014 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.
Compiled by GNU CC version 4.8.4.
Compiled on a Linux 3.16.7 system on 2015-08-30.
Available extensions:
        crypt add-on version 2.1 by Michael Glad and others
        GNU Libidn by Simon Josefsson
        Native POSIX Threads Library by Ulrich Drepper et al
        BIND-8.2.3-T5B
libc ABIs: UNIQUE IFUNC
For bug reporting instructions, please see:
<http://www.debian.org/Bugs/>.

Now I want to do the same with the following minimalistic example (i. e. I want my own SO to also have a main()):

#include <stdio.h>

int main(int argc, char *argv[]) {
        printf("Hello, World!\n");
        return 0;
}

Linking as a regular executable:

$ gcc -g -O0 -Wall -c test.c
$ gcc -o test test.o
$ ./test
Hello, World!

Now linking as a shared object:

$ gcc -g -O0 -Wall -c test.c
$ gcc -shared -o libtest.so test.o
$ ./libtest.so
Segmentation fault

nm shows that main symbol is present (000004f5 T main)

When debugging, gdb doesn't show any meaningful backtrace.

Adding -fpic or -fPIC to the gcc command line doesn't help.

What am I doing wrong?


问:
Sql server Not listed in PlasticScm Server configuration wizard
I want to use MS Sql Server as my Database backend with PlasticScm.

When I click to configure it , my Database is not listed in backend server.
It just show embedded backend.

I have also checked Sql server is running

I am using Windows Server 2012 R2 and Sql server 2016.

答:
MS SQL Server, Oracle and PostgreSQL are only supported if you are using an Enterprise edition license. If you aren't, those options won't be even listed in the server configurator:
https://www.plasticscm.com/pricing.html</p>


问:
How to use "setPress" a Button from an Activity?
I have a fragment that generates buttons like so:

```<code>public class MyFragment extends Fragment {
    LinearLayout lLayout;
    MyInterface mInterface;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        for (int j = 0; j < 2; j++) {
            final Button btn = new Button(getActivity());
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    tellActivityToPressButton(btn);
                }
            }
            lLayout.addView(btn);
        }
        return lLayout;
    }

    public interface MyInterface {
        void pressButton(Button button);
    }

    @Override
    public void onAttach(Context activity) {
        super.onAttach(activity);

        try {
            mInterface = (MyInterface) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() +
        " must implement MyInterface");
        }
    }

    public void tellActivityToPressButton(Button button) {
        mInterface.pressButton(button);
    }
}
</code>```

And my activity is:

```<code>public class Activity extends AppCompatActivity implements MyFragment.MyInterface {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_activity);
        MyFragment frag = new MyFragment();
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.add(R.id.container, frag);
    }
    public void pressButton(Button button) {
        button.setPressed(true);
    }
}
</code>```

When I attempt to use this code and run it, the buttons that are created do not remain pressed when I click on them. Why is this? I understand that I could just move the setPressed method into the onClick method for the buttons, but I want it so that I call the setPressed method from the activity like above and the button remains pressed. How can I do this? Or is there any other way to keep a button pressed from the Activity?

答:
May be the button is pressed but it just doesnot show up like a "pressed button"
what you can do is add selector to make button look pressed

Put a selector file in your drawable for example

my_button_selector.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/light_orange" android:state_pressed="true"/>
<item android:drawable="@color/orange"/>
</selector>
</code>```

Use your selector like this

```<code><Button
android:id="@+id/btn_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="how_it_works_button_title"
android:background="@drawable/my_button_selector" />
</code>```

Body:
I have a fragment that generates buttons like so:

public class MyFragment extends Fragment {
    LinearLayout lLayout;
    MyInterface mInterface;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        for (int j = 0; j < 2; j++) {
            final Button btn = new Button(getActivity());
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    tellActivityToPressButton(btn);
                }
            }
            lLayout.addView(btn);
        }
        return lLayout;
    }

    public interface MyInterface {
        void pressButton(Button button);
    }

    @Override
    public void onAttach(Context activity) {
        super.onAttach(activity);

        try {
            mInterface = (MyInterface) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() +
        " must implement MyInterface");
        }
    }

    public void tellActivityToPressButton(Button button) {
        mInterface.pressButton(button);
    }
}

And my activity is:

public class Activity extends AppCompatActivity implements MyFragment.MyInterface {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_activity);
        MyFragment frag = new MyFragment();
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.add(R.id.container, frag);
    }
    public void pressButton(Button button) {
        button.setPressed(true);
    }
}

When I attempt to use this code and run it, the buttons that are created do not remain pressed when I click on them. Why is this? I understand that I could just move the setPressed method into the onClick method for the buttons, but I want it so that I call the setPressed method from the activity like above and the button remains pressed. How can I do this? Or is there any other way to keep a button pressed from the Activity?

Body:
May be the button is pressed but it just doesnot show up like a "pressed button"
what you can do is add selector to make button look pressed

Put a selector file in your drawable for example

my_button_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/light_orange" android:state_pressed="true"/>
<item android:drawable="@color/orange"/>
</selector>

Use your selector like this

<Button
android:id="@+id/btn_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="how_it_works_button_title"
android:background="@drawable/my_button_selector" />


问:
Calling a function overloaded in several namespaces from inside one namespace
I have the following code snippet:

```<code>void foo(double a) {}

namespace bar_space
{
  struct Bar {};

  void foo(Bar a) {}
}
</code>```

foo(double) is a general function from a library.
I have my own namespace bar_space with my own struct, Bar. I would like to implement an overloading of foo() for Bar, thus making Bar more similar to the built-in types.

Trouble appears when I attempt to call the original foo(double) from within the namespace:

```<code>namespace bar_space
{
  void baz()
  {
    foo(5.0); // error: conversion from ‘double’ to non-scalar type ‘ssc::bar_space::Bar’ requested
  }
}
</code>```

This fails to compile on gcc on both my Fedora and Mac.

Calling

```<code>foo(5.0)
</code>```

from outside the namespace or using

```<code>namespace bar_space
{
  ::foo(5.0)
}
</code>```

works ok, but this doesnt make my new function quite as nice as I had hoped for (other developers are also working inside bar_space).

Is bar_space hiding the original function? Is there a way to make foo(5.0) callable from within bar_space without explicit scoping (::)? Any help is appreciated.

答:
However, in your sample code you could use something like that</p>

```<code>namespace bar_space
{
    using ::foo;
    void baz()
    {
       Bar bar;
       foo(5.0);
       foo(bar);
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have the following code snippet:

void foo(double a) {}

namespace bar_space
{
  struct Bar {};

  void foo(Bar a) {}
}

foo(double) is a general function from a library.
I have my own namespace bar_space with my own struct, Bar. I would like to implement an overloading of foo() for Bar, thus making Bar more similar to the built-in types.

Trouble appears when I attempt to call the original foo(double) from within the namespace:

namespace bar_space
{
  void baz()
  {
    foo(5.0); // error: conversion from ‘double’ to non-scalar type ‘ssc::bar_space::Bar’ requested
  }
}

This fails to compile on gcc on both my Fedora and Mac.

Calling

foo(5.0)

from outside the namespace or using

namespace bar_space
{
  ::foo(5.0)
}

works ok, but this doesnt make my new function quite as nice as I had hoped for (other developers are also working inside bar_space).

Is bar_space hiding the original function? Is there a way to make foo(5.0) callable from within bar_space without explicit scoping (::)? Any help is appreciated.

Body:
However, in your sample code you could use something like that

namespace bar_space
{
    using ::foo;
    void baz()
    {
       Bar bar;
       foo(5.0);
       foo(bar);
    }
}


问:
Lets Encrypt 403 Error When Installing Certificate
I receive a urllib2.HTTPError: HTTP Error 403: Forbidden error when attempting to install a Lets Encrypt certificate using Certbot. I have been installing certificates using the steps listed in this article for over a year and recently starting running into an issue on many of my servers.

The environment of each of the servers with the issue:

GoDaddy Cloud Server (512MB)

Bitnami Wordpress

Ubuntu 14.04.5 LTS

Python 2.7.6

Here are the outputs when attempting to install a certificate:

```<code>sudo ./certbot-auto certonly --webroot -w /opt/bitnami/apps/wordpress/htdocs/ -d xxxxxxxxxxxxx.com
Bootstrapping dependencies for Debian-based OSes... (you can skip this with --no-bootstrap)
Ign http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty InRelease
Get:1 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates InRelease [65.9 kB]
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports InRelease
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty Release.gpg
Get:2 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/main Sources [399 kB]
28% [2 Sources 63.9 kB/399 kB 16%] [Waiting for headers] [Waiting for headers]
Hit http://security.ubuntu.com trusty-security InRelease
Hit http://ppa.launchpad.net trusty InRelease
Hit http://security.ubuntu.com trusty-security/main Sources
Get:3 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/restricted Sources [6,331 B]
Get:4 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/universe Sources [180 kB]
Hit http://ppa.launchpad.net trusty/main amd64 Packages
Get:5 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/multiverse Sources [7,764 B]
Get:6 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/main amd64 Packages [984 kB]
Hit http://security.ubuntu.com trusty-security/universe Sources
Hit http://ppa.launchpad.net trusty/main i386 Packages
Hit http://ppa.launchpad.net trusty/main Translation-en
Hit http://security.ubuntu.com trusty-security/main amd64 Packages
Hit http://security.ubuntu.com trusty-security/universe amd64 Packages
Hit http://security.ubuntu.com trusty-security/main i386 Packages
Get:7 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/restricted amd64 Packages [17.1 kB]
Hit http://security.ubuntu.com trusty-security/universe i386 Packages
Get:8 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/universe amd64 Packages [408 kB]
Hit http://security.ubuntu.com trusty-security/main Translation-en
Get:9 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/multiverse amd64 Packages [14.3 kB]
Get:10 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/main i386 Packages [941 kB]
Hit http://security.ubuntu.com trusty-security/universe Translation-en
Get:11 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/restricted i386 Packages [16.9 kB]
Get:12 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/universe i386 Packages [408 kB]
Get:13 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/multiverse i386 Packages [14.6 kB]
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/main Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/multiverse Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/restricted Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/universe Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty Release
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/main Sources
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/restricted Sources
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/universe Sources
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/multiverse Sources
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/main amd64 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/restricted amd64 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/universe amd64 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/multiverse amd64 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/main i386 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/restricted i386 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/universe i386 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/multiverse i386 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/main Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/multiverse Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/restricted Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/universe Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/main Sources
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/restricted Sources
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/universe Sources
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/multiverse Sources
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/main amd64 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/restricted amd64 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/universe amd64 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/multiverse amd64 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/main i386 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/restricted i386 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/universe i386 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/multiverse i386 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/main Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/multiverse Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/restricted Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/universe Translation-en
Ign http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/main Translation-en_US
Ign http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/multiverse Translation-en_US
Ign http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/restricted Translation-en_US
Ign http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/universe Translation-en_US
Fetched 3,463 kB in 8s (395 kB/s)
Reading package lists... Done
W: Ignoring Provides line with DepCompareOp for package python-cffi-backend-api-max
W: Ignoring Provides line with DepCompareOp for package python-cffi-backend-api-min
W: Ignoring Provides line with DepCompareOp for package python3-cffi-backend-api-max
W: Ignoring Provides line with DepCompareOp for package python3-cffi-backend-api-min
W: Ignoring Provides line with DepCompareOp for package python-cffi-backend-api-max
W: Ignoring Provides line with DepCompareOp for package python-cffi-backend-api-min
W: Ignoring Provides line with DepCompareOp for package python3-cffi-backend-api-max
W: Ignoring Provides line with DepCompareOp for package python3-cffi-backend-api-min
W: You may want to run apt-get update to correct these problems
Reading package lists... Done
Building dependency tree
Reading state information... Done
gcc is already the newest version.
python is already the newest version.
python-dev is already the newest version.
augeas-lenses is already the newest version.
ca-certificates is already the newest version.
libaugeas0 is already the newest version.
libffi-dev is already the newest version.
libssl-dev is already the newest version.
openssl is already the newest version.
python-virtualenv is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 19 not upgraded.
WARNING: unable to check for updates.
Creating virtual environment...
Running virtualenv with interpreter /usr/bin/python2.7
New python executable in /home/xxxxxxxxxxx/.local/share/letsencrypt/bin/python2.7
Also creating executable in /home/xxxxxxxxxxx/.local/share/letsencrypt/bin/python
Installing setuptools, pip...done.
Installing Python packages...
Traceback (most recent call last):
  File "/tmp/tmp.rG5cNt1Qm0/pipstrap.py", line 146, in <module>
    exit(main())
  File "/tmp/tmp.rG5cNt1Qm0/pipstrap.py", line 130, in main
    for url, digest in PACKAGES]
  File "/tmp/tmp.rG5cNt1Qm0/pipstrap.py", line 112, in hashed_download
    response = opener().open(url)
  File "/usr/lib/python2.7/urllib2.py", line 410, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 523, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 448, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 382, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 531, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden
</code>```

UPDATE

Here is what happens when I try to download the tar files from pypi.python.org

```<code>bitnami@atv-demo:/tmp$ sudo wget https://pypi.python.org/packages/source/p/pip/pip-8.0.3.tar.gz
--2017-06-07 06:58:33--  https://pypi.python.org/packages/source/p/pip/pip-8.0.3.tar.gz
Resolving pypi.python.org (pypi.python.org)... 151.101.32.223, 2a04:4e42:8::223
Connecting to pypi.python.org (pypi.python.org)|151.101.32.223|:443... connected.
HTTP request sent, awaiting response... 403 Forbidden
2017-06-07 06:58:33 ERROR 403: Forbidden.

bitnami@atv-demo:/tmp$ sudo wget https://pypi.python.org/packages/source/s/setuptools/setuptools-20.2.2.tar.gz
--2017-06-07 06:58:41--  https://pypi.python.org/packages/source/s/setuptools/setuptools-20.2.2.tar.gz
Resolving pypi.python.org (pypi.python.org)... 151.101.32.223, 2a04:4e42:8::223
Connecting to pypi.python.org (pypi.python.org)|151.101.32.223|:443... connected.
HTTP request sent, awaiting response... 403 Forbidden
2017-06-07 06:58:41 ERROR 403: Forbidden.

bitnami@atv-demo:/tmp$ sudo wget https://pypi.python.org/packages/source/w/wheel/wheel-0.29.0.tar.gz
--2017-06-07 06:58:48--  https://pypi.python.org/packages/source/w/wheel/wheel-0.29.0.tar.gz
Resolving pypi.python.org (pypi.python.org)... 151.101.32.223, 2a04:4e42:8::223
Connecting to pypi.python.org (pypi.python.org)|151.101.32.223|:443... connected.
HTTP request sent, awaiting response... 403 Forbidden
2017-06-07 06:58:48 ERROR 403: Forbidden.
</code>```

答:
Bitnami developer here.

According to the traceback you shared, the error occurred while trying to download a Python package. The list of URLs that the script tries to download is:

```<code>https://pypi.python.org/packages/source/p/pip/pip-8.0.3.tar.gz
https://pypi.python.org/packages/source/s/setuptools/setuptools-20.2.2.tar.gz
https://pypi.python.org/packages/source/w/wheel/wheel-0.29.0.tar.gz
</code>```

And optionally:

```<code>https://pypi.python.org/packages/source/a/argparse/argparse-1.4.0.tar.gz
</code>```

Taking into account the URLs point to pypi.python.org, this was probably a transient error.

Alternatively, you may try to install Certbot from the official PPA instead of using certbot-auto.

Body:
I receive a urllib2.HTTPError: HTTP Error 403: Forbidden error when attempting to install a Lets Encrypt certificate using Certbot. I have been installing certificates using the steps listed in this article for over a year and recently starting running into an issue on many of my servers.

The environment of each of the servers with the issue:

GoDaddy Cloud Server (512MB)

Bitnami Wordpress

Ubuntu 14.04.5 LTS

Python 2.7.6

Here are the outputs when attempting to install a certificate:

sudo ./certbot-auto certonly --webroot -w /opt/bitnami/apps/wordpress/htdocs/ -d xxxxxxxxxxxxx.com
Bootstrapping dependencies for Debian-based OSes... (you can skip this with --no-bootstrap)
Ign http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty InRelease
Get:1 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates InRelease [65.9 kB]
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports InRelease
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty Release.gpg
Get:2 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/main Sources [399 kB]
28% [2 Sources 63.9 kB/399 kB 16%] [Waiting for headers] [Waiting for headers]
Hit http://security.ubuntu.com trusty-security InRelease
Hit http://ppa.launchpad.net trusty InRelease
Hit http://security.ubuntu.com trusty-security/main Sources
Get:3 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/restricted Sources [6,331 B]
Get:4 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/universe Sources [180 kB]
Hit http://ppa.launchpad.net trusty/main amd64 Packages
Get:5 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/multiverse Sources [7,764 B]
Get:6 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/main amd64 Packages [984 kB]
Hit http://security.ubuntu.com trusty-security/universe Sources
Hit http://ppa.launchpad.net trusty/main i386 Packages
Hit http://ppa.launchpad.net trusty/main Translation-en
Hit http://security.ubuntu.com trusty-security/main amd64 Packages
Hit http://security.ubuntu.com trusty-security/universe amd64 Packages
Hit http://security.ubuntu.com trusty-security/main i386 Packages
Get:7 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/restricted amd64 Packages [17.1 kB]
Hit http://security.ubuntu.com trusty-security/universe i386 Packages
Get:8 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/universe amd64 Packages [408 kB]
Hit http://security.ubuntu.com trusty-security/main Translation-en
Get:9 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/multiverse amd64 Packages [14.3 kB]
Get:10 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/main i386 Packages [941 kB]
Hit http://security.ubuntu.com trusty-security/universe Translation-en
Get:11 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/restricted i386 Packages [16.9 kB]
Get:12 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/universe i386 Packages [408 kB]
Get:13 http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/multiverse i386 Packages [14.6 kB]
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/main Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/multiverse Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/restricted Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-updates/universe Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty Release
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/main Sources
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/restricted Sources
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/universe Sources
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/multiverse Sources
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/main amd64 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/restricted amd64 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/universe amd64 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/multiverse amd64 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/main i386 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/restricted i386 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/universe i386 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/multiverse i386 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/main Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/multiverse Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/restricted Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty-backports/universe Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/main Sources
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/restricted Sources
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/universe Sources
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/multiverse Sources
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/main amd64 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/restricted amd64 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/universe amd64 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/multiverse amd64 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/main i386 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/restricted i386 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/universe i386 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/multiverse i386 Packages
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/main Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/multiverse Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/restricted Translation-en
Hit http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/universe Translation-en
Ign http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/main Translation-en_US
Ign http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/multiverse Translation-en_US
Ign http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/restricted Translation-en_US
Ign http://iad-public-cmh-zone-1.clouds.archive.ubuntu.com trusty/universe Translation-en_US
Fetched 3,463 kB in 8s (395 kB/s)
Reading package lists... Done
W: Ignoring Provides line with DepCompareOp for package python-cffi-backend-api-max
W: Ignoring Provides line with DepCompareOp for package python-cffi-backend-api-min
W: Ignoring Provides line with DepCompareOp for package python3-cffi-backend-api-max
W: Ignoring Provides line with DepCompareOp for package python3-cffi-backend-api-min
W: Ignoring Provides line with DepCompareOp for package python-cffi-backend-api-max
W: Ignoring Provides line with DepCompareOp for package python-cffi-backend-api-min
W: Ignoring Provides line with DepCompareOp for package python3-cffi-backend-api-max
W: Ignoring Provides line with DepCompareOp for package python3-cffi-backend-api-min
W: You may want to run apt-get update to correct these problems
Reading package lists... Done
Building dependency tree
Reading state information... Done
gcc is already the newest version.
python is already the newest version.
python-dev is already the newest version.
augeas-lenses is already the newest version.
ca-certificates is already the newest version.
libaugeas0 is already the newest version.
libffi-dev is already the newest version.
libssl-dev is already the newest version.
openssl is already the newest version.
python-virtualenv is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 19 not upgraded.
WARNING: unable to check for updates.
Creating virtual environment...
Running virtualenv with interpreter /usr/bin/python2.7
New python executable in /home/xxxxxxxxxxx/.local/share/letsencrypt/bin/python2.7
Also creating executable in /home/xxxxxxxxxxx/.local/share/letsencrypt/bin/python
Installing setuptools, pip...done.
Installing Python packages...
Traceback (most recent call last):
  File "/tmp/tmp.rG5cNt1Qm0/pipstrap.py", line 146, in <module>
    exit(main())
  File "/tmp/tmp.rG5cNt1Qm0/pipstrap.py", line 130, in main
    for url, digest in PACKAGES]
  File "/tmp/tmp.rG5cNt1Qm0/pipstrap.py", line 112, in hashed_download
    response = opener().open(url)
  File "/usr/lib/python2.7/urllib2.py", line 410, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 523, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 448, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 382, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 531, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden

UPDATE

Here is what happens when I try to download the tar files from pypi.python.org

bitnami@atv-demo:/tmp$ sudo wget https://pypi.python.org/packages/source/p/pip/pip-8.0.3.tar.gz
--2017-06-07 06:58:33--  https://pypi.python.org/packages/source/p/pip/pip-8.0.3.tar.gz
Resolving pypi.python.org (pypi.python.org)... 151.101.32.223, 2a04:4e42:8::223
Connecting to pypi.python.org (pypi.python.org)|151.101.32.223|:443... connected.
HTTP request sent, awaiting response... 403 Forbidden
2017-06-07 06:58:33 ERROR 403: Forbidden.

bitnami@atv-demo:/tmp$ sudo wget https://pypi.python.org/packages/source/s/setuptools/setuptools-20.2.2.tar.gz
--2017-06-07 06:58:41--  https://pypi.python.org/packages/source/s/setuptools/setuptools-20.2.2.tar.gz
Resolving pypi.python.org (pypi.python.org)... 151.101.32.223, 2a04:4e42:8::223
Connecting to pypi.python.org (pypi.python.org)|151.101.32.223|:443... connected.
HTTP request sent, awaiting response... 403 Forbidden
2017-06-07 06:58:41 ERROR 403: Forbidden.

bitnami@atv-demo:/tmp$ sudo wget https://pypi.python.org/packages/source/w/wheel/wheel-0.29.0.tar.gz
--2017-06-07 06:58:48--  https://pypi.python.org/packages/source/w/wheel/wheel-0.29.0.tar.gz
Resolving pypi.python.org (pypi.python.org)... 151.101.32.223, 2a04:4e42:8::223
Connecting to pypi.python.org (pypi.python.org)|151.101.32.223|:443... connected.
HTTP request sent, awaiting response... 403 Forbidden
2017-06-07 06:58:48 ERROR 403: Forbidden.

Body:
Bitnami developer here.

According to the traceback you shared, the error occurred while trying to download a Python package. The list of URLs that the script tries to download is:

https://pypi.python.org/packages/source/p/pip/pip-8.0.3.tar.gz
https://pypi.python.org/packages/source/s/setuptools/setuptools-20.2.2.tar.gz
https://pypi.python.org/packages/source/w/wheel/wheel-0.29.0.tar.gz

And optionally:

https://pypi.python.org/packages/source/a/argparse/argparse-1.4.0.tar.gz

Taking into account the URLs point to pypi.python.org, this was probably a transient error.

Alternatively, you may try to install Certbot from the official PPA instead of using certbot-auto.


问:
How can I implement an add/edit parameter mechanism?
Assume this is my current URL:

```<code>http://example.com/search?param1=foo&param2=bar
</code>```

Now I want to add param3=baz. So this is the code:

```<code><a href="?param3=baz" >add param3</a>
//=> http://example.com/search?param3=baz
</code>```

See? param1 and param2 will be removed. So I have to handle it like this:

```<code><?php
    $query_str = parse_url($url, PHP_URL_QUERY);
    parse_str($query_str, $query_params);
    $query_params = $query_params == '' ? '?' : $query_params . '&';
?>

<a href="?{$query_params}param3=baz" >add param3</a>
</code>```

Seems ugly, but ok, nevermind. Now what happens if a parameter be already exist and I need to edit it? Assume this example:

```<code>http://example.com/search?param1=foo&param2=bar
</code>```

Now how can I make a link which edits the value of parame2? (plus keeping other parameters)

答:
You can use function http_build_query to generate new query, like this:

```<code>$url = 'http://example.com/search?param1=foo&param2=bar';

$query_str = parse_url($url, PHP_URL_QUERY);
parse_str($query_str, $params);

$data = [
    'param3' => 'baz'
];

$params = array_merge($params, $data);

echo http_build_query($params) . "\n";
</code>```

And output will be:

```<code>param1=foo&param2=bar&param3=baz
</code>```

I use array_merge for override exist params, if we get url:

```<code>$url = 'http://example.com/search?param1=foo&param3=bar';
</code>```

The same code output will be:

```<code>param1=foo&param3=baz
</code>```

We override exist param and save old params.

Body:
Assume this is my current URL:

http://example.com/search?param1=foo&param2=bar

Now I want to add param3=baz. So this is the code:

add param3
//=> http://example.com/search?param3=baz

See? param1 and param2 will be removed. So I have to handle it like this:

<?php
    $query_str = parse_url($url, PHP_URL_QUERY);
    parse_str($query_str, $query_params);
    $query_params = $query_params == '' ? '?' : $query_params . '&';
?>

add param3

Seems ugly, but ok, nevermind. Now what happens if a parameter be already exist and I need to edit it? Assume this example:

http://example.com/search?param1=foo&param2=bar

Now how can I make a link which edits the value of parame2? (plus keeping other parameters)

Body:
You can use function http_build_query to generate new query, like this:

$url = 'http://example.com/search?param1=foo&param2=bar';

$query_str = parse_url($url, PHP_URL_QUERY);
parse_str($query_str, $params);

$data = [
    'param3' => 'baz'
];

$params = array_merge($params, $data);

echo http_build_query($params) . "\n";

And output will be:

param1=foo&param2=bar&param3=baz

I use array_merge for override exist params, if we get url:

$url = 'http://example.com/search?param1=foo&param3=bar';

The same code output will be:

param1=foo&param3=baz

We override exist param and save old params.


问:
How to build an external linux module which uses a custom library
I am trying to compile an external linux driver with the the line below within an existing platform using many dependencies (such as libraries):

```<code>    obj-m += mydriver.o
    KDIR ?= $(OUT_DIR)
    default:
       $(MAKE) -C $(KDIR) M=$$PWD
    clean:
       $(MAKE) -C $(KDIR) M=$$PWD clean
    modules:
       $(MAKE) -C $(KDIR) M=$$PWD modules
</code>```

I have noticed that this invokes the kernel Makefile with creates object files and does the link in order to prepare a "module".ko loadable with linux. But what if, I have to use a specific library (eg. my_library.a): how can I prevent the Linux makefile to take into account this extra library when linking all the object files

```<code>   Appendice:
</code>```

My_library.a is a c++ source code contains functions that access to FPGA registers in order to report some useful data. Then my_driver (since it is a C code source , I had to create an C- interface from my_library.a ) will prepare basic system calls accessible from a user-space application. Bottom of line, my_driver reads from FPGA with 8khz, thanks to my_library.a via a C-interface and make data readable for user-space APP.

Cheers,
sahbi

答:
Most probably, you cannot use an application-level external library libmy.a or my_library.a in any kernel module (or kernel code). Such libraries are generally built above the C standard library (e.g. because they use <stdio.h> thru fprintf or <stdlib.h> thru malloc), which does not exist for kernel code.

Conceptually kernel modules and kernel code is freestanding (i.e. not above the C standard library).

Notice that the ABI & calling conventions might be different in kernel code and in application code. And certainly, some standard functions (like malloc, printf, snprintf ....) might not exist inside the kernel. BTW kernel code is not allowed to use floating point, etc...

Of course, you could link your own kernel library (out of your own kernel object files), but that is often not worthwhile.

(an improbable exception could be some external library which do not use any standard C function and do not compute with floating point, but that does not happen in pracice)

At last, the conventional wisdom is to avoid needing lot of kernel code. So you should consider having some helper user-mode process. See netlink(7).

You probably should redesign your driver to avoid needing any external library. Since you read the FPGA at only 8KHz, that part of your code could sit in user-land above existing system calls.

Notice that kernel code cannot be written in C++

Body:
I am trying to compile an external linux driver with the the line below within an existing platform using many dependencies (such as libraries):

    obj-m += mydriver.o
    KDIR ?= $(OUT_DIR)
    default:
       $(MAKE) -C $(KDIR) M=$$PWD
    clean:
       $(MAKE) -C $(KDIR) M=$$PWD clean
    modules:
       $(MAKE) -C $(KDIR) M=$$PWD modules

I have noticed that this invokes the kernel Makefile with creates object files and does the link in order to prepare a "module".ko loadable with linux. But what if, I have to use a specific library (eg. my_library.a): how can I prevent the Linux makefile to take into account this extra library when linking all the object files

   Appendice:

My_library.a is a c++ source code contains functions that access to FPGA registers in order to report some useful data. Then my_driver (since it is a C code source , I had to create an C- interface from my_library.a ) will prepare basic system calls accessible from a user-space application. Bottom of line, my_driver reads from FPGA with 8khz, thanks to my_library.a via a C-interface and make data readable for user-space APP.

Cheers,
sahbi