问:
java.lang.NullPointerException: No API environment is registered for this thread
I have gwt 2.6.1 application which runs successfully in kepler with google app engine sdk 1.9.7. now i have updated Cloud Tools for Eclipse  and GWT Eclipse Plugin

Now i have improted existing project in this new version then when i run this project with GWT development mode with jetty then i got below exception

```<code>2017-11-14 13:09:35.108:WARN:oejw.WebAppContext:Failed startup of context c.g.g.d.s.j.WebAppContextWithReload{/,file:/C:/NEON%20Projects/14%20nov%20existing%20project/Slick%20Erp/war/},C:\NEON Projects\14 nov existing project\Slick Erp\war
java.lang.NullPointerException: No API environment is registered for this thread.
    at com.google.appengine.api.datastore.DatastoreApiHelper.getCurrentAppId(DatastoreApiHelper.java:144)
    at com.google.appengine.api.datastore.DatastoreApiHelper.getCurrentAppIdNamespace(DatastoreApiHelper.java:160)
    at com.google.appengine.api.datastore.Query.<init>(Query.java:210)
    at com.google.appengine.api.datastore.Query.<init>(Query.java:141)
    at com.googlecode.objectify.impl.QueryImpl.<init>(QueryImpl.java:69)
    at com.googlecode.objectify.impl.LoadTypeImpl.createQuery(LoadTypeImpl.java:48)
    at com.googlecode.objectify.impl.Queryable.list(Queryable.java:55)
    at com.slicktechnologies.server.MyWarmup.contextInitialized(MyWarmup.java:352)
    at org.eclipse.jetty.server.handler.ContextHandler.callContextInitialized(ContextHandler.java:782)
    at org.eclipse.jetty.servlet.ServletContextHandler.callContextInitialized(ServletContextHandler.java:424)
    at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:774)
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:249)
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1242)
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:717)
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:494)
    at com.google.gwt.dev.shell.jetty.JettyLauncher$WebAppContextWithReload.doStart(JettyLauncher.java:541)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
    at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:95)
    at org.eclipse.jetty.server.handler.RequestLogHandler.doStart(RequestLogHandler.java:162)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
    at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:95)
    at org.eclipse.jetty.server.Server.doStart(Server.java:282)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
    at com.google.gwt.dev.shell.jetty.JettyLauncher.start(JettyLauncher.java:740)
    at com.google.gwt.dev.DevMode.doStartUpServer(DevMode.java:632)
    at com.google.gwt.dev.DevModeBase.startUp(DevModeBase.java:1054)
    at com.google.gwt.dev.DevModeBase.run(DevModeBase.java:836)
    at com.google.gwt.dev.DevMode.main(DevMode.java:413)
</code>```

any help ? how to solve this exception ?

答: You need to launch using the App Engine development server.  Fortunately it can serve GWT applications, but you need to enable the GWT Super Dev Mode builder on your project.  See the Cloud Tools for Eclipse docs on Migrating from the Google Plugin for Eclipse.

Body:
I have gwt 2.6.1 application which runs successfully in kepler with google app engine sdk 1.9.7. now i have updated Cloud Tools for Eclipse  and GWT Eclipse Plugin

Now i have improted existing project in this new version then when i run this project with GWT development mode with jetty then i got below exception

2017-11-14 13:09:35.108:WARN:oejw.WebAppContext:Failed startup of context c.g.g.d.s.j.WebAppContextWithReload{/,file:/C:/NEON%20Projects/14%20nov%20existing%20project/Slick%20Erp/war/},C:\NEON Projects\14 nov existing project\Slick Erp\war
java.lang.NullPointerException: No API environment is registered for this thread.
    at com.google.appengine.api.datastore.DatastoreApiHelper.getCurrentAppId(DatastoreApiHelper.java:144)
    at com.google.appengine.api.datastore.DatastoreApiHelper.getCurrentAppIdNamespace(DatastoreApiHelper.java:160)
    at com.google.appengine.api.datastore.Query.<init>(Query.java:210)
    at com.google.appengine.api.datastore.Query.<init>(Query.java:141)
    at com.googlecode.objectify.impl.QueryImpl.<init>(QueryImpl.java:69)
    at com.googlecode.objectify.impl.LoadTypeImpl.createQuery(LoadTypeImpl.java:48)
    at com.googlecode.objectify.impl.Queryable.list(Queryable.java:55)
    at com.slicktechnologies.server.MyWarmup.contextInitialized(MyWarmup.java:352)
    at org.eclipse.jetty.server.handler.ContextHandler.callContextInitialized(ContextHandler.java:782)
    at org.eclipse.jetty.servlet.ServletContextHandler.callContextInitialized(ServletContextHandler.java:424)
    at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:774)
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:249)
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1242)
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:717)
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:494)
    at com.google.gwt.dev.shell.jetty.JettyLauncher$WebAppContextWithReload.doStart(JettyLauncher.java:541)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
    at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:95)
    at org.eclipse.jetty.server.handler.RequestLogHandler.doStart(RequestLogHandler.java:162)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
    at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:95)
    at org.eclipse.jetty.server.Server.doStart(Server.java:282)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
    at com.google.gwt.dev.shell.jetty.JettyLauncher.start(JettyLauncher.java:740)
    at com.google.gwt.dev.DevMode.doStartUpServer(DevMode.java:632)
    at com.google.gwt.dev.DevModeBase.startUp(DevModeBase.java:1054)
    at com.google.gwt.dev.DevModeBase.run(DevModeBase.java:836)
    at com.google.gwt.dev.DevMode.main(DevMode.java:413)

any help ? how to solve this exception ?


来源: stackexchange

问:
jQuery - manipulate dropped element in sortable list
I have a draggable list (.field) where you can drag & drop items from it into a sortable list (.sortlist). I did it this way because I didn't want the master list (.field) altered in any way. It works fine, except I cannot work out how to manipulate the dropped field in a sortable list.

I can do it  from a draggable into a droppable area by using the following in a function for 'drop:' in droppable():

```<code>$(this).append('html code here to change content of dragged field');
</code>```

However this doesn't work inside a sortable(). My code looks like this:

```<code>$(".sortlist").sortable({
  receive: function(event, ui) {
    var dropElemTxt = $(ui.item).text();
    var dropElemId = $(ui.item).attr('id');
    $(ui.item).replaceWith('<li class="box" id="'+dropElemId+'">Updated field! '+dropElemTxt+'</li>');
  }
});
</code>```

$(ui.item).replaceWith changes the master field that was being dragged, so this doesn't work. And I tried $(this).replaceWith, but that updates the sortable area (.sortlist).

Any idea what code I need to reference the dragged item?

Many thanks,
Ali.

答:
You could get the dragged item in beforeStop event:

```<code>beforeStop: function (event, ui) { draggedItem = ui.item;},
receive: function (event, ui) { /* use draggedItem here*/ }
</code>```

Using beforeStop event instead of receive was enough for me:

```<code>beforeStop: function(event, ui) {
        var myClassItem = $('.myClass', ui.item);
        myClassItem.bind('click', function(){ /*my function*/ });
    }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a draggable list (.field) where you can drag & drop items from it into a sortable list (.sortlist). I did it this way because I didn't want the master list (.field) altered in any way. It works fine, except I cannot work out how to manipulate the dropped field in a sortable list.

I can do it  from a draggable into a droppable area by using the following in a function for 'drop:' in droppable():

$(this).append('html code here to change content of dragged field');

However this doesn't work inside a sortable(). My code looks like this:

$(".sortlist").sortable({
  receive: function(event, ui) {
    var dropElemTxt = $(ui.item).text();
    var dropElemId = $(ui.item).attr('id');
    $(ui.item).replaceWith('
Updated field! '+dropElemTxt+'
');
  }
});

$(ui.item).replaceWith changes the master field that was being dragged, so this doesn't work. And I tried $(this).replaceWith, but that updates the sortable area (.sortlist).

Any idea what code I need to reference the dragged item?

Many thanks,
Ali.

Body:
You could get the dragged item in beforeStop event:

beforeStop: function (event, ui) { draggedItem = ui.item;},
receive: function (event, ui) { /* use draggedItem here*/ }

Using beforeStop event instead of receive was enough for me:

beforeStop: function(event, ui) {
        var myClassItem = $('.myClass', ui.item);
        myClassItem.bind('click', function(){ /*my function*/ });
    }


问:
imap_append not working with attachments
I'm trying to copy emails into my sent folder using php's imap_append function. It works perfectly fine on emails without attachments. However, if I add an attachment it seems to spring out an error:

```<code>Notice: Unknown: [CLOSED] IMAP connection broken (server response) (errflg=2) in Unknown
</code>```

Oddly, if I attach a .txt file with a few lines the attachment comes through, but if I attach a pdf/word document/etc it gives out the above error.

I have checked the headers/body/attachments and all appear to be fine to the best of my knowledge. I am using PHPMailer version 5.

PHP code below:

```<code>$mail = new PHPMailer();

$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = true;
$mail->Host = "smtp.livemail.co.uk";
$mail->Username = "xxx@xxx.com";
$mail->Password = "xxx";
$mail->CharSet    = "UTF-8";
$mail->From       = "xxx@xxx.co.uk";
$mail->FromName   = "Test";
$mail->Subject = "Testing";
$mail->AltBody = "Testing";
$mail->MsgHTML("<body><h1>Hello, this is a test</h1></body>");
$mail->AddAddress("xxx@xxx.co.uk", "xxx");
$mail->AddAttachment("attachment.docx");

$mail->Send();

// We would like to append message into our sent folder at this point
$connection_string = "{mail.livemail.co.uk:993/imap/ssl}Sent Items";

$stream = imap_open($connection_string, "xxx@xxx.co.uk", "xxx");

imap_append($stream,$connection_string,$mail->CreateHeader() . $mail->CreateBody());
</code>```

Headers

```<code>Date: Thu, 16 Nov 2017 19:30:43 +0000
Return-Path: xxx@xxx.co.uk
To: xxx <xxx@xxx.co.uk>
From: xxx <xxx@xxx.co.uk>
Subject: Testing
Message-ID: <e92d6eed5e3b708416fb06661aeaab2c@localhost>
X-Priority: 3
X-Mailer: PHPMailer 5.1 (phpmailer.sourceforge.net)
MIME-Version: 1.0
Content-Type: multipart/mixed;
    boundary="b1_e92d6eed5e3b708416fb06661aeaab2c"

--b1_e92d6eed5e3b708416fb06661aeaab2c
Content-Type: multipart/alternative;
    boundary="b2_e92d6eed5e3b708416fb06661aeaab2c"

--b2_e92d6eed5e3b708416fb06661aeaab2c
Content-Type: text/plain; charset = "UTF-8"
Content-Transfer-Encoding: 8bit

Testing

--b2_e92d6eed5e3b708416fb06661aeaab2c
Content-Type: text/html; charset = "UTF-8"
Content-Transfer-Encoding: 8bit

<body><h1>Hello, this is a test</h1></body>

--b2_e92d6eed5e3b708416fb06661aeaab2c--
--b1_e92d6eed5e3b708416fb06661aeaab2c
Content-Type: application/octet-stream; name="attachment.docx"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="attachment.docx"

[encoded data, 15628 characters]

--b1_e92d6eed5e3b708416fb06661aeaab2c--
</code>```

To update this, I am using an older version of PHPMailer:

```<code>  /**
   * Assembles the message body.  Returns an empty string on failure.
   * @access public
   * @return string The assembled message body
   */
  public function CreateBody() {
    $body = '';

    if ($this->sign_key_file) {
      $body .= $this->GetMailMIME();
    }

    $this->SetWordWrap();

    switch($this->message_type) {
      case 'alt':
        $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
        $body .= $this->EncodeString($this->AltBody, $this->Encoding);
        $body .= $this->LE.$this->LE;
        $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', '');
        $body .= $this->EncodeString($this->Body, $this->Encoding);
        $body .= $this->LE.$this->LE;
        $body .= $this->EndBoundary($this->boundary[1]);
        break;
      case 'plain':
        $body .= $this->EncodeString($this->Body, $this->Encoding);
        break;
      case 'attachments':
        $body .= $this->GetBoundary($this->boundary[1], '', '', '');
        $body .= $this->EncodeString($this->Body, $this->Encoding);
        $body .= $this->LE;
        $body .= $this->AttachAll();
        break;
      case 'alt_attachments':
        $body .= sprintf("--%s%s", $this->boundary[1], $this->LE);
        $body .= sprintf("Content-Type: %s;%s" . "\tboundary=\"%s\"%s", 'multipart/alternative', $this->LE, $this->boundary[2], $this->LE.$this->LE);
        $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '') . $this->LE; // Create text body
        $body .= $this->EncodeString($this->AltBody, $this->Encoding);
        $body .= $this->LE.$this->LE;
        $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '') . $this->LE; // Create the HTML body
        $body .= $this->EncodeString($this->Body, $this->Encoding);
        $body .= $this->LE.$this->LE;
        $body .= $this->EndBoundary($this->boundary[2]);
        $body .= $this->AttachAll();
        break;
    }

    if ($this->IsError()) {
      $body = '';
    } elseif ($this->sign_key_file) {
      try {
        $file = tempnam('', 'mail');
        file_put_contents($file, $body); //TODO check this worked
        $signed = tempnam("", "signed");
        if (@openssl_pkcs7_sign($file, $signed, "file://".$this->sign_cert_file, array("file://".$this->sign_key_file, $this->sign_key_pass), NULL)) {
          @unlink($file);
          @unlink($signed);
          $body = file_get_contents($signed);
        } else {
          @unlink($file);
          @unlink($signed);
          throw new phpmailerException($this->Lang("signing").openssl_error_string());
        }
      } catch (phpmailerException $e) {
        $body = '';
        if ($this->exceptions) {
          throw $e;
        }
      }
    }

    return $body;
  }

  /**
   * Assembles message header.
   * @access public
   * @return string The assembled header
   */
  public function CreateHeader() {
    $result = '';

    // Set the boundaries
    $uniq_id = md5(uniqid(time()));
    $this->boundary[1] = 'b1_' . $uniq_id;
    $this->boundary[2] = 'b2_' . $uniq_id;

    if($this->Timezone=='' || $this->Timezone==0) $this->Timezone = date_default_timezone_get();
    date_default_timezone_set($this->Timezone);
    $result .= $this->HeaderLine('Date', self::RFCDate($this->Timezone));
    if($this->Sender == '') {
      $result .= $this->HeaderLine('Return-Path', trim($this->From));
    } else {
      $result .= $this->HeaderLine('Return-Path', trim($this->Sender));
    }

    // To be created automatically by mail()
    if($this->Mailer != 'mail') {
      if ($this->SingleTo === true) {
        foreach($this->to as $t) {
          $this->SingleToArray[] = $this->AddrFormat($t);
        }
      } else {
        if(count($this->to) > 0) {
          $result .= $this->AddrAppend('To', $this->to);
        } elseif (count($this->cc) == 0) {
          $result .= $this->HeaderLine('To', 'undisclosed-recipients:;');
        }
      }
    }

    $from = array();
    $from[0][0] = trim($this->From);
    $from[0][1] = $this->FromName;
    $result .= $this->AddrAppend('From', $from);

    // sendmail and mail() extract Cc from the header before sending
    if(count($this->cc) > 0) {
      $result .= $this->AddrAppend('Cc', $this->cc);
    }

    // sendmail and mail() extract Bcc from the header before sending
    if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) {
      $result .= $this->AddrAppend('Bcc', $this->bcc);
    }

    if(count($this->ReplyTo) > 0) {
      $result .= $this->AddrAppend('Reply-to', $this->ReplyTo);
    }

    // mail() sets the subject itself
    if($this->Mailer != 'mail') {
      $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject)));
    }

    if($this->MessageID != '') {
      $result .= $this->HeaderLine('Message-ID',$this->MessageID);
    } else {
      $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
    }
    $result .= $this->HeaderLine('X-Priority', $this->Priority);
    $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (phpmailer.sourceforge.net)');

    if($this->ConfirmReadingTo != '') {
      $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
    }

    // Add custom headers
    for($index = 0; $index < count($this->CustomHeader); $index++) {
      $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
    }
    if (!$this->sign_key_file) {
      $result .= $this->HeaderLine('MIME-Version', '1.0');
      $result .= $this->GetMailMIME();
    }

    return $result;
  }
</code>```

The above two functions are exactly how Send() is calling the body/header.

Anyone got any ideas? Can't find anything on this.

答:
One of the PHPMailer examples shows IMAP upload, though I've not tried it with attachments. I suspect that the problem lies in how you're creating the message to upload; I don't know where you got this from:

```<code>$mail->CreateHeader() . $mail->CreateBody()
</code>```

That will not work properly as there is no separator between header and body, likely resulting in an unusable message. PHPMailer has a built-in function to get the whole message for you: getSentMIMEMessage(), so to upload a copy of the message you should do this instead:

```<code>$result = imap_append($imapStream, $path, $mail->getSentMIMEMessage());
</code>```

and compare the rest of the example with your code.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to copy emails into my sent folder using php's imap_append function. It works perfectly fine on emails without attachments. However, if I add an attachment it seems to spring out an error:

Notice: Unknown: [CLOSED] IMAP connection broken (server response) (errflg=2) in Unknown

Oddly, if I attach a .txt file with a few lines the attachment comes through, but if I attach a pdf/word document/etc it gives out the above error.

I have checked the headers/body/attachments and all appear to be fine to the best of my knowledge. I am using PHPMailer version 5.

PHP code below:

$mail = new PHPMailer();

$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = true;
$mail->Host = "smtp.livemail.co.uk";
$mail->Username = "xxx@xxx.com";
$mail->Password = "xxx";
$mail->CharSet    = "UTF-8";
$mail->From       = "xxx@xxx.co.uk";
$mail->FromName   = "Test";
$mail->Subject = "Testing";
$mail->AltBody = "Testing";
$mail->MsgHTML("
Hello, this is a test
");
$mail->AddAddress("xxx@xxx.co.uk", "xxx");
$mail->AddAttachment("attachment.docx");

$mail->Send();

// We would like to append message into our sent folder at this point
$connection_string = "{mail.livemail.co.uk:993/imap/ssl}Sent Items";

$stream = imap_open($connection_string, "xxx@xxx.co.uk", "xxx");

imap_append($stream,$connection_string,$mail->CreateHeader() . $mail->CreateBody());

Headers

Date: Thu, 16 Nov 2017 19:30:43 +0000
Return-Path: xxx@xxx.co.uk
To: xxx <xxx@xxx.co.uk>
From: xxx <xxx@xxx.co.uk>
Subject: Testing
Message-ID: <e92d6eed5e3b708416fb06661aeaab2c@localhost>
X-Priority: 3
X-Mailer: PHPMailer 5.1 (phpmailer.sourceforge.net)
MIME-Version: 1.0
Content-Type: multipart/mixed;
    boundary="b1_e92d6eed5e3b708416fb06661aeaab2c"

--b1_e92d6eed5e3b708416fb06661aeaab2c
Content-Type: multipart/alternative;
    boundary="b2_e92d6eed5e3b708416fb06661aeaab2c"

--b2_e92d6eed5e3b708416fb06661aeaab2c
Content-Type: text/plain; charset = "UTF-8"
Content-Transfer-Encoding: 8bit

Testing

--b2_e92d6eed5e3b708416fb06661aeaab2c
Content-Type: text/html; charset = "UTF-8"
Content-Transfer-Encoding: 8bit

Hello, this is a test

--b2_e92d6eed5e3b708416fb06661aeaab2c--
--b1_e92d6eed5e3b708416fb06661aeaab2c
Content-Type: application/octet-stream; name="attachment.docx"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="attachment.docx"

[encoded data, 15628 characters]

--b1_e92d6eed5e3b708416fb06661aeaab2c--

To update this, I am using an older version of PHPMailer:

  /**
   * Assembles the message body.  Returns an empty string on failure.
   * @access public
   * @return string The assembled message body
   */
  public function CreateBody() {
    $body = '';

    if ($this->sign_key_file) {
      $body .= $this->GetMailMIME();
    }

    $this->SetWordWrap();

    switch($this->message_type) {
      case 'alt':
        $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
        $body .= $this->EncodeString($this->AltBody, $this->Encoding);
        $body .= $this->LE.$this->LE;
        $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', '');
        $body .= $this->EncodeString($this->Body, $this->Encoding);
        $body .= $this->LE.$this->LE;
        $body .= $this->EndBoundary($this->boundary[1]);
        break;
      case 'plain':
        $body .= $this->EncodeString($this->Body, $this->Encoding);
        break;
      case 'attachments':
        $body .= $this->GetBoundary($this->boundary[1], '', '', '');
        $body .= $this->EncodeString($this->Body, $this->Encoding);
        $body .= $this->LE;
        $body .= $this->AttachAll();
        break;
      case 'alt_attachments':
        $body .= sprintf("--%s%s", $this->boundary[1], $this->LE);
        $body .= sprintf("Content-Type: %s;%s" . "\tboundary=\"%s\"%s", 'multipart/alternative', $this->LE, $this->boundary[2], $this->LE.$this->LE);
        $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '') . $this->LE; // Create text body
        $body .= $this->EncodeString($this->AltBody, $this->Encoding);
        $body .= $this->LE.$this->LE;
        $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '') . $this->LE; // Create the HTML body
        $body .= $this->EncodeString($this->Body, $this->Encoding);
        $body .= $this->LE.$this->LE;
        $body .= $this->EndBoundary($this->boundary[2]);
        $body .= $this->AttachAll();
        break;
    }

    if ($this->IsError()) {
      $body = '';
    } elseif ($this->sign_key_file) {
      try {
        $file = tempnam('', 'mail');
        file_put_contents($file, $body); //TODO check this worked
        $signed = tempnam("", "signed");
        if (@openssl_pkcs7_sign($file, $signed, "file://".$this->sign_cert_file, array("file://".$this->sign_key_file, $this->sign_key_pass), NULL)) {
          @unlink($file);
          @unlink($signed);
          $body = file_get_contents($signed);
        } else {
          @unlink($file);
          @unlink($signed);
          throw new phpmailerException($this->Lang("signing").openssl_error_string());
        }
      } catch (phpmailerException $e) {
        $body = '';
        if ($this->exceptions) {
          throw $e;
        }
      }
    }

    return $body;
  }

  /**
   * Assembles message header.
   * @access public
   * @return string The assembled header
   */
  public function CreateHeader() {
    $result = '';

    // Set the boundaries
    $uniq_id = md5(uniqid(time()));
    $this->boundary[1] = 'b1_' . $uniq_id;
    $this->boundary[2] = 'b2_' . $uniq_id;

    if($this->Timezone=='' || $this->Timezone==0) $this->Timezone = date_default_timezone_get();
    date_default_timezone_set($this->Timezone);
    $result .= $this->HeaderLine('Date', self::RFCDate($this->Timezone));
    if($this->Sender == '') {
      $result .= $this->HeaderLine('Return-Path', trim($this->From));
    } else {
      $result .= $this->HeaderLine('Return-Path', trim($this->Sender));
    }

    // To be created automatically by mail()
    if($this->Mailer != 'mail') {
      if ($this->SingleTo === true) {
        foreach($this->to as $t) {
          $this->SingleToArray[] = $this->AddrFormat($t);
        }
      } else {
        if(count($this->to) > 0) {
          $result .= $this->AddrAppend('To', $this->to);
        } elseif (count($this->cc) == 0) {
          $result .= $this->HeaderLine('To', 'undisclosed-recipients:;');
        }
      }
    }

    $from = array();
    $from[0][0] = trim($this->From);
    $from[0][1] = $this->FromName;
    $result .= $this->AddrAppend('From', $from);

    // sendmail and mail() extract Cc from the header before sending
    if(count($this->cc) > 0) {
      $result .= $this->AddrAppend('Cc', $this->cc);
    }

    // sendmail and mail() extract Bcc from the header before sending
    if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) {
      $result .= $this->AddrAppend('Bcc', $this->bcc);
    }

    if(count($this->ReplyTo) > 0) {
      $result .= $this->AddrAppend('Reply-to', $this->ReplyTo);
    }

    // mail() sets the subject itself
    if($this->Mailer != 'mail') {
      $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject)));
    }

    if($this->MessageID != '') {
      $result .= $this->HeaderLine('Message-ID',$this->MessageID);
    } else {
      $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
    }
    $result .= $this->HeaderLine('X-Priority', $this->Priority);
    $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (phpmailer.sourceforge.net)');

    if($this->ConfirmReadingTo != '') {
      $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
    }

    // Add custom headers
    for($index = 0; $index < count($this->CustomHeader); $index++) {
      $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
    }
    if (!$this->sign_key_file) {
      $result .= $this->HeaderLine('MIME-Version', '1.0');
      $result .= $this->GetMailMIME();
    }

    return $result;
  }

The above two functions are exactly how Send() is calling the body/header.

Anyone got any ideas? Can't find anything on this.

Body:
One of the PHPMailer examples shows IMAP upload, though I've not tried it with attachments. I suspect that the problem lies in how you're creating the message to upload; I don't know where you got this from:

$mail->CreateHeader() . $mail->CreateBody()

That will not work properly as there is no separator between header and body, likely resulting in an unusable message. PHPMailer has a built-in function to get the whole message for you: getSentMIMEMessage(), so to upload a copy of the message you should do this instead:

$result = imap_append($imapStream, $path, $mail->getSentMIMEMessage());

and compare the rest of the example with your code.


问:
The most efficient way to determine the presence of repeated values in a 2D array, arranged like a table (with some starting ideas)
I am switching the tags for this question as I don't believe it is a C# .NET specific question, and more so a mathematical/algorithms one. Say I have an 2D array of ints, like below:

```<code> 0 | 1 | 2
---+---+---
 0 | 1 | 0
---+---+---
 1 | 0 | 0
</code>```

These could be stored in a different data structure if this would allow a faster solution to the problem. The problem being how to detect (and find the locations of) equal integer values stored adjacently (allowing for diagonals) (and not accounting for "wrapping around" adjacency, for example a corner piece should only need to be compared with 3 other values... that is unless there is a better solution to storing the data).

My first (and I am sure naive) approach would be a 2D array (implemented as a jagged array or just indexed like this) in which I store the integer values. I have no need for any sort property besides just whether or not values are equal (i.e. no need for >, <, etc). I could then do an N^8 (not sure if this is the correct time analysis for this situation but it was my best try)traversal of all N locations in the array, and 8 checks maximum (if not on the edge) per iteration. I think there may be a better way to do this, however. Especially as this approach is very time consuming.

One idea I had is to modify the data structure so that every item has a flag (included in each structure in the array [so not just an array of ints]) of whether it is the same as any adjacent value. This would slow down my insertion and building processes, but may (??) speed up the process of finding pairs in the table. Thanks for any help.

答:
I think you have to just traverse the rows and check if the value in the current cell matches one of it's neighbors. If you always move from left to right and top to bottom, then you only need to check a maximum of 4 other cells: the cell to the right and the three cells below (prev column, this column, and next column). As soon as you find a match, you return true. If no matches are found, return false:</p>

```<code>private static bool HasRepeatingItem(int[][] board)
{
    if (board == null) return false;

    for (int row = 0; row < board.Length; row++)
    {
        for (int col = 0; col < board[row].Length; col++)
        {
            var thisValue = board[row][col];

            // If there's another column, check for horizontal match
            if (col < board[row].Length - 1 && thisValue == board[row][col + 1])
                return true;

            // If there's a row below, check for matches
            if (row < board.Length - 1)
            {
                // Check directly below for vertical match
                if (thisValue == board[row + 1][col]) return true;

                // Check below left for horizontal match
                if (col > 0 && thisValue == board[row + 1][col - 1]) return true;

                // Check below right for horizontal match
                if (col < board[row].Length - 1 && thisValue == board[row + 1][col + 1])
                    return true;
            }
        }
    }

    return false;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am switching the tags for this question as I don't believe it is a C# .NET specific question, and more so a mathematical/algorithms one. Say I have an 2D array of ints, like below:

 0 | 1 | 2
---+---+---
 0 | 1 | 0
---+---+---
 1 | 0 | 0

These could be stored in a different data structure if this would allow a faster solution to the problem. The problem being how to detect (and find the locations of) equal integer values stored adjacently (allowing for diagonals) (and not accounting for "wrapping around" adjacency, for example a corner piece should only need to be compared with 3 other values... that is unless there is a better solution to storing the data).

My first (and I am sure naive) approach would be a 2D array (implemented as a jagged array or just indexed like this) in which I store the integer values. I have no need for any sort property besides just whether or not values are equal (i.e. no need for >, <, etc). I could then do an N^8 (not sure if this is the correct time analysis for this situation but it was my best try)traversal of all N locations in the array, and 8 checks maximum (if not on the edge) per iteration. I think there may be a better way to do this, however. Especially as this approach is very time consuming.

One idea I had is to modify the data structure so that every item has a flag (included in each structure in the array [so not just an array of ints]) of whether it is the same as any adjacent value. This would slow down my insertion and building processes, but may (??) speed up the process of finding pairs in the table. Thanks for any help.

Body:
I think you have to just traverse the rows and check if the value in the current cell matches one of it's neighbors. If you always move from left to right and top to bottom, then you only need to check a maximum of 4 other cells: the cell to the right and the three cells below (prev column, this column, and next column). As soon as you find a match, you return true. If no matches are found, return false:

private static bool HasRepeatingItem(int[][] board)
{
    if (board == null) return false;

    for (int row = 0; row < board.Length; row++)
    {
        for (int col = 0; col < board[row].Length; col++)
        {
            var thisValue = board[row][col];

            // If there's another column, check for horizontal match
            if (col < board[row].Length - 1 && thisValue == board[row][col + 1])
                return true;

            // If there's a row below, check for matches
            if (row < board.Length - 1)
            {
                // Check directly below for vertical match
                if (thisValue == board[row + 1][col]) return true;

                // Check below left for horizontal match
                if (col > 0 && thisValue == board[row + 1][col - 1]) return true;

                // Check below right for horizontal match
                if (col < board[row].Length - 1 && thisValue == board[row + 1][col + 1])
                    return true;
            }
        }
    }

    return false;
}


问:
How to find the index based on the gathered population
A dataset has some patterns of gathered group. Here is the dataset:

```<code>index <- c(1:30)
a <- c(0,1,0,0,0,1,1,1,0,0,1,1,0,0,0,0,1,1,1,1,0,0,1,0,1,1,1,0,1,0)
b <- c(1,1,1,0,0,1,1,1,0,0,1,1,1,1,0,0,1,1,1,0,0,0,0,0,1,0,1,1,1,1)
c <- c(1,1,1,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
d <- c(0,0,0,0,0,0,1,0,1,0,1,1,1,1,1,0,0,1,1,1,0,0,0,0,0,1,0,1,1,1)
df <- data.frame(cbind(index, a, b, c, d))
</code>```

In general, the task is to identify the index (i.e., the column "index") when the data columns (i.e., a, b, c, d) show at least three consecutive value (i.e., 1) in its column and also its neighbor column show at least three consecutive value (i.e., 1).

For example, the result from the example below will output 2, 3, 4, 7, 8, 9. See highlighted consecutive value.

index   1 2 3 4 5 6 7 8 9

col-a 0 0 0 0 0 1 1 0 1

col-b 1 0 1 0 1 1 1 1 1

col-c 0 1 1 1 0 0 1 1 1

col-d 1 1 1 1 0 0 0 0 0

The result should output the index: 1, 2, 3, 6, 7, 8, 12, 13, 14, 17, 18, 19, 27.

答:
```<code>sort(Reduce(union,
       lapply(lapply(2:(ncol(df) - 1), function(j) c(j, j + 1)), function(cols) {
           which(rowSums(sapply(df[cols], function(x)
             sapply(1:length(x), function(i) {
               sum(x[max(1, i - 1):min(i + 1, length(x))]) == 3 |
                 sum(x[max(1, i - 2):i]) == 3 |
                 sum(x[i:min(i + 2, length(x))]) == 3
             }))) > 1)
         })))
# [1]  1  2  3  6  7  8 12 13 14 17 18 19 27
</code>```

Body:
A dataset has some patterns of gathered group. Here is the dataset:

index <- c(1:30)
a <- c(0,1,0,0,0,1,1,1,0,0,1,1,0,0,0,0,1,1,1,1,0,0,1,0,1,1,1,0,1,0)
b <- c(1,1,1,0,0,1,1,1,0,0,1,1,1,1,0,0,1,1,1,0,0,0,0,0,1,0,1,1,1,1)
c <- c(1,1,1,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
d <- c(0,0,0,0,0,0,1,0,1,0,1,1,1,1,1,0,0,1,1,1,0,0,0,0,0,1,0,1,1,1)
df <- data.frame(cbind(index, a, b, c, d))

In general, the task is to identify the index (i.e., the column "index") when the data columns (i.e., a, b, c, d) show at least three consecutive value (i.e., 1) in its column and also its neighbor column show at least three consecutive value (i.e., 1).

For example, the result from the example below will output 2, 3, 4, 7, 8, 9. See highlighted consecutive value.

index   1 2 3 4 5 6 7 8 9

col-a 0 0 0 0 0 1 1 0 1

col-b 1 0 1 0 1 1 1 1 1

col-c 0 1 1 1 0 0 1 1 1

col-d 1 1 1 1 0 0 0 0 0

The result should output the index: 1, 2, 3, 6, 7, 8, 12, 13, 14, 17, 18, 19, 27.


问:
Expiring/busting Etag in Rails
When doing HTTP caching in rails, once would use:

fresh_when etag: @user, public: true

The problem with that is that if you chance your html for the page, the cached page is no longer going to be valid. Therefor we need a way to invalidate the page/etag every time we change something.

One way to do that is to change RAILS_CACHE_ID every time you deploy as per
Etag busting on deployment .However doing that will results in all etags, for all the pages getting expired for every deployment.

I would rather have a solution where  I can expire individual tags, for individual pages.

I could generate my own etag with a version like this:
fresh_when etag: (@user.updated_at.to_s + "V1"), public: true

But this just doesn't feel like the "Rails way". Any more elegant solutions?

答:
If you are using Capistrano, or a deployment strategy where the Rails.root value changes on each deployment, you can add this to your application controller:

```<code>class ApplicationController < ActionController::Base

  # This causes http request caching to expire when we deploy.
  # The app is deployed /mnt/code/releases/<timestamp>
  etag { $etag_cache_control_fragement ||= Rails.root.to_s.split("/").last }
</code>```

Reference here: http://api.rubyonrails.org/v5.1/classes/ActionController/ConditionalGet/ClassMethods.html

Title: Expiring/busting Etag in Rails

Body:
If you are using Capistrano, or a deployment strategy where the Rails.root value changes on each deployment, you can add this to your application controller:

class ApplicationController < ActionController::Base

  # This causes http request caching to expire when we deploy.
  # The app is deployed /mnt/code/releases/<timestamp>
  etag { $etag_cache_control_fragement ||= Rails.root.to_s.split("/").last }

Reference here: http://api.rubyonrails.org/v5.1/classes/ActionController/ConditionalGet/ClassMethods.html


问:
What in code defines c++ version?
I am new to C++.  I compiled some code from boost/asio examples using g++.

I was successful only after using -std=c++14 at the g++ command line.
I understood then, and I may be wrong, that the boost/asio library uses C++14.

Then I tried to add code for encoding and decoding base64.

And I received a linker error:

undefined reference to base64_decode(std::__cxx11:basic.....

I understood by the error that I am passing a std:string in C++11 format and the linker does not find a reference in the files of a function that accepts an argument in that format.

But, where in the code can I see which format this method accepts?
If my code boost/asio have a std::string and I passed it to this function:

```<code>std::string base64_decode(std::string const& s)
</code>```

Why does the linker inform me that this parameter is a C++11 std::string?

How does this work?

Where, in the code, is the version of C++ being used?

This is the Base64 file I tried to add:

```<code>#ifndef _BASE64_H_
#define _BASE64_H_
#include <string>
std::string base64_encode(unsigned char const* , unsigned int len);
std::string base64_decode(std::string const& s);
#endif
</code>```

And this the cpp file

```<code>#include "base64.h"

static const std::string base64_chars =
             "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
             "abcdefghijklmnopqrstuvwxyz"
             "0123456789+/";

static inline bool is_base64(unsigned char c) {
  return (isalnum(c) || (c == '+') || (c == '/'));
}

std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
  std::string ret;
  int i = 0;
  int j = 0;
  unsigned char char_array_3[3];
  unsigned char char_array_4[4];

  while (in_len--) {
    char_array_3[i++] = *(bytes_to_encode++);
    if (i == 3) {
      char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
      char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
      char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
      char_array_4[3] = char_array_3[2] & 0x3f;

      for(i = 0; (i <4) ; i++)
        ret += base64_chars[char_array_4[i]];
      i = 0;
    }
  }

  if (i)
  {
    for(j = i; j < 3; j++)
      char_array_3[j] = '\0';

    char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
    char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
    char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
    char_array_4[3] = char_array_3[2] & 0x3f;

    for (j = 0; (j < i + 1); j++)
      ret += base64_chars[char_array_4[j]];

    while((i++ < 3))
      ret += '=';

  }

  return ret;

}

std::string base64_decode(std::string const& encoded_string) {
  size_t in_len = encoded_string.size();
  size_t i = 0;
  size_t j = 0;
  int in_ = 0;
  unsigned char char_array_4[4], char_array_3[3];
  std::string ret;

  while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
    char_array_4[i++] = encoded_string[in_]; in_++;
    if (i ==4) {
      for (i = 0; i <4; i++)
        char_array_4[i] = static_cast<unsigned char>(base64_chars.find(char_array_4[i]));

      char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
      char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
      char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

      for (i = 0; (i < 3); i++)
        ret += char_array_3[i];
      i = 0;
    }
  }

  if (i) {
    for (j = i; j <4; j++)
      char_array_4[j] = 0;

    for (j = 0; j <4; j++)
      char_array_4[j] = static_cast<unsigned char>(base64_chars.find(char_array_4[j]));

    char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
    char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
    char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

    for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
  }

  return ret;
}
</code>```

答:
The issue you are experiencing is caused by the fact that C++11 changed requirements to std::string (or more preceisly - std::basic_string) disallowing usage of copy-on-write semantics used by libstdc++ previously.

To adopt C++11, libstdc++ had to change layout of std::basic_string, breaking existing applications. To avoid this, C++11 strings use different name internally. In <bits/basic_string.h> you can find this macro:

```<code># define _GLIBCXX_BEGIN_NAMESPACE_CXX11 namespace __cxx11 {
</code>```

which is used in <string>. So the actual name of C++ std::string in libstdc++ starts with std::__cxx11::, not with std::.

Since libstdc++ provides both C++11 and C++98 versions of std::string, you need to make sure your code is consistent in its usage of this class - all code and libraries should use only one version to be interoperable e.g. everything should be build with either C++98/C++03 or with C++11 and newer. In short, you have to use -std=c++11, -std=c++14, -std=c++17 flags of compiler consistently.

Title: What in code defines c++ version?

Body:
I am new to C++.  I compiled some code from boost/asio examples using g++.

I was successful only after using -std=c++14 at the g++ command line.
I understood then, and I may be wrong, that the boost/asio library uses C++14.

Then I tried to add code for encoding and decoding base64.

And I received a linker error:

undefined reference to base64_decode(std::__cxx11:basic.....

I understood by the error that I am passing a std:string in C++11 format and the linker does not find a reference in the files of a function that accepts an argument in that format.

But, where in the code can I see which format this method accepts?
If my code boost/asio have a std::string and I passed it to this function:

std::string base64_decode(std::string const& s)

Why does the linker inform me that this parameter is a C++11 std::string?

How does this work?

Where, in the code, is the version of C++ being used?

This is the Base64 file I tried to add:

#ifndef _BASE64_H_
#define _BASE64_H_
#include <string>
std::string base64_encode(unsigned char const* , unsigned int len);
std::string base64_decode(std::string const& s);
#endif

And this the cpp file

#include "base64.h"

static const std::string base64_chars =
             "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
             "abcdefghijklmnopqrstuvwxyz"
             "0123456789+/";

static inline bool is_base64(unsigned char c) {
  return (isalnum(c) || (c == '+') || (c == '/'));
}

std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
  std::string ret;
  int i = 0;
  int j = 0;
  unsigned char char_array_3[3];
  unsigned char char_array_4[4];

  while (in_len--) {
    char_array_3[i++] = *(bytes_to_encode++);
    if (i == 3) {
      char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
      char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
      char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
      char_array_4[3] = char_array_3[2] & 0x3f;

      for(i = 0; (i <4) ; i++)
        ret += base64_chars[char_array_4[i]];
      i = 0;
    }
  }

  if (i)
  {
    for(j = i; j < 3; j++)
      char_array_3[j] = '\0';

    char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
    char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
    char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
    char_array_4[3] = char_array_3[2] & 0x3f;

    for (j = 0; (j < i + 1); j++)
      ret += base64_chars[char_array_4[j]];

    while((i++ < 3))
      ret += '=';

  }

  return ret;

}

std::string base64_decode(std::string const& encoded_string) {
  size_t in_len = encoded_string.size();
  size_t i = 0;
  size_t j = 0;
  int in_ = 0;
  unsigned char char_array_4[4], char_array_3[3];
  std::string ret;

  while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
    char_array_4[i++] = encoded_string[in_]; in_++;
    if (i ==4) {
      for (i = 0; i <4; i++)
        char_array_4[i] = static_cast<unsigned char>(base64_chars.find(char_array_4[i]));

      char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
      char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
      char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

      for (i = 0; (i < 3); i++)
        ret += char_array_3[i];
      i = 0;
    }
  }

  if (i) {
    for (j = i; j <4; j++)
      char_array_4[j] = 0;

    for (j = 0; j <4; j++)
      char_array_4[j] = static_cast<unsigned char>(base64_chars.find(char_array_4[j]));

    char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
    char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
    char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

    for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
  }

  return ret;
}

Body:
The issue you are experiencing is caused by the fact that C++11 changed requirements to std::string (or more preceisly - std::basic_string) disallowing usage of copy-on-write semantics used by libstdc++ previously.

To adopt C++11, libstdc++ had to change layout of std::basic_string, breaking existing applications. To avoid this, C++11 strings use different name internally. In <bits/basic_string.h> you can find this macro:

# define _GLIBCXX_BEGIN_NAMESPACE_CXX11 namespace __cxx11 {

which is used in <string>. So the actual name of C++ std::string in libstdc++ starts with std::__cxx11::, not with std::.

Since libstdc++ provides both C++11 and C++98 versions of std::string, you need to make sure your code is consistent in its usage of this class - all code and libraries should use only one version to be interoperable e.g. everything should be build with either C++98/C++03 or with C++11 and newer. In short, you have to use -std=c++11, -std=c++14, -std=c++17 flags of compiler consistently.


问:
Forward and Reverse Field Relationships in Django
The context is: I have a Match model where I want to store data for a football match. There are some fields are going to be common to all matches (not the value I mean the field name), such as season, local_team, away_team... But the stats of the match are going to differ (one match can have 2 goals and another one 0).

My approach to building a common abstract (Django model) of Match is creating the class Stats (to store the actions) and the Class Action. So:

Action will have fields --> minute, player, action(goal, red card...)

Stats will have fields --> actions (Many to many field to store several actions)

Match will have fields --> local, away, ref, stadium, stats (so all matches have 1 common field which is stats).

The big question comes now, when I would like to give a proper name to actions and stats. Because a lot of actions and stats from different matches are going to be stored together, when de MatchAdminForm ask me for the stats of the game I want to know quickly which one corresponds, same when the StatsAdminForm ask me for the actions.

The ideal for stats would be to catch the name of the local_team of the match which this stats belongs to. How can I access to that name if Match has not been created yet?? (Same parallelism with actions and stats)

Here I share my models.py so you can check.

```<code>from django.db import models
from django.utils import timezone

from globalModels.models import Season
from seasonalModels.models import SeasonTeam as Team
from seasonalModels.models import SeasonPlayer as Player
from seasonalModels.models import SeasonReferee as Referee
from seasonalModels.models import SeasonStadium as Stadium

class Action(models.Model):

    ACTION_CHOICES = (
        ('Gol', 'Gol'),
        ('Yellow', 'Yellow Card'),
        ('2Yellow', 'Second Yellow Card'),
        ('Red', 'Red Card'),
    )

    # minute = models.IntegerField(choices = (range(1,90)))
    name = models.CharField(max_length=255, default='abc')
    minute = models.IntegerField(default=0)
    player = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='player_action')
    action = models.CharField(choices=ACTION_CHOICES, max_length=255)

    def __str__(self):

        return "%s %s %s" % (Match.local_team, Match.away_team) # Ideally I will like the stat to give this information BUT MATCH DOESN'T EXISTE YET error

class Stats(models.Model):

    actions = models.ManyToManyField(Action, related_name='action_name')
    name = models.CharField(max_length=255, default='auto')

    def __str__(self):

        return "%s %s %s" % (Match.local_team, Match.away_team) # Ideally I will like the stat to give this information BUT MATCH DOESN'T EXISTE YET error

class Match(models.Model):

    season = models.ForeignKey(Season, on_delete=models.CASCADE, related_name='match_season')
    date = models.DateTimeField(default=timezone.now)
    # round = models.IntegerField(choices = (range(1,10)))
    round = models.IntegerField(default=0)
    number = models.IntegerField(default=0, unique=True)

    local_team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='match_local_team')
    away_team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='match_away_team')
    referee = models.ForeignKey(Referee, on_delete=models.CASCADE, related_name='match_referee')
    stadium = models.ForeignKey(Stadium, on_delete=models.CASCADE, related_name='match_stadium')

    local_team_possession = models.IntegerField(blank=True, null=True)
    away_team_possession = models.IntegerField(blank=True, null=True)

    stats = models.OneToOneField(Stats, blank=True, related_name='match_stats')

    local_team_goals = models.IntegerField(blank=True, null=True)
    away_team_goals = models.IntegerField(blank=True, null=True)
    local_team_yellow_cards = models.IntegerField(blank=True, null=True)
    local_team_red_cards = models.IntegerField(blank=True, null=True)
    away_team_yellow_cards = models.IntegerField(blank=True, null=True)
    away_team_red_cards = models.IntegerField(blank=True, null=True)
</code>```

Summarizing, when I am in the admin browser API and select ADD MATCH
In the stats field, I am able to ADD STATS (that are going to be stored in the corresponding match, but I would like to save a customized fieldname for the name field for stats, as well as the second case).

Thanks a lot in advance guys!

PR

答:
You would use the related_name to trace back through your specific instance. For example:

```<code>def __str__(self):
    return "%s %s %s" % (Match.local_team, Match.away_team)
</code>```

^ That refers to the Match class, not an instance.

Instead, you can use:

```<code>def __str__(self):
    return "{0} {1}".format(self.match_stats.local_team, self.match_stats.away_team)
</code>```

Body:
The context is: I have a Match model where I want to store data for a football match. There are some fields are going to be common to all matches (not the value I mean the field name), such as season, local_team, away_team... But the stats of the match are going to differ (one match can have 2 goals and another one 0).

My approach to building a common abstract (Django model) of Match is creating the class Stats (to store the actions) and the Class Action. So:

Action will have fields --> minute, player, action(goal, red card...)

Stats will have fields --> actions (Many to many field to store several actions)

Match will have fields --> local, away, ref, stadium, stats (so all matches have 1 common field which is stats).

The big question comes now, when I would like to give a proper name to actions and stats. Because a lot of actions and stats from different matches are going to be stored together, when de MatchAdminForm ask me for the stats of the game I want to know quickly which one corresponds, same when the StatsAdminForm ask me for the actions.

The ideal for stats would be to catch the name of the local_team of the match which this stats belongs to. How can I access to that name if Match has not been created yet?? (Same parallelism with actions and stats)

Here I share my models.py so you can check.

from django.db import models
from django.utils import timezone

from globalModels.models import Season
from seasonalModels.models import SeasonTeam as Team
from seasonalModels.models import SeasonPlayer as Player
from seasonalModels.models import SeasonReferee as Referee
from seasonalModels.models import SeasonStadium as Stadium

class Action(models.Model):

    ACTION_CHOICES = (
        ('Gol', 'Gol'),
        ('Yellow', 'Yellow Card'),
        ('2Yellow', 'Second Yellow Card'),
        ('Red', 'Red Card'),
    )

    # minute = models.IntegerField(choices = (range(1,90)))
    name = models.CharField(max_length=255, default='abc')
    minute = models.IntegerField(default=0)
    player = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='player_action')
    action = models.CharField(choices=ACTION_CHOICES, max_length=255)

    def __str__(self):

        return "%s %s %s" % (Match.local_team, Match.away_team) # Ideally I will like the stat to give this information BUT MATCH DOESN'T EXISTE YET error

class Stats(models.Model):

    actions = models.ManyToManyField(Action, related_name='action_name')
    name = models.CharField(max_length=255, default='auto')

    def __str__(self):

        return "%s %s %s" % (Match.local_team, Match.away_team) # Ideally I will like the stat to give this information BUT MATCH DOESN'T EXISTE YET error

class Match(models.Model):

    season = models.ForeignKey(Season, on_delete=models.CASCADE, related_name='match_season')
    date = models.DateTimeField(default=timezone.now)
    # round = models.IntegerField(choices = (range(1,10)))
    round = models.IntegerField(default=0)
    number = models.IntegerField(default=0, unique=True)

    local_team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='match_local_team')
    away_team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='match_away_team')
    referee = models.ForeignKey(Referee, on_delete=models.CASCADE, related_name='match_referee')
    stadium = models.ForeignKey(Stadium, on_delete=models.CASCADE, related_name='match_stadium')

    local_team_possession = models.IntegerField(blank=True, null=True)
    away_team_possession = models.IntegerField(blank=True, null=True)

    stats = models.OneToOneField(Stats, blank=True, related_name='match_stats')

    local_team_goals = models.IntegerField(blank=True, null=True)
    away_team_goals = models.IntegerField(blank=True, null=True)
    local_team_yellow_cards = models.IntegerField(blank=True, null=True)
    local_team_red_cards = models.IntegerField(blank=True, null=True)
    away_team_yellow_cards = models.IntegerField(blank=True, null=True)
    away_team_red_cards = models.IntegerField(blank=True, null=True)

Summarizing, when I am in the admin browser API and select ADD MATCH
In the stats field, I am able to ADD STATS (that are going to be stored in the corresponding match, but I would like to save a customized fieldname for the name field for stats, as well as the second case).

Thanks a lot in advance guys!

PR

Body:
You would use the related_name to trace back through your specific instance. For example:

def __str__(self):
    return "%s %s %s" % (Match.local_team, Match.away_team)

^ That refers to the Match class, not an instance.

Instead, you can use:

def __str__(self):
    return "{0} {1}".format(self.match_stats.local_team, self.match_stats.away_team)


问:
ClearCase: change branch type name?
I used mkbrtype BRANCH_NAME, checked out a few files, had some check-ins, etc. Now I discovered I had a typo in the branch name, and it looks pretty ugly. Is there a way I can change the branch name and still have all the versions/checkouts under it? I'm the only one using it.

答:
You can rename a brtype with the ct rename command.

```<code>cleartool rename brtype:oldname@\vob newname
</code>```

But you will need to:

change the config spec of your view (non-UCM): no side-effect on checked out files

or change the name of the stream, remove and recreate your view no the new Stream name (UCM). Your checked-out files still have their checked-out status, but you have to save their local modified content first to re-apply that content to the new view.

Title: ClearCase: change branch type name?

Body:
You can rename a brtype with the ct rename command.

cleartool rename brtype:oldname@\vob newname

But you will need to:

change the config spec of your view (non-UCM): no side-effect on checked out files

or change the name of the stream, remove and recreate your view no the new Stream name (UCM). Your checked-out files still have their checked-out status, but you have to save their local modified content first to re-apply that content to the new view.


问:
issue with image_tag when using html in helper
I have a situation where I need to insert a part of the html inside an existing html block so I am trying first to create this html and as it will be used in many places hence I am using an helper to create this fragment
But the image_tag is throwing errors and it works perfectly if directly used in the view

my helper code

```<code>def create_banner_html_helper(banner)

    if banner.logo.present?
      return "<div class='m3-news_wrap m3-mdcast-banner slide'>
    <a href='" + banner.link_url + "' target=_'blank'>
    <div class='m3-article'>

<div class='m3-section m3-img_holder'>"
      image_tag banner.logo(:small)
      "</div>
    <div class='m3-section m3-desc'>
         <h3 class='m3-title'>" + banner.title+ "</h3>
                    <p>" + banner.subtitle + "</p>
         <a href='" + banner.link_url + "' target='_blank'>" + banner.link_text + "</a>
                  </div>
                </div>
              </a>".html_safe

    end

    return "<div class='m3-news_wrap m3-mdcast-banner slide'>
    <a href='" + banner.link_url + "' target=_'blank'>
    <div class='m3-article'>

    <div class='m3-section m3-desc'>
         <h3 class='m3-title'>" + banner.title+ "</h3>
                    <p>" + banner.subtitle + "</p>
         <a href='" + banner.link_url + "' target='_blank'>" + banner.link_text + "</a>
                  </div>
                </div>
              </a>".html_safe
  end
</code>```

banner passed is an ActiveRecord object.

I really don't know what is the issue so any help will be highly appreciated

答:
Try calling your method with

```<code><%= create_banner_html_helper(banner).html_safe %>
</code>```

It should fix your problem of printing it directly as a string instead of html

Body:
I have a situation where I need to insert a part of the html inside an existing html block so I am trying first to create this html and as it will be used in many places hence I am using an helper to create this fragment
But the image_tag is throwing errors and it works perfectly if directly used in the view

my helper code

def create_banner_html_helper(banner)

    if banner.logo.present?
      return "

"
      image_tag banner.logo(:small)
      "

" + banner.title+ "

" + banner.subtitle + "

         " + banner.link_text + "

              ".html_safe

    end

    return "

" + banner.title+ "

" + banner.subtitle + "

         " + banner.link_text + "

              ".html_safe
  end

banner passed is an ActiveRecord object.

I really don't know what is the issue so any help will be highly appreciated

Body:
Try calling your method with

<%= create_banner_html_helper(banner).html_safe %>

It should fix your problem of printing it directly as a string instead of html


问:
broadcast receiver not received in IntentService
I am building a service to be able to catch intent from FirebaseMessagingService.

The first version I made use to do it at app level in the main activity but I do not want to handle it at this level anymore. I have created an intent service as below:

```<code>package com.seb.sebastien.appservices;

import android.app.IntentService;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.Context;
import android.content.IntentFilter;
import android.telephony.TelephonyManager;
import android.util.Log;

public class appsControlIntentService extends IntentService {
    public static final String REQUEST_MSG = "request";
    public static final String RESPONSE_MSG = "response";
    public static final String TAG = "appsControlIntentService";
    private String type_sim;

    public appsControlIntentService() {
        super("appsControlIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        boolean request = intent.getBooleanExtra(REQUEST_MSG, false);

        if(request == true) {
            sendResponse("Enable");
            handleAction(getCarrier());
            registerAllReceivers();
        }
        else if (request == false) {
            sendResponse("Disable");
            unRegisterAllReceivers();
            disableAction();
        }
        else
            Log.e(TAG, "Error msg");

    }
    ...

    /* Firebase and SIM */
    private BroadcastReceiver serviceBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "Broadcast received");
            if (intent.getExtras().getString(appFirebaseMessagingService.FIREBASE).equals(appFirebaseMessagingService.FIREBASE))
                type_sim = intent.getExtras().getString(appFirebaseMessagingService.SIM_TYPE);
            else if(intent.getExtras().getString(SimNotificationService.EXTRA_SIM_STATE) != null)
                Log.d(TAG, "Get something from Sim");
            else
                type_sim = null;

            if(type_sim != null){
                handleAction(type_sim);
            }
        }
    };

    private void registerAllReceivers(){
        Log.d(TAG, "Broadcast receiver register");
        registerReceiver(serviceBroadcastReceiver, new IntentFilter(appFirebaseMessagingService.INTENT_FILTER));
    }

    private void unRegisterAllReceivers() {
        if (serviceBroadcastReceiver != null) {
            unregisterReceiver(serviceBroadcastReceiver);
            serviceBroadcastReceiver = null;
        }
    }

    @Override
    public void onDestroy() {
        unRegisterAllReceivers();
        super.onDestroy();
    }

}
</code>```

this intent service register a broadcast receiver to be able to receive the firebase broadcast as shown below:

```<code>package com.seb.sebastien.appservices;

public class appFirebaseMessagingService extends FirebaseMessagingService {

    public static final String TAG = "appFirebaseMessagingService";
    public static final String INTENT_FILTER = "INTENT_FILTER";
    public static final String FIREBASE = "firebase";
    public static final String SIM_TYPE = "simtype";

    public appFirebaseMessagingService() {
    }

   /* @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    } */

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        String sim = null;

        Log.d(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            sim = remoteMessage.getNotification().getBody();
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

        Intent intent = new Intent(INTENT_FILTER);
        intent.putExtra(FIREBASE, FIREBASE);
        intent.putExtra(SIM_TYPE, sim );

        sendBroadcast(intent);

    }
}
</code>```

when debugging, I saw that we went until the sendBroadcast but nothing seems received in the "appControlIntentService" class event if I have registered the receiver.

Any idea why the broadcast is not received in the intentservice ?

答:
You should use alarm manager for broadcast receiver like this -</p>

```<code>AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        Intent alarmIntent = new Intent(MainActivity.this, BroadCastReciever.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1,
                alarmIntent, 0);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
                    + duration(in millisecond), pendingIntent);
        } else {
            alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
                    + in millisecond, pendingIntent);

        }
</code>```

Body:
I am building a service to be able to catch intent from FirebaseMessagingService.

The first version I made use to do it at app level in the main activity but I do not want to handle it at this level anymore. I have created an intent service as below:

package com.seb.sebastien.appservices;

import android.app.IntentService;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.Context;
import android.content.IntentFilter;
import android.telephony.TelephonyManager;
import android.util.Log;

public class appsControlIntentService extends IntentService {
    public static final String REQUEST_MSG = "request";
    public static final String RESPONSE_MSG = "response";
    public static final String TAG = "appsControlIntentService";
    private String type_sim;

    public appsControlIntentService() {
        super("appsControlIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        boolean request = intent.getBooleanExtra(REQUEST_MSG, false);

        if(request == true) {
            sendResponse("Enable");
            handleAction(getCarrier());
            registerAllReceivers();
        }
        else if (request == false) {
            sendResponse("Disable");
            unRegisterAllReceivers();
            disableAction();
        }
        else
            Log.e(TAG, "Error msg");

    }
    ...

    /* Firebase and SIM */
    private BroadcastReceiver serviceBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "Broadcast received");
            if (intent.getExtras().getString(appFirebaseMessagingService.FIREBASE).equals(appFirebaseMessagingService.FIREBASE))
                type_sim = intent.getExtras().getString(appFirebaseMessagingService.SIM_TYPE);
            else if(intent.getExtras().getString(SimNotificationService.EXTRA_SIM_STATE) != null)
                Log.d(TAG, "Get something from Sim");
            else
                type_sim = null;

            if(type_sim != null){
                handleAction(type_sim);
            }
        }
    };

    private void registerAllReceivers(){
        Log.d(TAG, "Broadcast receiver register");
        registerReceiver(serviceBroadcastReceiver, new IntentFilter(appFirebaseMessagingService.INTENT_FILTER));
    }

    private void unRegisterAllReceivers() {
        if (serviceBroadcastReceiver != null) {
            unregisterReceiver(serviceBroadcastReceiver);
            serviceBroadcastReceiver = null;
        }
    }

    @Override
    public void onDestroy() {
        unRegisterAllReceivers();
        super.onDestroy();
    }

}

this intent service register a broadcast receiver to be able to receive the firebase broadcast as shown below:

package com.seb.sebastien.appservices;

public class appFirebaseMessagingService extends FirebaseMessagingService {

    public static final String TAG = "appFirebaseMessagingService";
    public static final String INTENT_FILTER = "INTENT_FILTER";
    public static final String FIREBASE = "firebase";
    public static final String SIM_TYPE = "simtype";

    public appFirebaseMessagingService() {
    }

   /* @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    } */

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        String sim = null;

        Log.d(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            sim = remoteMessage.getNotification().getBody();
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

        Intent intent = new Intent(INTENT_FILTER);
        intent.putExtra(FIREBASE, FIREBASE);
        intent.putExtra(SIM_TYPE, sim );

        sendBroadcast(intent);

    }
}

when debugging, I saw that we went until the sendBroadcast but nothing seems received in the "appControlIntentService" class event if I have registered the receiver.

Any idea why the broadcast is not received in the intentservice ?

Body:
You should use alarm manager for broadcast receiver like this -

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        Intent alarmIntent = new Intent(MainActivity.this, BroadCastReciever.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1,
                alarmIntent, 0);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
                    + duration(in millisecond), pendingIntent);
        } else {
            alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
                    + in millisecond, pendingIntent);

        }


问:
How would I create a palindrome checker without if statements
I'm trying to create a programme like this previous one I've made;

It simply gives a boolean true/false on if a string backwards is still spelt the same way.

I've created this using if statements, but would like too know if it is possible too create using only methods and loops, and if so how? I have looked for duplicates, and there are similar posts that achieve what I have below, but everything I find uses if else statements

Any help appreciated as always; thanks.

```<code>import java.util.*;
public class testingthingsv24 {

private static Scanner in;

public static void main(String args[])
{
    in = new Scanner(System.in);
    System.out.println("Please Enter Your String: ");
    String n=in.nextLine();
    System.out.println("Your String Was: "+n);
    StringBuffer str=new StringBuffer(n);
    StringBuffer str2=new StringBuffer(str.reverse());
    String s2=new String(str2);
    System.out.println("Reversed Is: "+str2);
    if(n.equals(s2))
        System.out.println("ITS A PALINDROME");
    else
        System.out.println("ITS NOT A PALINDROME");
}
}
</code>```

Output:

```<code>Please Enter Your String:
dad
Your String Was: dad
Reversed Is: dad
ITS A PALINDROME
</code>```

答:
This can't really be achieved any more efficiently (as in using a method or function). The reason is that the if-statement:

```<code>if (n.equals(s2))
    System.out.println("ITS A PALINDROME");
else
    System.out.println("ITS NOT A PALINDROME");
</code>```

at the processor level would simply evaluate the statement: n.equals(s2) and then switch to the first println if true else go to the second println. If you think about this, there isn't really any optimisation that you can do as this condition will always have to be evaluated and always have to carry out the necessary task (printing).

However, having said that this is the most optimised solution for this part of your code, you can make the code slightly shorted and less bulky without a big if-else.

And to do that, the best solution IMO would be @shmosel's with a ternary expression. This would replace this if-else block with a simple line:

```<code>System.out.println(n.equals(s2) ? "ITS A PALINDROME" : "ITS NOT A PALINDROME");
</code>```

This works due to the general format of a ternary statement:

```<code>condition ? task if true : task if false
</code>```

Body:
I'm trying to create a programme like this previous one I've made;

It simply gives a boolean true/false on if a string backwards is still spelt the same way.

I've created this using if statements, but would like too know if it is possible too create using only methods and loops, and if so how? I have looked for duplicates, and there are similar posts that achieve what I have below, but everything I find uses if else statements

Any help appreciated as always; thanks.

import java.util.*;
public class testingthingsv24 {

private static Scanner in;

public static void main(String args[])
{
    in = new Scanner(System.in);
    System.out.println("Please Enter Your String: ");
    String n=in.nextLine();
    System.out.println("Your String Was: "+n);
    StringBuffer str=new StringBuffer(n);
    StringBuffer str2=new StringBuffer(str.reverse());
    String s2=new String(str2);
    System.out.println("Reversed Is: "+str2);
    if(n.equals(s2))
        System.out.println("ITS A PALINDROME");
    else
        System.out.println("ITS NOT A PALINDROME");
}
}

Output:

Please Enter Your String:
dad
Your String Was: dad
Reversed Is: dad
ITS A PALINDROME

Body:
This can't really be achieved any more efficiently (as in using a method or function). The reason is that the if-statement:

if (n.equals(s2))
    System.out.println("ITS A PALINDROME");
else
    System.out.println("ITS NOT A PALINDROME");

at the processor level would simply evaluate the statement: n.equals(s2) and then switch to the first println if true else go to the second println. If you think about this, there isn't really any optimisation that you can do as this condition will always have to be evaluated and always have to carry out the necessary task (printing).

However, having said that this is the most optimised solution for this part of your code, you can make the code slightly shorted and less bulky without a big if-else.

And to do that, the best solution IMO would be @shmosel's with a ternary expression. This would replace this if-else block with a simple line:

System.out.println(n.equals(s2) ? "ITS A PALINDROME" : "ITS NOT A PALINDROME");

This works due to the general format of a ternary statement:

condition ? task if true : task if false


问:
Breakpoint will not currently be hit. No executable code associated with this line
I have a class in a .h file:

```<code>class Blah
{
public:
    Blah(){}
    virtual ~Blah(){}

    void WriteMessage( bool MessageReceived )
    {
        if(MessageReceived)
        {
            cout << "Message Recieved\n";
        }
    }
};
</code>```

I was trying to figure out why my code isn't working, so I set a breakpoint on the conditional inside the WriteMessage() funcition, but as soon as I started running the project in debug mode the breakpoint faded out and the tooltip for it said:

Breakpoint will not currently be hit.

  No executable code associated with this line.

I have no idea why this is happening, because all of my other member functions for other classes work just fine when implemented in the .h file.  What is causing this?

Edit: Okay as requested, here's a stripped down version of the real code I'm working with:

VimbaBridgeAPI.h (header file for .dll)

```<code>#pragma once

#ifdef VIMBABRIDGEAPI_EXPORTS
#define VIMBABRIDGEAPI_API __declspec(dllexport)
#else
#define VIMBABRIDGEAPI_API __declspec(dllimport)
#endif

#include "AlCamIncludes.h"
#include "VimbaSystem.h"

////////////////////////////////////////////
//  Global Variables ///////////////////////
////////////////////////////////////////////
extern HBITMAP hbit;
extern CEdit* global_filenamehandle;

////////////////////////////////////////////
//  Global Flags ///////////////////////////
////////////////////////////////////////////
extern bool imageReady;
extern bool take_picture;

using namespace AVT::VmbAPI;

VIMBABRIDGEAPI_API void BridgedGetImage(FramePtr framepoint, VmbUchar_t** imgDat);

VIMBABRIDGEAPI_API HBITMAP ExternalFrameRecieved( const FramePtr pFrame );

//////////////////////////////////////////////////////////////////////////
//////////  MyObserver class   ///////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
class VIMBABRIDGEAPI_API MyObserver : public IFrameObserver
{
private:
    MyObserver( MyObserver& );

    MyObserver& operator=( const MyObserver& );

    //class member variables
    //BITMAPINFO*             pbmi;
    CEdit*                  m_filenameedit;

public:

    MyObserver(CameraPtr pCamera) : IFrameObserver(pCamera) {}
    virtual ~MyObserver() {}

    void FrameReceived ( const FramePtr pFrame );
};
</code>```

NOTE: IFrameObserver is not written by me, but the FrameReceived function is a pure virtual declared in the IFrameObserver class.  Their documentation says that FrameRecieved gets called by their API whenever a frame comes in, and I had to implement the function.  I have tested this functions and it works, but only when defined outside the class (inside I get the error I'm getting now)

VimbaBridgeAPI.cpp (code hidden from user)

```<code>void FrameRecieved( const FramePtr pFrame )
{
    DbgMsg(L"Frame Received\n");

    ////////////////////////////////////////////////////////////////////////
    //////////  Setup Bitmap  ////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////

    //// FILEHEADER ////
    BITMAPFILEHEADER* bf = new BITMAPFILEHEADER;
    bf->bfType = 0x4d42;
    bf->bfSize = 6054400 + 54 + sizeof(BITMAPINFO);
    bf->bfOffBits = 54;

    //// INFOHEADER ////
    BITMAPINFOHEADER* bih = new BITMAPINFOHEADER;
    bih->biSize = 40;
    bih->biWidth = 2752;
    bih->biHeight = -2200;
    bih->biPlanes = 1;
    bih->biBitCount = 32;
    bih->biCompression = 0;
    //bi->biSizeImage = 6054400; //not required
    bih->biXPelsPerMeter = 2835;
    bih->biYPelsPerMeter = 2835;
    bih->biClrUsed = 0;
    bih->biClrImportant = 0;

    //// INFO ////
    BITMAPINFO* pbmi = (BITMAPINFO*)alloca( sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD)*256);
    pbmi->bmiHeader.biSize = sizeof (pbmi->bmiHeader);
    pbmi->bmiHeader.biWidth = 2752;
    pbmi->bmiHeader.biHeight = -2200;
    pbmi->bmiHeader.biPlanes = 1;
    pbmi->bmiHeader.biBitCount = 8;
    pbmi->bmiHeader.biCompression = BI_RGB;
    pbmi->bmiHeader.biSizeImage = 0;
    pbmi->bmiHeader.biXPelsPerMeter = 14173;
    pbmi->bmiHeader.biYPelsPerMeter = 14173;
    pbmi->bmiHeader.biClrUsed = 0;
    pbmi->bmiHeader.biClrImportant = 0;

    //create grayscale color palette
    for(int i=0; i<256; i++)
    {
        pbmi->bmiColors[i].rgbRed = BYTE(i);
        pbmi->bmiColors[i].rgbGreen = BYTE(i);
        pbmi->bmiColors[i].rgbBlue = BYTE(i);
        pbmi->bmiColors[i].rgbReserved = BYTE(0);
    }

    //// IMAGE DATA ////
    VmbUchar_t* imageData = NULL;
    BridgedGetImage(pFrame, &imageData);

    //////////////////////////////////////////////////////////////////////////
    ////// Create image that's printed to dialog box /////////////////////////
    //////////////////////////////////////////////////////////////////////////
    HDC hdc = ::GetDC(NULL);
    hbit = CreateDIBitmap(hdc, bih, CBM_INIT, imageData, pbmi, DIB_RGB_COLORS);

    //clean up
    DeleteObject(bf);
    DeleteObject(bih);
    DeleteObject(hdc);
}
</code>```

答: I also wanted to chime in with my own solution. I had a C++ project loading a dll that consisted of C++/CLR code. Turns out, I had to set the startup project's debugger type to "Mixed". "Auto" wasn't detecting that it needed managed support because the dll was loaded manually after the program started.</p>

Body:
I have a class in a .h file:

class Blah
{
public:
    Blah(){}
    virtual ~Blah(){}

    void WriteMessage( bool MessageReceived )
    {
        if(MessageReceived)
        {
            cout << "Message Recieved\n";
        }
    }
};

I was trying to figure out why my code isn't working, so I set a breakpoint on the conditional inside the WriteMessage() funcition, but as soon as I started running the project in debug mode the breakpoint faded out and the tooltip for it said:

Breakpoint will not currently be hit.

  No executable code associated with this line.

I have no idea why this is happening, because all of my other member functions for other classes work just fine when implemented in the .h file.  What is causing this?

Edit: Okay as requested, here's a stripped down version of the real code I'm working with:

VimbaBridgeAPI.h (header file for .dll)

#pragma once

#ifdef VIMBABRIDGEAPI_EXPORTS
#define VIMBABRIDGEAPI_API __declspec(dllexport)
#else
#define VIMBABRIDGEAPI_API __declspec(dllimport)
#endif

#include "AlCamIncludes.h"
#include "VimbaSystem.h"

////////////////////////////////////////////
//  Global Variables ///////////////////////
////////////////////////////////////////////
extern HBITMAP hbit;
extern CEdit* global_filenamehandle;

////////////////////////////////////////////
//  Global Flags ///////////////////////////
////////////////////////////////////////////
extern bool imageReady;
extern bool take_picture;

using namespace AVT::VmbAPI;

VIMBABRIDGEAPI_API void BridgedGetImage(FramePtr framepoint, VmbUchar_t** imgDat);

VIMBABRIDGEAPI_API HBITMAP ExternalFrameRecieved( const FramePtr pFrame );

//////////////////////////////////////////////////////////////////////////
//////////  MyObserver class   ///////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
class VIMBABRIDGEAPI_API MyObserver : public IFrameObserver
{
private:
    MyObserver( MyObserver& );

    MyObserver& operator=( const MyObserver& );

    //class member variables
    //BITMAPINFO*             pbmi;
    CEdit*                  m_filenameedit;

public:

    MyObserver(CameraPtr pCamera) : IFrameObserver(pCamera) {}
    virtual ~MyObserver() {}

    void FrameReceived ( const FramePtr pFrame );
};

NOTE: IFrameObserver is not written by me, but the FrameReceived function is a pure virtual declared in the IFrameObserver class.  Their documentation says that FrameRecieved gets called by their API whenever a frame comes in, and I had to implement the function.  I have tested this functions and it works, but only when defined outside the class (inside I get the error I'm getting now)

VimbaBridgeAPI.cpp (code hidden from user)

void FrameRecieved( const FramePtr pFrame )
{
    DbgMsg(L"Frame Received\n");

    ////////////////////////////////////////////////////////////////////////
    //////////  Setup Bitmap  ////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////

    //// FILEHEADER ////
    BITMAPFILEHEADER* bf = new BITMAPFILEHEADER;
    bf->bfType = 0x4d42;
    bf->bfSize = 6054400 + 54 + sizeof(BITMAPINFO);
    bf->bfOffBits = 54;

    //// INFOHEADER ////
    BITMAPINFOHEADER* bih = new BITMAPINFOHEADER;
    bih->biSize = 40;
    bih->biWidth = 2752;
    bih->biHeight = -2200;
    bih->biPlanes = 1;
    bih->biBitCount = 32;
    bih->biCompression = 0;
    //bi->biSizeImage = 6054400; //not required
    bih->biXPelsPerMeter = 2835;
    bih->biYPelsPerMeter = 2835;
    bih->biClrUsed = 0;
    bih->biClrImportant = 0;

    //// INFO ////
    BITMAPINFO* pbmi = (BITMAPINFO*)alloca( sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD)*256);
    pbmi->bmiHeader.biSize = sizeof (pbmi->bmiHeader);
    pbmi->bmiHeader.biWidth = 2752;
    pbmi->bmiHeader.biHeight = -2200;
    pbmi->bmiHeader.biPlanes = 1;
    pbmi->bmiHeader.biBitCount = 8;
    pbmi->bmiHeader.biCompression = BI_RGB;
    pbmi->bmiHeader.biSizeImage = 0;
    pbmi->bmiHeader.biXPelsPerMeter = 14173;
    pbmi->bmiHeader.biYPelsPerMeter = 14173;
    pbmi->bmiHeader.biClrUsed = 0;
    pbmi->bmiHeader.biClrImportant = 0;

    //create grayscale color palette
    for(int i=0; i<256; i++)
    {
        pbmi->bmiColors[i].rgbRed = BYTE(i);
        pbmi->bmiColors[i].rgbGreen = BYTE(i);
        pbmi->bmiColors[i].rgbBlue = BYTE(i);
        pbmi->bmiColors[i].rgbReserved = BYTE(0);
    }

    //// IMAGE DATA ////
    VmbUchar_t* imageData = NULL;
    BridgedGetImage(pFrame, &imageData);

    //////////////////////////////////////////////////////////////////////////
    ////// Create image that's printed to dialog box /////////////////////////
    //////////////////////////////////////////////////////////////////////////
    HDC hdc = ::GetDC(NULL);
    hbit = CreateDIBitmap(hdc, bih, CBM_INIT, imageData, pbmi, DIB_RGB_COLORS);

    //clean up
    DeleteObject(bf);
    DeleteObject(bih);
    DeleteObject(hdc);
}


问:
Angular - detecting when two subscriptions have updated
In a component, in ngOnInit() I've got two subscriptions to a data service. I want to do some processing once both subscriptions have returned. Whats the best way to do this? I can just process at the end of each, this just seems a little inefficient and won't work for which ever subscription activates first,

Thanks,

Component.TS

```<code>ngOnInit()
{
  this.dataService.dataA().subscribe((dataAJSON) =>
 {
   this.dataA= dataAJSON
 }

 this.dataService.dataB().subscribe((dataBJSON) =>
 {
   this.dataB= dataBJSON
 }
</code>```

DataService

```<code>import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()

export class PMDataService
{
  constructor(public http : Http)
  {

  }

  dataA()
  {

    var dataA: any;
    var json;

    dataA= this.http.get("./assets/dataa.json")
      .map(res => res.json());

    return dataA
  }

  dataB()
  {

    var dataB: any;
    var json;

    dataB= this.http.get("./assets/datab.json")
      .map(res => res.json());

    return dataB
  }

}
</code>```

答:
The method used depends on how you want to receive the data:

You can use the zip function.  Emits once when all have emitted once. So similar to Promise.all except not on completion.

```<code>Observable.zip(obs1, obs2).subscribe((val) => { ... });
</code>```

You can use the forkJoin function.  Emits once when all have completed. So exactly like Promise.all.

```<code>Observable.forkJoin(obs1, obs2).subscribe((val) => { ... });
</code>```

You can use the merge function. Emits in order of emission so could be 1st then 2nd or 2nd then 1st:

```<code>obs1.merge(obs2).subscribe((val) => { ... });
</code>```

You can use concat function.  Emits in order 1st then 2nd regardless if 2nd emits first:

```<code>obs1.concat(obs2).subscribe((val) => { ... });
</code>```

It's best practice to split these up into a couple lines for clarity.

```<code>const obs1 = Rx.Observable.of(1,2,3);
const obs2 = Rx.Observable.of(1,2,3);
const example = Observable.zip(obs1, obs2);
//const example = Observable.forkJoin(obs1, obs2);
//const example = obs1.merge(obs2);
//const example = obs1.concat(obs2);
example.subscribe(val => { ... });
</code>```

Body:
In a component, in ngOnInit() I've got two subscriptions to a data service. I want to do some processing once both subscriptions have returned. Whats the best way to do this? I can just process at the end of each, this just seems a little inefficient and won't work for which ever subscription activates first,

Thanks,

Component.TS

ngOnInit()
{
  this.dataService.dataA().subscribe((dataAJSON) =>
 {
   this.dataA= dataAJSON
 }

 this.dataService.dataB().subscribe((dataBJSON) =>
 {
   this.dataB= dataBJSON
 }

DataService

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()

export class PMDataService
{
  constructor(public http : Http)
  {

  }

  dataA()
  {

    var dataA: any;
    var json;

    dataA= this.http.get("./assets/dataa.json")
      .map(res => res.json());

    return dataA
  }

  dataB()
  {

    var dataB: any;
    var json;

    dataB= this.http.get("./assets/datab.json")
      .map(res => res.json());

    return dataB
  }

}

Body:
The method used depends on how you want to receive the data:

You can use the zip function.  Emits once when all have emitted once. So similar to Promise.all except not on completion.

Observable.zip(obs1, obs2).subscribe((val) => { ... });

You can use the forkJoin function.  Emits once when all have completed. So exactly like Promise.all.

Observable.forkJoin(obs1, obs2).subscribe((val) => { ... });

You can use the merge function. Emits in order of emission so could be 1st then 2nd or 2nd then 1st:

obs1.merge(obs2).subscribe((val) => { ... });

You can use concat function.  Emits in order 1st then 2nd regardless if 2nd emits first:

obs1.concat(obs2).subscribe((val) => { ... });

It's best practice to split these up into a couple lines for clarity.

const obs1 = Rx.Observable.of(1,2,3);
const obs2 = Rx.Observable.of(1,2,3);
const example = Observable.zip(obs1, obs2);
//const example = Observable.forkJoin(obs1, obs2);
//const example = obs1.merge(obs2);
//const example = obs1.concat(obs2);
example.subscribe(val => { ... });


问:
Python saying variable mentioned before assignment when it is assigned in the for loop it's nested in?
EDIT
Well I'm an idiot for deleting the thing I'm looping through. Thanks y'all.

I've tried looking up answers but honestly this is just boggling me.

I have a for loop which loops through lists in a list, but then in an if statement nested into the for loop it says the thing it is looping with is not defined?

```<code>for monster in self.monsters:
    print("google chrome")
    if monster[1][1] <= 0:
        self.exp_gotten += monster[1][8]
        for j in self.turns:
            if j[0] == monster[1][0]:
                del j
                self.defeated_monsters.append(monster)
                del monster
</code>```

self.monsters is a list containing other lists for the monsters. The lists are like ["Monster Name", [monster_id, hp, mp, ...]]. Monster[1][1] is the HP stat, and it checks if it is smaller than 0, indicating its been defeated. It then adds the exp, then deletes the monster from the turns list, adds it to the list of defeated monsters, then deletes the monster itself.
 Except when it comes to this part, I keep getting "monster variable referenced before assignment"

```<code>File "C:\Users\Admin\Documents\Dave's stuff\Python\COURSEWORK\battle.py", line 150, in check_if_fin
    if j[0] == monster[1][0]:
UnboundLocalError: local variable 'monster' referenced before assignment
</code>```

I just don't get what I'm doing wrong.

答:
Your inner for loop deletes the monster variable:

```<code>    for j in self.turns:
        if j[0] == monster[1][0]:
            del j
            self.defeated_monsters.append(monster)
            del monster
            ^^^^^^^^^^^
</code>```

If self.turns contains more than one element and and anything but the last enters the if block, you'll delete monster and get that error. You probably want to throw in a break statement or otherwise exit the loop if you're done.

It's tricky to remove objects from a list that you're currently iterating over. One solution would be to use intermediate lists:

```<code>new_monsters = []

for monster in self.monsters:
    # It's usually clearer to remove unnecessarily nested `if` statements
    if monster[1][1] > 0:
        continue

    self.exp_gotten += monster[1][8]

    for j in self.turns:
        if j[0] == monster[1][0]:
            self.defeated_monsters.append(monster)

            break  # Don't continue checking, you've already defeated the monster
    else:
        # We never broke out of the above loop, so we never defeated the monster
        new_monsters.append(monster)

self.monsters = new_monsters
</code>```

Finally, code like monster[1][8] and monster[1][1] is really difficult to manage. Consider setting up your monster as a class with descriptive attributes or at the very least a namedtuple. That way, you can use monster.exp instead of monster[1][8].

Body:
EDIT
Well I'm an idiot for deleting the thing I'm looping through. Thanks y'all.

I've tried looking up answers but honestly this is just boggling me.

I have a for loop which loops through lists in a list, but then in an if statement nested into the for loop it says the thing it is looping with is not defined?

for monster in self.monsters:
    print("google chrome")
    if monster[1][1] <= 0:
        self.exp_gotten += monster[1][8]
        for j in self.turns:
            if j[0] == monster[1][0]:
                del j
                self.defeated_monsters.append(monster)
                del monster

self.monsters is a list containing other lists for the monsters. The lists are like ["Monster Name", [monster_id, hp, mp, ...]]. Monster[1][1] is the HP stat, and it checks if it is smaller than 0, indicating its been defeated. It then adds the exp, then deletes the monster from the turns list, adds it to the list of defeated monsters, then deletes the monster itself.
 Except when it comes to this part, I keep getting "monster variable referenced before assignment"

File "C:\Users\Admin\Documents\Dave's stuff\Python\COURSEWORK\battle.py", line 150, in check_if_fin
    if j[0] == monster[1][0]:
UnboundLocalError: local variable 'monster' referenced before assignment

I just don't get what I'm doing wrong.

Body:
Your inner for loop deletes the monster variable:

    for j in self.turns:
        if j[0] == monster[1][0]:
            del j
            self.defeated_monsters.append(monster)
            del monster
            ^^^^^^^^^^^

If self.turns contains more than one element and and anything but the last enters the if block, you'll delete monster and get that error. You probably want to throw in a break statement or otherwise exit the loop if you're done.

It's tricky to remove objects from a list that you're currently iterating over. One solution would be to use intermediate lists:

new_monsters = []

for monster in self.monsters:
    # It's usually clearer to remove unnecessarily nested `if` statements
    if monster[1][1] > 0:
        continue

    self.exp_gotten += monster[1][8]

    for j in self.turns:
        if j[0] == monster[1][0]:
            self.defeated_monsters.append(monster)

            break  # Don't continue checking, you've already defeated the monster
    else:
        # We never broke out of the above loop, so we never defeated the monster
        new_monsters.append(monster)

self.monsters = new_monsters

Finally, code like monster[1][8] and monster[1][1] is really difficult to manage. Consider setting up your monster as a class with descriptive attributes or at the very least a namedtuple. That way, you can use monster.exp instead of monster[1][8].