问:
Adding another line to a existing PHP Contact form
I'm working on a simple single page site from a template. The contact from had only name email and message body. I tried adding the number. It shows up on the page, and the line shows up in the email, but the number does not actually come through.

Ive copied and pasted the existing code for one of the other data points and changed the id, type etc. for the phone number.

The page is live on test.wotactical.com

EDIT: Added the javascript code

PHP

```<code><?php

// Put contacting email here
$php_main_email = "ffl@wotactical.com";
$php_sending_email = "contact@wotactical.com";

//Fetching Values from URL
$php_name = $_POST['ajax_name'];
$php_email = $_POST['ajax_email'];
$php_phone = $_POST['ajax_phone'];
$php_message = $_POST['ajax_message'];

//Sanitizing email
$php_email = filter_var($php_email, FILTER_SANITIZE_EMAIL);

//After sanitization Validation is performed
if (filter_var($php_email, FILTER_VALIDATE_EMAIL)) {

        $php_subject = "New WOtactical contact form from " . $php_name;

        // To send HTML mail, the Content-type header must be set
        $php_headers = 'MIME-Version: 1.0' . "\r\n";
        $php_headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
        $php_headers .= 'From:' . $php_sending_email. "\r\n"; // Sender's Email
        $php_headers .= 'Cc:' . $php_email. "\r\n"; // Carbon copy to Sender

        $php_template = '<div style="padding:50px;">Hello ' . $php_name . ',<br/>'
        . 'Thank you for contacting us.<br/><br/>'
        . '<strong style="color:#f00a77;">Name:</strong>  ' . $php_name . '<br/>'
        . '<strong style="color:#f00a77;">Number:</strong>  ' . $php_phone . '<br/>'
        . '<strong style="color:#f00a77;">Email:</strong>  ' . $php_email . '<br/>'
        . '<strong style="color:#f00a77;">Message:</strong>  ' . $php_message . '<br/><br/>'
        . 'This is a Contact Confirmation mail.'
        . '<br/>'
        . 'We will contact you as soon as possible .</div>';
        $php_sendmessage = "<div style=\"background-color:#f5f5f5; color:#333;\">" . $php_template . "</div>";

        // message lines should not exceed 70 characters (PHP rule), so wrap it
        $php_sendmessage = wordwrap($php_sendmessage, 70);

        // Send mail by PHP Mail Function
        mail($php_main_email, $php_subject, $php_sendmessage, $php_headers);
        echo "";

} else {
    echo "<span class='contact_error'>* Invalid email *</span>";
}

?>
</code>```

HTML

```<code>        <!-- CONTACT1 -->
        <div class="edina_tm_section" id="contact">
            <div class="edina_tm_main_title_holder_wrap contact">
                <div class="number_wrap">
                    <span>06</span>
                </div>
                <div class="title_wrap">
                    <span>Contact Form</span>
                </div>
            </div>
            <div class="edina_tm_contact_wrap">
                <div class="short_info">
                    <div class="container">
                        <div class="subtitle">
                            <p class="wow fadeIn" data-wow-duration="1.2s">Special order, FFL Transfer, consignment or just have questions? We're happy to help.</p>
                        </div>
                    </div>
                </div>
                <div class="main_input_wrap">
                    <form action="/" method="post" class="contact_form" id="contact_form">
                        <div class="returnmessage" data-success="Your message has been received, We will contact you soon."></div>
                        <div class="empty_notice"><span>Please Fill Required Fields</span></div>
                        <div class="wrap wow fadeIn" data-wow-duration="1.2s" data-wow-delay="0.2s">
                            <input id="name" type="text" placeholder="Your Name">
                        </div>
                        <div class="wrap wow fadeIn" data-wow-duration="1.2s" data-wow-delay="0.4s">
                            <input id="email" type="text" placeholder="Your Email">
                        </div>
                        <div class="wrap wow fadeIn" data-wow-duration="1.2s" data-wow-delay="0.4s">
                            <input id="phone" type="tel" placeholder="Contact Number ex 123-456-7890" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
                        required>
                        </div>
                        <div class="wrap wow fadeIn" data-wow-duration="1.2s" data-wow-delay="0.6s">
                            <textarea id="message" placeholder="Type of inquiry, and/or details"></textarea>
                        </div>
                        <div class="edina_tm_button wow fadeIn" data-wow-duration="1.2s" data-wow-delay="0.8s">
                            <a id="send_message" href="#">Send Message</a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <!-- /CONTACT1 -->
</code>```

javascript

```<code>// -----------------------------------------------------
// ----------------    CONTACT FORM    -----------------
// -----------------------------------------------------

function edina_tm_contact_form(){

    "use strict";

    jQuery(".contact_form #send_message").on('click', function(){

        var name        = jQuery(".contact_form #name").val();
        var email       = jQuery(".contact_form #email").val();
        var phone       = jQuery(".contact_form #phone").val();
        var message     = jQuery(".contact_form #message").val();
        var subject     = jQuery(".contact_form #subject").val();
        var success     = jQuery(".contact_form .returnmessage").data('success');

        jQuery(".contact_form .returnmessage").empty(); //To empty previous error/success message.
        //checking for blank fields
        if(name===''||email===''||phone===''||message===''){

            jQuery('div.empty_notice').slideDown(500).delay(2000).slideUp(500);
        }
        else{
            // Returns successful data submission message when the entered information is stored in database.
            jQuery.post("modal/contact.php",{ ajax_name: name, ajax_email: email, ajax_phone: phone, ajax_message:message, ajax_subject: subject}, function(data) {

                jQuery(".contact_form .returnmessage").append(data);//Append returned message to message paragraph

                if(jQuery(".contact_form .returnmessage span.contact_error").length){
                    jQuery(".contact_form .returnmessage").slideDown(500).delay(2000).slideUp(500);
                }else{
                    jQuery(".contact_form .returnmessage").append("<span class='contact_success'>"+ success +"</span>");
                    jQuery(".contact_form .returnmessage").slideDown(500).delay(4000).slideUp(500);
                }

                if(data===""){
                    jQuery("#contact_form")[0].reset();//To reset form fields on success
                }

            });
        }
        return false;
    });
}

</code>```

答:
I'm guessing that if you might remove your regex pattern:

```<code>pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
</code>```

here in this element:

```<code><div class="wrap wow fadeIn" data-wow-duration="1.2s" data-wow-delay="0.4s">
    <input id="phone" type="tel" placeholder="Contact Number ex 123-456-7890" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
required>
</code>```

and change it to just:

```<code><div class="wrap wow fadeIn" data-wow-duration="1.2s" data-wow-delay="0.4s">
    <input id="phone" type="tel" placeholder="Contact Number ex 123-456-7890" required>
</code>```

and test it, it would likely work. Or you might just test it with a 888-888-8888 number and see if it would work.

Body:
I'm working on a simple single page site from a template. The contact from had only name email and message body. I tried adding the number. It shows up on the page, and the line shows up in the email, but the number does not actually come through.

Ive copied and pasted the existing code for one of the other data points and changed the id, type etc. for the phone number.

The page is live on test.wotactical.com

EDIT: Added the javascript code

PHP

<?php

// Put contacting email here
$php_main_email = "ffl@wotactical.com";
$php_sending_email = "contact@wotactical.com";

//Fetching Values from URL
$php_name = $_POST['ajax_name'];
$php_email = $_POST['ajax_email'];
$php_phone = $_POST['ajax_phone'];
$php_message = $_POST['ajax_message'];

//Sanitizing email
$php_email = filter_var($php_email, FILTER_SANITIZE_EMAIL);

//After sanitization Validation is performed
if (filter_var($php_email, FILTER_VALIDATE_EMAIL)) {

        $php_subject = "New WOtactical contact form from " . $php_name;

        // To send HTML mail, the Content-type header must be set
        $php_headers = 'MIME-Version: 1.0' . "\r\n";
        $php_headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
        $php_headers .= 'From:' . $php_sending_email. "\r\n"; // Sender's Email
        $php_headers .= 'Cc:' . $php_email. "\r\n"; // Carbon copy to Sender

        $php_template = '
Hello ' . $php_name . ',
'
        . 'Thank you for contacting us.

'
        . 'Name:  ' . $php_name . '
'
        . 'Number:  ' . $php_phone . '
'
        . 'Email:  ' . $php_email . '
'
        . 'Message:  ' . $php_message . '

'
        . 'This is a Contact Confirmation mail.'
        . '
'
        . 'We will contact you as soon as possible .
';
        $php_sendmessage = "
" . $php_template . "
";

        // message lines should not exceed 70 characters (PHP rule), so wrap it
        $php_sendmessage = wordwrap($php_sendmessage, 70);

        // Send mail by PHP Mail Function
        mail($php_main_email, $php_subject, $php_sendmessage, $php_headers);
        echo "";

} else {
    echo "* Invalid email *";
}

?>

HTML

                    06

                    Contact Form

Special order, FFL Transfer, consignment or just have questions? We're happy to help.

                    <form action="/" method="post" class="contact_form" id="contact_form">

Please Fill Required Fields

                            <input id="name" type="text" placeholder="Your Name">

                            <input id="email" type="text" placeholder="Your Email">

                            <input id="phone" type="tel" placeholder="Contact Number ex 123-456-7890" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
                        required>

                            <textarea id="message" placeholder="Type of inquiry, and/or details"></textarea>

                            Send Message

                    </form>

javascript

// -----------------------------------------------------
// ----------------    CONTACT FORM    -----------------
// -----------------------------------------------------

function edina_tm_contact_form(){

    "use strict";

    jQuery(".contact_form #send_message").on('click', function(){

        var name        = jQuery(".contact_form #name").val();
        var email       = jQuery(".contact_form #email").val();
        var phone       = jQuery(".contact_form #phone").val();
        var message     = jQuery(".contact_form #message").val();
        var subject     = jQuery(".contact_form #subject").val();
        var success     = jQuery(".contact_form .returnmessage").data('success');

        jQuery(".contact_form .returnmessage").empty(); //To empty previous error/success message.
        //checking for blank fields
        if(name===''||email===''||phone===''||message===''){

            jQuery('div.empty_notice').slideDown(500).delay(2000).slideUp(500);
        }
        else{
            // Returns successful data submission message when the entered information is stored in database.
            jQuery.post("modal/contact.php",{ ajax_name: name, ajax_email: email, ajax_phone: phone, ajax_message:message, ajax_subject: subject}, function(data) {

                jQuery(".contact_form .returnmessage").append(data);//Append returned message to message paragraph

                if(jQuery(".contact_form .returnmessage span.contact_error").length){
                    jQuery(".contact_form .returnmessage").slideDown(500).delay(2000).slideUp(500);
                }else{
                    jQuery(".contact_form .returnmessage").append(""+ success +"");
                    jQuery(".contact_form .returnmessage").slideDown(500).delay(4000).slideUp(500);
                }

                if(data===""){
                    jQuery("#contact_form")[0].reset();//To reset form fields on success
                }

            });
        }
        return false;
    });
}

Body:
I'm guessing that if you might remove your regex pattern:

pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"

here in this element:

<div class="wrap wow fadeIn" data-wow-duration="1.2s" data-wow-delay="0.4s">
    <input id="phone" type="tel" placeholder="Contact Number ex 123-456-7890" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
required>

and change it to just:

<div class="wrap wow fadeIn" data-wow-duration="1.2s" data-wow-delay="0.4s">
    <input id="phone" type="tel" placeholder="Contact Number ex 123-456-7890" required>

and test it, it would likely work. Or you might just test it with a 888-888-8888 number and see if it would work.


来源: stackexchange

问:
MySQL Where Clause Issues
```<code>SELECT `location`.`building`, `location`.`classroom` FROM `schools`
LEFT OUTER JOIN `location`
ON `location`.`location_serial` = `classroom`.`location_serial`
LEFT OUTER JOIN `rack_info`
ON `classroom_info`.`location_serial` = `classroom`.`location_serial`
WHERE (
    (((`location`.`building` LIKE 'SCH%')))
    AND
    (`classroom_info`.`status` NOT IN (1, 2))
    AND
    (
        (
            (`location`.`building` = 'SCH1' AND `location`.`classroom` != '99')
            AND
            (`location`.`building` = 'SCH1' AND `location`.`classroom` != '34')
        )
    )
)
</code>```

I'm having a problem in my WHERE clause.

Let's say location.building can be SCH1, SCH2, SCH3, SCH4, CAB1, CAB2. I'm trying to select all of the SCH classrooms, where some classroom statuses are 1 & 2.

This all works fine

The problem arises when I try to further filter my results to exclude instances when the building is SCH1 and the classroom ID is 99, and when the building is SCH1 and the classroom ID is 34. I want to show all other classrooms across all SCH buildings (including SCH1, e.g. SCH1.98) but exclude the two specific classrooms mentioned in the SQL query above (SCH1.99 and SCH1.34)

I may also want to exclude other SCH rooms, like SCH2.24, SCH3.33 - but I want all the other classrooms to appear.

I've been looking for hours and I think I've reached the limits of my ability - all help welcome.

答:
To "exclude instances when the building is SCH1 and the classroom ID is 99, and when the building is SCH1 and the classroom ID is 34" you can check that the building isn't 'SCH1' or (especially when the building is 'SCH1') the classroom ID is not in '34' or '99'. (Assuming the classroom ID is a varchar, otherwise you can drop the single quotes.)

```<code>SELECT `location`.`building`,
       `location`.`classroom`
       FROM `schools`
            LEFT OUTER JOIN `location`
                            ON `location`.`location_serial` = `classroom`.`location_serial`
            LEFT OUTER JOIN `rack_info`
                            ON `classroom_info`.`location_serial` = `classroom`.`location_serial`
       WHERE `location`.`building` LIKE 'SCH%'
             AND `classroom_info`.`status` NOT IN (1,
                                                   2)
             AND (`location`.`building` <> 'SCH1'
                   OR `location`.`classroom` NOT IN ('34',
                                                     '99'));
</code>```

ContentLicense: CC BY-SA 4.0

Title: MySQL Where Clause Issues

Body:
SELECT `location`.`building`, `location`.`classroom` FROM `schools`
LEFT OUTER JOIN `location`
ON `location`.`location_serial` = `classroom`.`location_serial`
LEFT OUTER JOIN `rack_info`
ON `classroom_info`.`location_serial` = `classroom`.`location_serial`
WHERE (
    (((`location`.`building` LIKE 'SCH%')))
    AND
    (`classroom_info`.`status` NOT IN (1, 2))
    AND
    (
        (
            (`location`.`building` = 'SCH1' AND `location`.`classroom` != '99')
            AND
            (`location`.`building` = 'SCH1' AND `location`.`classroom` != '34')
        )
    )
)

I'm having a problem in my WHERE clause.

Let's say location.building can be SCH1, SCH2, SCH3, SCH4, CAB1, CAB2. I'm trying to select all of the SCH classrooms, where some classroom statuses are 1 & 2.

This all works fine

The problem arises when I try to further filter my results to exclude instances when the building is SCH1 and the classroom ID is 99, and when the building is SCH1 and the classroom ID is 34. I want to show all other classrooms across all SCH buildings (including SCH1, e.g. SCH1.98) but exclude the two specific classrooms mentioned in the SQL query above (SCH1.99 and SCH1.34)

I may also want to exclude other SCH rooms, like SCH2.24, SCH3.33 - but I want all the other classrooms to appear.

I've been looking for hours and I think I've reached the limits of my ability - all help welcome.

Body:
To "exclude instances when the building is SCH1 and the classroom ID is 99, and when the building is SCH1 and the classroom ID is 34" you can check that the building isn't 'SCH1' or (especially when the building is 'SCH1') the classroom ID is not in '34' or '99'. (Assuming the classroom ID is a varchar, otherwise you can drop the single quotes.)

SELECT `location`.`building`,
       `location`.`classroom`
       FROM `schools`
            LEFT OUTER JOIN `location`
                            ON `location`.`location_serial` = `classroom`.`location_serial`
            LEFT OUTER JOIN `rack_info`
                            ON `classroom_info`.`location_serial` = `classroom`.`location_serial`
       WHERE `location`.`building` LIKE 'SCH%'
             AND `classroom_info`.`status` NOT IN (1,
                                                   2)
             AND (`location`.`building` <> 'SCH1'
                   OR `location`.`classroom` NOT IN ('34',
                                                     '99'));


问:
Python Selenium ActionChains - drag_and_drop method isn't working properly
I'm trying to drag and drop an element using ActionChains. But can't get it to work.

Environment:

Python 3.x

Selenium 3.14.x

Driver: Chrome

PC: Mac OS X 10.14.15

Url: https://demoqa.com/sortable/

So there are two drag and drop methods:

drag_and_drop

drag_and_drop_by_offset

When I try with offset it works but when I use regular drag_and_drop it doesn't.

driver = webdriver.Chrome()
driver.get("https://demoqa.com/")

sortable_button = driver.find_element(
    By.CSS_SELECTOR, "aside.widget:nth-of-type(1) li:nth-of-type(1)")
sortable_button.click()
items = driver.find_elements(By.CSS_SELECTOR, "#sortable li")
actions = ActionChains(driver)
actions.drag_and_drop_by_offset(items[0], 0, 200).perform()
# actions.drag_and_drop(items[0], items[4]).perform()
time.sleep(5)
driver.close()
```

答:
It appears that drag_and_drop method doesn't work with HTML5

Here's a reference that provides a workaround and a confirmation by selenium dev that indeed it doesn't work on HTML5

https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/3604


问:
Which Files In My Application that Make Slow Mysql Query Log Entries
I have been struggling for 2 days for this problem and have not found a solution.

I log mysql slow query with 10 seconds period. In the log file there are a huge entries with this statement:

```<code># Thread_id: 222244  Schema: user  QC_hit: No
# Query_time: 51.019708  Lock_time: 0.000119  Rows_sent: 1  Rows_examined: 13295012
# Rows_affected: 0
SET timestamp=1559388099;
SELECT (COUNT(*)) AS `count`
FROM statistics Statistics WHERE (id >= 1 AND ad_type <> 3);
</code>```

Which is associated with a surge in apache requests.
The query_time is up to one minute or more completed and causes my server to be overloaded.
The problem is I can't find which file in my php script that causes the slow queries.

Is there any command line to find the associated file. Or any fast way?

```<code>CREATE TABLE statistics` (
    id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
    ... ,
    PRIMARY KEY (id),
    KEY idx_uid (uid),
    KEY idx_ip (ip),
    KEY idx_cnid_uid (cid,uid),
    KEY idx_rlid (rid),
    KEY idx_created_uid (created,uid)
) ENGINE=InnoDB AUTO_INCREMENT=34015 DEFAULT CHARSET=utf8
</code>```

答:
If there is no reason for checking id >= 1, get rid of it -- it inhibits certain optimizations.

Then add INDEX(ad_type)

Still, I see no good reason for COUNT(*) on a 34K-row(?) table to take 51 seconds.  Something else must be involved.

Body:
I have been struggling for 2 days for this problem and have not found a solution.

I log mysql slow query with 10 seconds period. In the log file there are a huge entries with this statement:

# Thread_id: 222244  Schema: user  QC_hit: No
# Query_time: 51.019708  Lock_time: 0.000119  Rows_sent: 1  Rows_examined: 13295012
# Rows_affected: 0
SET timestamp=1559388099;
SELECT (COUNT(*)) AS `count`
FROM statistics Statistics WHERE (id >= 1 AND ad_type <> 3);

Which is associated with a surge in apache requests.
The query_time is up to one minute or more completed and causes my server to be overloaded.
The problem is I can't find which file in my php script that causes the slow queries.

Is there any command line to find the associated file. Or any fast way?

CREATE TABLE statistics` (
    id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
    ... ,
    PRIMARY KEY (id),
    KEY idx_uid (uid),
    KEY idx_ip (ip),
    KEY idx_cnid_uid (cid,uid),
    KEY idx_rlid (rid),
    KEY idx_created_uid (created,uid)
) ENGINE=InnoDB AUTO_INCREMENT=34015 DEFAULT CHARSET=utf8


问:
WebSocket challenges with Scala and fs2/cats
I'm using Http4s to mount a websocket service that I can use to communicate between this backend service and a UI (piping status updates and completion % for a batch job).

I'm using the BlazeBuilder Websocket Example to set up the service.

The service works, but what I'm trying to do is emit socket messages from within a class instance. For example, I want to instantiate a worker, pass a reference for the socket connection, and be able to emit data into that connection. Unfortunately, I'm having a very hard time making this work! It's much simpler in Python and JS.

See the code below, which is mostly the example code I linked above. In the place I'm calling Stream.emit(...), how can I pass a reference to that "toClient" and still emit to it? If I pass the toClient instance into a class instance, it doesn't seem to work.

```<code>case GET -> Root / "ws" =>
      val toClient: Stream[F, WebSocketFrame] = Stream.emit(Text("How can I do this from a class instance?"))
      val fromClient: Sink[F, WebSocketFrame] = _.evalMap { (ws: WebSocketFrame) =>
        ws match {
          case Text(t, _) => F.delay(println(t))
          case f => F.delay(println(s"Unknown type: $f"))
        }
      }
      WebSocketBuilder[F].build(toClient, fromClient)
</code>```

答:
You could use a MVar for the thread safe communication with the websocket.

Here is a example using Cats IO Effect:

final class WebSocketServer(implicit timer: Timer[IO]) extends Http4sDsl[IO] {

  implicit val contextShift: ContextShift[IO] = IO.contextShift(ExecutionContext.global)

  def start: IO[ExitCode] = {
    BlazeServerBuilder[IO]
      .bindHttp(8080)
      .withWebSockets(true)
      .withHttpApp(routes.orNotFound)
      .resource
      .use(_ => IO.never)
      .as(ExitCode.Success)
  }

  private[this] val routes: HttpRoutes[IO] = HttpRoutes.of[IO] {
    case GET -> Root / "ws" => {
      for {
        channel <- cats.effect.concurrent.MVar[IO].empty[List[WebSocketFrame]]
        webSocket <- {
          WebSocketBuilder[IO].build(
            send = fs2.Stream
              .eval(channel.take)
              .flatMap(fs2.Stream.emits(_))
              .repeat,
            receive = stream => {
              stream.evalMap {
                case Text(data, _)   => channel.put(List(Text("pong")))
                case unknown         => IO(println(s"Unknown type: $unknown"))
              }
            }
          )
        }
      } yield webSocket
    }
  }
}
```

<p>If you want to send a message back to the client you have to put it into the MVar.</p>

<pre class="lang-scala prettyprint-override"><code>channel.put(List(Text("pong")))
</code>```

The interesting part is the repeating stream that is polling the MVar for new messages to send back to the client of the WebSocket.

fs2.Stream.eval(channel.take).flatMap(fs2.Stream.emits(_).repeat
```

ContentLicense: CC BY-SA 3.0

Body:
I'm using Http4s to mount a websocket service that I can use to communicate between this backend service and a UI (piping status updates and completion % for a batch job).

I'm using the BlazeBuilder Websocket Example to set up the service.

The service works, but what I'm trying to do is emit socket messages from within a class instance. For example, I want to instantiate a worker, pass a reference for the socket connection, and be able to emit data into that connection. Unfortunately, I'm having a very hard time making this work! It's much simpler in Python and JS.

See the code below, which is mostly the example code I linked above. In the place I'm calling Stream.emit(...), how can I pass a reference to that "toClient" and still emit to it? If I pass the toClient instance into a class instance, it doesn't seem to work.

case GET -> Root / "ws" =>
      val toClient: Stream[F, WebSocketFrame] = Stream.emit(Text("How can I do this from a class instance?"))
      val fromClient: Sink[F, WebSocketFrame] = _.evalMap { (ws: WebSocketFrame) =>
        ws match {
          case Text(t, _) => F.delay(println(t))
          case f => F.delay(println(s"Unknown type: $f"))
        }
      }
      WebSocketBuilder[F].build(toClient, fromClient)

Body:
You could use a MVar for the thread safe communication with the websocket.

Here is a example using Cats IO Effect:

final class WebSocketServer(implicit timer: Timer[IO]) extends Http4sDsl[IO] {

  implicit val contextShift: ContextShift[IO] = IO.contextShift(ExecutionContext.global)

  def start: IO[ExitCode] = {
    BlazeServerBuilder[IO]
      .bindHttp(8080)
      .withWebSockets(true)
      .withHttpApp(routes.orNotFound)
      .resource
      .use(_ => IO.never)
      .as(ExitCode.Success)
  }

  private[this] val routes: HttpRoutes[IO] = HttpRoutes.of[IO] {
    case GET -> Root / "ws" => {
      for {
        channel <- cats.effect.concurrent.MVar[IO].empty[List[WebSocketFrame]]
        webSocket <- {
          WebSocketBuilder[IO].build(
            send = fs2.Stream
              .eval(channel.take)
              .flatMap(fs2.Stream.emits(_))
              .repeat,
            receive = stream => {
              stream.evalMap {
                case Text(data, _)   => channel.put(List(Text("pong")))
                case unknown         => IO(println(s"Unknown type: $unknown"))
              }
            }
          )
        }
      } yield webSocket
    }
  }
}

If you want to send a message back to the client you have to put it into the MVar.

channel.put(List(Text("pong")))

The interesting part is the repeating stream that is polling the MVar for new messages to send back to the client of the WebSocket.

fs2.Stream.eval(channel.take).flatMap(fs2.Stream.emits(_).repeat


问:
How can i extract a word using loops and not arrays
Situation:

A user will input a sentence.
I need to perform certain modifications to each word but depending on the length of each word.

For example for each vowel i need to put a 3 before if the word length is over 2.

```<code>// for words with length > 2
for (i=0;i<example.length();i++)

    switch (word.charAt(i))
    {
    case 'a':
    case 'e':
    case 'i':
    case 'o':
    case 'u':
    case 'y':
        output += "3" + word.charAt(i);
        break;
    default:
        output += word.charAt(i);
        break;
    }
</code>```

Objective:

How can i test a word's length before i perform my for loop. Say my word is 1-character long, i need to put a "1", 2-character long a "2".

Example:

"hello my name is roger"

Output:

h3ell3o m2y n3am3e 2is 1A

Important:

No arrays, only for, while loops, switch or if statements.

答:
```<code>public class Test {
  public static void main(String[] args) {
     String input = "hello my name is roger";
     input+=' '; // adding a whitespace at end to indicate completion of last word

     String word = "";
     char ch;
     String res = "";
     int len = input.length();

     for(int i = 0;i<len ;i++) {
       ch = input.charAt(i);
       if(Character.isWhitespace(ch)) {
         res = res +" "+processWord(word);
         System.out.println(word);
         word = "";
       }else {
         word+=ch;
       }
     }
}

  private static String processWord(String word) {
    // TODO Auto-generated method stub
    if(word.length()<=2) {
      return word;
    }

    // do whatever you have to do with your word
    String res = "";
    return res;
  }
}
</code>```

Basically,The logic to extract out words is -

if current character is a whitespace,then we've got a word.

else if current character is not a whitespace,then we append this character to current word that we are building

Body:
Situation:

A user will input a sentence.
I need to perform certain modifications to each word but depending on the length of each word.

For example for each vowel i need to put a 3 before if the word length is over 2.

// for words with length > 2
for (i=0;i<example.length();i++)

    switch (word.charAt(i))
    {
    case 'a':
    case 'e':
    case 'i':
    case 'o':
    case 'u':
    case 'y':
        output += "3" + word.charAt(i);
        break;
    default:
        output += word.charAt(i);
        break;
    }

Objective:

How can i test a word's length before i perform my for loop. Say my word is 1-character long, i need to put a "1", 2-character long a "2".

Example:

"hello my name is roger"

Output:

h3ell3o m2y n3am3e 2is 1A

Important:

No arrays, only for, while loops, switch or if statements.

Body:
public class Test {
  public static void main(String[] args) {
     String input = "hello my name is roger";
     input+=' '; // adding a whitespace at end to indicate completion of last word

     String word = "";
     char ch;
     String res = "";
     int len = input.length();

     for(int i = 0;i<len ;i++) {
       ch = input.charAt(i);
       if(Character.isWhitespace(ch)) {
         res = res +" "+processWord(word);
         System.out.println(word);
         word = "";
       }else {
         word+=ch;
       }
     }
}

  private static String processWord(String word) {
    // TODO Auto-generated method stub
    if(word.length()<=2) {
      return word;
    }

    // do whatever you have to do with your word
    String res = "";
    return res;
  }
}

Basically,The logic to extract out words is -

if current character is a whitespace,then we've got a word.

else if current character is not a whitespace,then we append this character to current word that we are building


问:
Open external link with function in React
I'm trying to create a button in React which opens an external link to a google maps url.

I have a function which asks the user for their geolocation, which once provided, inputs the location into the url link which gets directions from their geolocation to a set destination.

However, I'm struggling to get the button to firstly run the function and open the URL in a new tab. This is currently how I'm calling the button component.

```<code><Button variant="primary" onClick={this.onHandleClick}>Get Google Maps Directions</Button>
</code>```

And this is the function which forms and opens the link.

```<code>  onHandleClick = () => {
    var location = this.state.currentLocation;

    location.then(function(location){
      var link = `google.com/maps/dir/?api=1&origin=${location}&destination=50.927044,-1.299964&travelmode=driving`

      //window.location.href = link;
      window.location.assign(link);
    })
  }

</code>```

Currently the external link forms correctly, but is appended to the existing localhost domain in the url so does not open currently (or in a new tab).

url result of the above functions:

http://localhost:3000/google.com/maps/dir/?api=1&origin=50.4984,%20-2.6119074&destination=50.927044,-1.299964&travelmode=driving

I've tried setting target="_blank" when calling the compnent.

Any help would be greatly appreciated!

Thanks,
Max

答:
```<code>window.open(link, "_blank");
</code>```

This will cause the link to open in a new tab.

Note: If you do not include "http://" or "https://" before the link, the default behavior is to append the link onto the current domain, so if you're opening an external link, be sure to include the http/s.

Body:
I'm trying to create a button in React which opens an external link to a google maps url.

I have a function which asks the user for their geolocation, which once provided, inputs the location into the url link which gets directions from their geolocation to a set destination.

However, I'm struggling to get the button to firstly run the function and open the URL in a new tab. This is currently how I'm calling the button component.

<Button variant="primary" onClick={this.onHandleClick}>Get Google Maps Directions</Button>

And this is the function which forms and opens the link.

  onHandleClick = () => {
    var location = this.state.currentLocation;

    location.then(function(location){
      var link = `google.com/maps/dir/?api=1&origin=${location}&destination=50.927044,-1.299964&travelmode=driving`

      //window.location.href = link;
      window.location.assign(link);
    })
  }

Currently the external link forms correctly, but is appended to the existing localhost domain in the url so does not open currently (or in a new tab).

url result of the above functions:

http://localhost:3000/google.com/maps/dir/?api=1&origin=50.4984,%20-2.6119074&destination=50.927044,-1.299964&travelmode=driving

I've tried setting target="_blank" when calling the compnent.

Any help would be greatly appreciated!

Thanks,
Max

Body:
window.open(link, "_blank");

This will cause the link to open in a new tab.

Note: If you do not include "http://" or "https://" before the link, the default behavior is to append the link onto the current domain, so if you're opening an external link, be sure to include the http/s.


问:
Destructuring nested objects: How to get parent and its children values?
The function below receives an object that has a property current, which is also an object, and it has selectionStart and selectionEnd properties.

Here, nested destructuring works as expected with Start and End variables, But I also need the value for current.

function someFunction({ current: { selectionStart: Start, selectionEnd: End } }) {

    // do something with current, Start, and End
}
```

How do I get it using destructuring?

答:
You can destructure and assign the default value in a single statement.

```<code>function someFunction({
        current: {
          selectionStart: Start,
          selectionEnd: End
        } = {},
        current = {}
      },
      AppStateSetter) {
      // now you can use the let variables Start, End and current,
      // with current's default value set to empty object
      }
</code>```

If you don't want to assign default value to current, but still want to use that variable, you can just write the name of the property with no assignment. When someFunction is called with empty object, if you don't assign a default value to current it will be undefined.

```<code>    function someFunction1({
        current: {
          selectionStart: Start,
          selectionEnd: End
        } = {},
        current
      },
      AppStateSetter) {
      // now you can use the let variables Start, End and current
      // if empty object is passed, current will be undefined
    }
</code>```

JsFiddle snippet: Nested object destructuring with and without default values

Body:
The function below receives an object that has a property current, which is also an object, and it has selectionStart and selectionEnd properties.

Here, nested destructuring works as expected with Start and End variables, But I also need the value for current.

function someFunction({ current: { selectionStart: Start, selectionEnd: End } }) {

    // do something with current, Start, and End
}

How do I get it using destructuring?

Body:
You can destructure and assign the default value in a single statement.

function someFunction({
        current: {
          selectionStart: Start,
          selectionEnd: End
        } = {},
        current = {}
      },
      AppStateSetter) {
      // now you can use the let variables Start, End and current,
      // with current's default value set to empty object
      }

If you don't want to assign default value to current, but still want to use that variable, you can just write the name of the property with no assignment. When someFunction is called with empty object, if you don't assign a default value to current it will be undefined.

    function someFunction1({
        current: {
          selectionStart: Start,
          selectionEnd: End
        } = {},
        current
      },
      AppStateSetter) {
      // now you can use the let variables Start, End and current
      // if empty object is passed, current will be undefined
    }

JsFiddle snippet: Nested object destructuring with and without default values


问:
NodeRED: How to access configuration node?
How can a configuration node be accessed (for read and write) or even be created inside a function node?

My scenario: I have a ModbusTCP node that uses configuration nodes for host/port settings. I need to create different configuration nodes inside my flow.

答:
You can not (normally) create (config or otherwise) nodes from with in a flow.

And you definitely can not directly edit existing nodes from with in the flow.

I say normally, because if you REALLY REALLY need to you can use the admin api to fetch the flow as JSON, edit it and then redeploy the whole flow.

But this is a multi stage process


问:
Protractor + Selenium Grid: Shard Test Specs Across Nodes
I recently setup a Selenium Grid (1 server for the hub, and 10 other servers which host 1 node each), and I have no issues running my Protractor automated tests. However, I'd like to shard my ~400 tests across all the nodes defined in multiCapabilities (within my protractor.conf.js) so I can dramatically decrease the execution time.

Protractor once supported this, but it has since been deprecated (not sure why..?). I've tried setting shardTestFiles: true in the multiCapabilities object, but that just sharded tests across all browser instances within each node (every node ran all the tests). I played with the maxSessions, maxInstances and count configurations as well. I even tried removing multiCapabilities and putting the complete configuration in capabilities - no luck.

Is there a non-hacky way to get this working? I've scoured npm, and I can't find any node modules or gulp plugins for this either.

答:
Did you try giving multicapabilties something like below in conf.js

multiCapabilities: [{
    'browserName': 'chrome',
    shardTestFiles: true,
    maxInstances: 2
    specs : ['specs1', 'specs2'],
  },
{
    'browserName': 'firefox',
    shardTestFiles: true,
    maxInstances: 2,
     specs : ['specs3', 'specs4'],
  },
}]

This will run specs1 and 2 only on chrome and specs 3 and 4 on firefox and this reduces the total time.of execution by 50%.
You can pass more capabilities inside multicapabilities and distribute specs further to those capabilities to reduce the total execution time further more.


问:
clang backend when I start the terminal
I am not sure how much the
link helps. I have to see the list of these messages upon opening the terminal. It came with installing clang for the sake of pystan I believe.

I would very much like to denoise the following, but I've not got a good clue. Appreciate any input, thanks.

```<code>INFO: activate_clang_osx-64.sh made the following environmental changes:
+AR=//anaconda/bin/x86_64-apple-darwin13.4.0-ar
+AS=//anaconda/bin/x86_64-apple-darwin13.4.0-as
+CC=x86_64-apple-darwin13.4.0-clang
+CFLAGS=-march=core2 -mtune=haswell -mssse3 -ftree-vectorize -fPIC -fPIE -fstack-protector-strong -O2 -pipe
+CHECKSYMS=//anaconda/bin/x86_64-apple-darwin13.4.0-checksyms
+CLANG=//anaconda/bin/x86_64-apple-darwin13.4.0-clang
+CODESIGN_ALLOCATE=//anaconda/bin/x86_64-apple-darwin13.4.0-codesign_allocate
+CONDA_BUILD_SYSROOT=/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk
+CPPFLAGS=-D_FORTIFY_SOURCE=2 -mmacosx-version-min=10.9
+DEBUG_CFLAGS=-march=core2 -mtune=haswell -mssse3 -ftree-vectorize -fPIC -fPIE -fstack-protector-strong -O2 -pipe -Og -g -Wall -Wextra
+HOST=x86_64-apple-darwin13.4.0
+INDR=//anaconda/bin/x86_64-apple-darwin13.4.0-indr
+INSTALL_NAME_TOOL=//anaconda/bin/x86_64-apple-darwin13.4.0-install_name_tool
+LD=//anaconda/bin/x86_64-apple-darwin13.4.0-ld
+LDFLAGS=-Wl,-pie -Wl,-headerpad_max_install_names -Wl,-dead_strip_dylibs
+LDFLAGS_LD=-pie -headerpad_max_install_names -dead_strip_dylibs
+LIBTOOL=//anaconda/bin/x86_64-apple-darwin13.4.0-libtool
+LIPO=//anaconda/bin/x86_64-apple-darwin13.4.0-lipo
+NM=//anaconda/bin/x86_64-apple-darwin13.4.0-nm
+NMEDIT=//anaconda/bin/x86_64-apple-darwin13.4.0-nmedit
+OTOOL=//anaconda/bin/x86_64-apple-darwin13.4.0-otool
+PAGESTUFF=//anaconda/bin/x86_64-apple-darwin13.4.0-pagestuff
+RANLIB=//anaconda/bin/x86_64-apple-darwin13.4.0-ranlib
+REDO_PREBINDING=//anaconda/bin/x86_64-apple-darwin13.4.0-redo_prebinding
+SEGEDIT=//anaconda/bin/x86_64-apple-darwin13.4.0-segedit
+SEG_ADDR_TABLE=//anaconda/bin/x86_64-apple-darwin13.4.0-seg_addr_table
+SEG_HACK=//anaconda/bin/x86_64-apple-darwin13.4.0-seg_hack
+SIZE=//anaconda/bin/x86_64-apple-darwin13.4.0-size
+STRINGS=//anaconda/bin/x86_64-apple-darwin13.4.0-strings
+STRIP=//anaconda/bin/x86_64-apple-darwin13.4.0-strip
+_PYTHON_SYSCONFIGDATA_NAME=_sysconfigdata_x86_64_apple_darwin13_4_0
INFO: activate_clangxx_osx-64.sh made the following environmental changes:
+CLANGXX=//anaconda/bin/x86_64-apple-darwin13.4.0-clang++
+CXX=x86_64-apple-darwin13.4.0-clang++
+CXXFLAGS=-march=core2 -mtune=haswell -mssse3 -ftree-vectorize -fPIC -fPIE -fstack-protector-strong -O2 -pipe -stdlib=libc++ -fvisibility-inlines-hidden -std=c++14 -fmessage-length=0
+DEBUG_CXXFLAGS=-march=core2 -mtune=haswell -mssse3 -ftree-vectorize -fPIC -fPIE -fstack-protector-strong -O2 -pipe -stdlib=libc++ -fvisibility-inlines-hidden -std=c++14 -fmessage-length=0 -Og -g -Wall -Wextra
</code>```

答: I actually fixed this by the link, but it remains murky which of the versions btw clangxx_osx-64-4.0.1-h22b1bf0_8 vs. clangxx_osx-64-4.0.1-h22b1bf0_11 caused it. It seemed more likely that the recent version should be the reason for it, but I actually got lucky by commenting out the lines that were similarly mentioned in the link from the older version.. </p>

Title: clang backend when I start the terminal

Body:
I am not sure how much the
link helps. I have to see the list of these messages upon opening the terminal. It came with installing clang for the sake of pystan I believe.

I would very much like to denoise the following, but I've not got a good clue. Appreciate any input, thanks.

INFO: activate_clang_osx-64.sh made the following environmental changes:
+AR=//anaconda/bin/x86_64-apple-darwin13.4.0-ar
+AS=//anaconda/bin/x86_64-apple-darwin13.4.0-as
+CC=x86_64-apple-darwin13.4.0-clang
+CFLAGS=-march=core2 -mtune=haswell -mssse3 -ftree-vectorize -fPIC -fPIE -fstack-protector-strong -O2 -pipe
+CHECKSYMS=//anaconda/bin/x86_64-apple-darwin13.4.0-checksyms
+CLANG=//anaconda/bin/x86_64-apple-darwin13.4.0-clang
+CODESIGN_ALLOCATE=//anaconda/bin/x86_64-apple-darwin13.4.0-codesign_allocate
+CONDA_BUILD_SYSROOT=/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk
+CPPFLAGS=-D_FORTIFY_SOURCE=2 -mmacosx-version-min=10.9
+DEBUG_CFLAGS=-march=core2 -mtune=haswell -mssse3 -ftree-vectorize -fPIC -fPIE -fstack-protector-strong -O2 -pipe -Og -g -Wall -Wextra
+HOST=x86_64-apple-darwin13.4.0
+INDR=//anaconda/bin/x86_64-apple-darwin13.4.0-indr
+INSTALL_NAME_TOOL=//anaconda/bin/x86_64-apple-darwin13.4.0-install_name_tool
+LD=//anaconda/bin/x86_64-apple-darwin13.4.0-ld
+LDFLAGS=-Wl,-pie -Wl,-headerpad_max_install_names -Wl,-dead_strip_dylibs
+LDFLAGS_LD=-pie -headerpad_max_install_names -dead_strip_dylibs
+LIBTOOL=//anaconda/bin/x86_64-apple-darwin13.4.0-libtool
+LIPO=//anaconda/bin/x86_64-apple-darwin13.4.0-lipo
+NM=//anaconda/bin/x86_64-apple-darwin13.4.0-nm
+NMEDIT=//anaconda/bin/x86_64-apple-darwin13.4.0-nmedit
+OTOOL=//anaconda/bin/x86_64-apple-darwin13.4.0-otool
+PAGESTUFF=//anaconda/bin/x86_64-apple-darwin13.4.0-pagestuff
+RANLIB=//anaconda/bin/x86_64-apple-darwin13.4.0-ranlib
+REDO_PREBINDING=//anaconda/bin/x86_64-apple-darwin13.4.0-redo_prebinding
+SEGEDIT=//anaconda/bin/x86_64-apple-darwin13.4.0-segedit
+SEG_ADDR_TABLE=//anaconda/bin/x86_64-apple-darwin13.4.0-seg_addr_table
+SEG_HACK=//anaconda/bin/x86_64-apple-darwin13.4.0-seg_hack
+SIZE=//anaconda/bin/x86_64-apple-darwin13.4.0-size
+STRINGS=//anaconda/bin/x86_64-apple-darwin13.4.0-strings
+STRIP=//anaconda/bin/x86_64-apple-darwin13.4.0-strip
+_PYTHON_SYSCONFIGDATA_NAME=_sysconfigdata_x86_64_apple_darwin13_4_0
INFO: activate_clangxx_osx-64.sh made the following environmental changes:
+CLANGXX=//anaconda/bin/x86_64-apple-darwin13.4.0-clang++
+CXX=x86_64-apple-darwin13.4.0-clang++
+CXXFLAGS=-march=core2 -mtune=haswell -mssse3 -ftree-vectorize -fPIC -fPIE -fstack-protector-strong -O2 -pipe -stdlib=libc++ -fvisibility-inlines-hidden -std=c++14 -fmessage-length=0
+DEBUG_CXXFLAGS=-march=core2 -mtune=haswell -mssse3 -ftree-vectorize -fPIC -fPIE -fstack-protector-strong -O2 -pipe -stdlib=libc++ -fvisibility-inlines-hidden -std=c++14 -fmessage-length=0 -Og -g -Wall -Wextra


问:
Error running basic tensorflow example
I have just reinstalled latest tensorflow on ubuntu:

```<code>$ sudo pip install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.7.1-cp27-none-linux_x86_64.whl
[sudo] password for ubuntu:
The directory '/home/ubuntu/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/ubuntu/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting tensorflow==0.7.1 from https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.7.1-cp27-none-linux_x86_64.whl
  Downloading https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.7.1-cp27-none-linux_x86_64.whl (13.8MB)
    100% |████████████████████████████████| 13.8MB 32kB/s
Requirement already up-to-date: six>=1.10.0 in /usr/local/lib/python2.7/dist-packages (from tensorflow==0.7.1)
Requirement already up-to-date: protobuf==3.0.0b2 in /usr/local/lib/python2.7/dist-packages (from tensorflow==0.7.1)
Requirement already up-to-date: wheel in /usr/local/lib/python2.7/dist-packages (from tensorflow==0.7.1)
Requirement already up-to-date: numpy>=1.8.2 in /usr/local/lib/python2.7/dist-packages (from tensorflow==0.7.1)
Requirement already up-to-date: setuptools in /usr/local/lib/python2.7/dist-packages (from protobuf==3.0.0b2->tensorflow==0.7.1)
Installing collected packages: tensorflow
  Found existing installation: tensorflow 0.7.1
    Uninstalling tensorflow-0.7.1:
      Successfully uninstalled tensorflow-0.7.1
Successfully installed tensorflow-0.7.1
</code>```

When following the directions to test it fails with cannot import name pywrap_tensorflow:

```<code>$ ipython

/git/tensorflow/tensorflow/__init__.py in <module>()
     21 from __future__ import print_function
     22
---> 23 from tensorflow.python import *

/git/tensorflow/tensorflow/python/__init__.py in <module>()
     43 _default_dlopen_flags = sys.getdlopenflags()
     44 sys.setdlopenflags(_default_dlopen_flags | ctypes.RTLD_GLOBAL)
---> 45 from tensorflow.python import pywrap_tensorflow
     46 sys.setdlopenflags(_default_dlopen_flags)
     47

ImportError: cannot import name pywrap_tensorflow
</code>```

Is there an additional change needed to my python or ubuntu/bash environment?

答: I'm using tensorflow 1.13.1. Just reinstalling tensorflow worked for me. </p>

Title: Error running basic tensorflow example

Body:
I have just reinstalled latest tensorflow on ubuntu:

$ sudo pip install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.7.1-cp27-none-linux_x86_64.whl
[sudo] password for ubuntu:
The directory '/home/ubuntu/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/ubuntu/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting tensorflow==0.7.1 from https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.7.1-cp27-none-linux_x86_64.whl
  Downloading https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.7.1-cp27-none-linux_x86_64.whl (13.8MB)
    100% |████████████████████████████████| 13.8MB 32kB/s
Requirement already up-to-date: six>=1.10.0 in /usr/local/lib/python2.7/dist-packages (from tensorflow==0.7.1)
Requirement already up-to-date: protobuf==3.0.0b2 in /usr/local/lib/python2.7/dist-packages (from tensorflow==0.7.1)
Requirement already up-to-date: wheel in /usr/local/lib/python2.7/dist-packages (from tensorflow==0.7.1)
Requirement already up-to-date: numpy>=1.8.2 in /usr/local/lib/python2.7/dist-packages (from tensorflow==0.7.1)
Requirement already up-to-date: setuptools in /usr/local/lib/python2.7/dist-packages (from protobuf==3.0.0b2->tensorflow==0.7.1)
Installing collected packages: tensorflow
  Found existing installation: tensorflow 0.7.1
    Uninstalling tensorflow-0.7.1:
      Successfully uninstalled tensorflow-0.7.1
Successfully installed tensorflow-0.7.1

When following the directions to test it fails with cannot import name pywrap_tensorflow:

$ ipython

/git/tensorflow/tensorflow/__init__.py in <module>()
     21 from __future__ import print_function
     22
---> 23 from tensorflow.python import *

/git/tensorflow/tensorflow/python/__init__.py in <module>()
     43 _default_dlopen_flags = sys.getdlopenflags()
     44 sys.setdlopenflags(_default_dlopen_flags | ctypes.RTLD_GLOBAL)
---> 45 from tensorflow.python import pywrap_tensorflow
     46 sys.setdlopenflags(_default_dlopen_flags)
     47

ImportError: cannot import name pywrap_tensorflow

Is there an additional change needed to my python or ubuntu/bash environment?


问:
Defining (overloading) a custom C++ operator
I am learning C++ and I wondered whether it would be possible to have an operator like ->= or .=. That kind of operator would work like the arithmetic ones (+= and so on), however it would check whether both pointers to objects are of the same type. Now I am aware that in C++ you are allowed to overload operators, but apparently the ones I'm after don't exist in C++.
I did try something like this:

```<code>class Node {
      Node* ptr;
      Node* operator->=(Node * obj);
};
</code>```

But not even this class declaration compiles.
Then I tried to set up a macro like this #define ~ ->= where I swap the complement operator (which would have no use for an object) with the desired one with the idea that the IDE would allow me to overload ~ and then the preprocessor would swap all ->= with ~. Apparently that didn't work as well, there was an issue with the macro and I ran out of ideas.

From what I've heard C++ is a very rich and flexible language and I'd be glad to know whether implementing the operator I want would be possible.

答:
It is not possible to define new operators in C++, only the operation of the existing ones can be altered by overloading.

The macro is a very terrible idea and will immediately fail because macro names should only consist of alphanumeric characters and _.

Body:
I am learning C++ and I wondered whether it would be possible to have an operator like ->= or .=. That kind of operator would work like the arithmetic ones (+= and so on), however it would check whether both pointers to objects are of the same type. Now I am aware that in C++ you are allowed to overload operators, but apparently the ones I'm after don't exist in C++.
I did try something like this:

class Node {
      Node* ptr;
      Node* operator->=(Node * obj);
};

But not even this class declaration compiles.
Then I tried to set up a macro like this #define ~ ->= where I swap the complement operator (which would have no use for an object) with the desired one with the idea that the IDE would allow me to overload ~ and then the preprocessor would swap all ->= with ~. Apparently that didn't work as well, there was an issue with the macro and I ran out of ideas.

From what I've heard C++ is a very rich and flexible language and I'd be glad to know whether implementing the operator I want would be possible.


问:
Converting from float to percentage
I would like to convert a decimal number (say 0.33333) to percentage (expected answer 33.33%)

I used the following

```<code>x = 0.3333

print(format(x,'.2%'))
</code>```

which gives indeed 33.33%

However, the result is a string, I would like it to still be a number (in % format) to be able to perform mathematical operations on it (e.g. format(x,'.2%')*2 to give 66.66%

But this throws an exception as 33.33% is a string

答:
An idea is to create a custom datatype, I'll call it Percent, which inherit everything from float, but when you want to use it as a string it shows a % and multiplies the number with 100.

```<code>class Percent(float):
    def __str__(self):
        return '{:.2%}'.format(self)
x = Percent(0.3333)
print(x)
# 33.33%
</code>```

If you want to represnt the value in envoirment like jupyter notebook in your format you can add same method with the name __repr__ to Percent Class:

```<code>def __repr__(self):
    return '{:.2%}'.format(self)
</code>```

Title: Converting from float to percentage

Body:
I would like to convert a decimal number (say 0.33333) to percentage (expected answer 33.33%)

I used the following

x = 0.3333

print(format(x,'.2%'))

which gives indeed 33.33%

However, the result is a string, I would like it to still be a number (in % format) to be able to perform mathematical operations on it (e.g. format(x,'.2%')*2 to give 66.66%

But this throws an exception as 33.33% is a string

Body:
An idea is to create a custom datatype, I'll call it Percent, which inherit everything from float, but when you want to use it as a string it shows a % and multiplies the number with 100.

class Percent(float):
    def __str__(self):
        return '{:.2%}'.format(self)
x = Percent(0.3333)
print(x)
# 33.33%

If you want to represnt the value in envoirment like jupyter notebook in your format you can add same method with the name __repr__ to Percent Class:

def __repr__(self):
    return '{:.2%}'.format(self)


问:
Calling my API always returns my index.php file. Why is this?
I created an index.php file in my public folder (Laravel), an API route in my route/api.php with the url 'submit' and request method post, and a Controller with a function submit() that is executed on the API call.

I tried testing the route on Postman with the following url:

http://mysite.local/api/submit

This was tested as a POST request, but for some reason it keeps returning the index.php file.

I even added a return "Test"; at the start of my submit() function in my Controller to see if the problem was with the code within the function (hope that makes sense, working on my terminology).

But yet again, when I test the API on post man, it still returns the index.php.

Here are my route and Controller:

route/api.php

```<code>Route::post('submit', 'SubmitFormController@submit');
// I've also tried the following:
// Route::post('submit', 'App\Http\Controllers\SubmitFormController@submit');
</code>```

SubmitFormController.php

```<code>class SubmitFormController extends Controller {
    public function submit() {
        return "Test";

        /** .. More code below .. **/
    }
}
</code>```

I even tried changing return "Test"; to return json_encode(['test' => 'testvar']); thinking it would help. But Postman still returns the index.php.

My guess is that it's treating my API route as a "directory", but I may be wrong.

UPDATE: I noticed another strange (strange to me) thing happening.

So, when I go to my local host, which is mysite.local, it takes me to my index.php file in my public folder, which is what it should do. HOWEVER, when I then type in something like mysite.local/skjah/asjdklasjd/asjdklasj (which is clearly gibberish and not an actual directory), it redirects to index.php every single time.

So I'm assuming that because api\submit is not a directory in public, it just redirects to index.php. But I'm not sure why as this has worked in the past and my .htaccess has been untouched.

Hope this bit of information helps.

UPDATE: Just been fiddling with the code and noticed that the issue lies in my .htaccess as some of you have pointed out. Here is my .htaccess (straight out of the box when I made the project, didn't touch it).

```<code><IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews -Indexes
</IfModule>

RewriteEngine On

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
</code>```

I changed the line RewriteRule ^ index.php [L] to RewriteRule ^ index123.php [L] just to see what would happen and the API call to my route function no longer works. Which tells me it has something to do with this file.

That's as far as I got and still looking for a solution. Hope this helps clarify the problem.

答:
My user cant comment yet, so .. here it goes as a answer ...

By and large whenever this occurs it is some page server (this case apache) configuration issue, not php.

Considering you mentioned "routes" I assume you are using "

Have a look in your httpd.conf (and in the .htaccess) if you have something like the configuration below which would be missing or misconfigured (PS: time per time they change configurations, verify if the files in your configuration are compatible with the systems you are using - apache version and php version)

```<code># PHP5 module
LoadModule php5_module "c:/php/php5apache2_2.dll"
AddType application/x-httpd-php .php
PHPIniDir "C:/php"
</code>```

PS: API Calls (if using 80 or 443 port) should not work as well in this computer, if they do it tends to be misconfiguration on .htacces files.

Body:
I created an index.php file in my public folder (Laravel), an API route in my route/api.php with the url 'submit' and request method post, and a Controller with a function submit() that is executed on the API call.

I tried testing the route on Postman with the following url:

http://mysite.local/api/submit

This was tested as a POST request, but for some reason it keeps returning the index.php file.

I even added a return "Test"; at the start of my submit() function in my Controller to see if the problem was with the code within the function (hope that makes sense, working on my terminology).

But yet again, when I test the API on post man, it still returns the index.php.

Here are my route and Controller:

route/api.php

Route::post('submit', 'SubmitFormController@submit');
// I've also tried the following:
// Route::post('submit', 'App\Http\Controllers\SubmitFormController@submit');

SubmitFormController.php

class SubmitFormController extends Controller {
    public function submit() {
        return "Test";

        /** .. More code below .. **/
    }
}

I even tried changing return "Test"; to return json_encode(['test' => 'testvar']); thinking it would help. But Postman still returns the index.php.

My guess is that it's treating my API route as a "directory", but I may be wrong.

UPDATE: I noticed another strange (strange to me) thing happening.

So, when I go to my local host, which is mysite.local, it takes me to my index.php file in my public folder, which is what it should do. HOWEVER, when I then type in something like mysite.local/skjah/asjdklasjd/asjdklasj (which is clearly gibberish and not an actual directory), it redirects to index.php every single time.

So I'm assuming that because api\submit is not a directory in public, it just redirects to index.php. But I'm not sure why as this has worked in the past and my .htaccess has been untouched.

Hope this bit of information helps.

UPDATE: Just been fiddling with the code and noticed that the issue lies in my .htaccess as some of you have pointed out. Here is my .htaccess (straight out of the box when I made the project, didn't touch it).

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews -Indexes
</IfModule>

RewriteEngine On

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>

I changed the line RewriteRule ^ index.php [L] to RewriteRule ^ index123.php [L] just to see what would happen and the API call to my route function no longer works. Which tells me it has something to do with this file.

That's as far as I got and still looking for a solution. Hope this helps clarify the problem.

Body:
My user cant comment yet, so .. here it goes as a answer ...

By and large whenever this occurs it is some page server (this case apache) configuration issue, not php.

Considering you mentioned "routes" I assume you are using "

Have a look in your httpd.conf (and in the .htaccess) if you have something like the configuration below which would be missing or misconfigured (PS: time per time they change configurations, verify if the files in your configuration are compatible with the systems you are using - apache version and php version)

# PHP5 module
LoadModule php5_module "c:/php/php5apache2_2.dll"
AddType application/x-httpd-php .php
PHPIniDir "C:/php"

PS: API Calls (if using 80 or 443 port) should not work as well in this computer, if they do it tends to be misconfiguration on .htacces files.


问:
Raycast point is not on plane Layer (wierd position)?
Target: Get the point of intersection of the raycast with the plane's Layer.

The raycast draws a line that intersects the plane (on mouse click).

But the line also intersects everything in its path, so the outcome point is giving the point of intersection with objects other than the plane.

I have assigned the layer of the plane as "Plane" and included in the code the layer of the plane only when raycasting.

```<code>        if (Input.GetMouseButton(0))
        {
            RaycastHit hit;
            int layerMask = (1 << 8); // Plane's Layer
            var ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast (ray, out hit, layerMask)) {
                transform.position = hit.point;
            }
        }
</code>```

What is happening is that the position of the gameObject is overriding its old position until the object is clipping with the camera.

答:
So, you are passing a ray, a RayCastHit, and a number into Physics.Raycast and it's recognising them like this:

Physics.Raycast (ray, hit, distance)

Any time you do a raycast with a layer mask you need to set the distance of the cast first because that's what all the raycast methods expect as the first number after the hit to use. Here's a version that should work using Mathf.Infinity as the distance:

```<code>if (Input.GetMouseButton(0)) {
    RaycastHit hit;
    int layerMask = (1 << 8); // Plane's Layer
    var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    if (Physics.Raycast (ray, out hit, Mathf.Infinity, layerMask)) {
        transform.position = hit.point;
    }
}
</code>```

Body:
Target: Get the point of intersection of the raycast with the plane's Layer.

The raycast draws a line that intersects the plane (on mouse click).

But the line also intersects everything in its path, so the outcome point is giving the point of intersection with objects other than the plane.

I have assigned the layer of the plane as "Plane" and included in the code the layer of the plane only when raycasting.

        if (Input.GetMouseButton(0))
        {
            RaycastHit hit;
            int layerMask = (1 << 8); // Plane's Layer
            var ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast (ray, out hit, layerMask)) {
                transform.position = hit.point;
            }
        }

What is happening is that the position of the gameObject is overriding its old position until the object is clipping with the camera.

Body:
So, you are passing a ray, a RayCastHit, and a number into Physics.Raycast and it's recognising them like this:

Physics.Raycast (ray, hit, distance)

Any time you do a raycast with a layer mask you need to set the distance of the cast first because that's what all the raycast methods expect as the first number after the hit to use. Here's a version that should work using Mathf.Infinity as the distance:

if (Input.GetMouseButton(0)) {
    RaycastHit hit;
    int layerMask = (1 << 8); // Plane's Layer
    var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    if (Physics.Raycast (ray, out hit, Mathf.Infinity, layerMask)) {
        transform.position = hit.point;
    }
}


答:
Unfortunately C++ offers only a limited set of operators for overloading, and for them only a certain amount of parameters are allowed. See this.

#define ~ ->= preprocessor command doesn't work because it replaces in the wrong direction, and more importantly it is an invalid macro name as it contains more than just alphanumeric characters(as  HolyBlackCat pointed out). You could use some other valid name however, though I would highly advise against that.

```<code>//Raw.cpp
#define MY_OPERATORxx operator^
#define xx ^
void A::MY_OPERATORxx(const Node &n); // --> void A::operator^(const Node &n);

A{} xx A{}; // --> A{} ^ A {}
</code>```

Title: Defining (overloading) a custom C++ operator

Body:
Unfortunately C++ offers only a limited set of operators for overloading, and for them only a certain amount of parameters are allowed. See this.

#define ~ ->= preprocessor command doesn't work because it replaces in the wrong direction, and more importantly it is an invalid macro name as it contains more than just alphanumeric characters(as  HolyBlackCat pointed out). You could use some other valid name however, though I would highly advise against that.

//Raw.cpp
#define MY_OPERATORxx operator^
#define xx ^
void A::MY_OPERATORxx(const Node &n); // --> void A::operator^(const Node &n);

A{} xx A{}; // --> A{} ^ A {}


问:
Enabling Chrome Extension in Incognito Mode via CLI flags?
I'm using selenium to test a chrome extension and part of the extension requires the user to be in incognito mode. Currently, I've not been able to enable the extension to be allowed in incognito mode upon startup except by adding the argument user-data-dir=/path/to/directory.

The problem with this is that it loads the extension from the depths of my file system, rather than in a way I can check into git.

I've also tried navigating selenium to the chrome extensions settings page but it seems that selenium can't drive chrome:// pages.

Any ideas on to how to enable incognito on the chrome extension on boot of the chrome driver?

答:
Here is the solution that will work with the latest version of Chrome 74.

Navigate to chrome://extensions

Click on Details button for your desired extension

Copy the url (This contains your extension id)

Now we have to navigate to the above url and then click on the  allow in incognito toggle.

Java:

```<code>driver.get("chrome://extensions/?id=bhghoamapcdpbohphigoooaddinpkbai");
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.querySelector('extensions-manager').shadowRoot.querySelector('#viewManager > extensions-detail-view.active').shadowRoot.querySelector('div#container.page-container > div.page-content > div#options-section extensions-toggle-row#allow-incognito').shadowRoot.querySelector('label#label input').click()");
</code>```

Python:

```<code>driver.get("chrome://extensions/?id=bhghoamapcdpbohphigoooaddinpkbai")
driver.execute_script("return document.querySelector('extensions-manager').shadowRoot.querySelector('#viewManager > extensions-detail-view.active').shadowRoot.querySelector('div#container.page-container > div.page-content > div#options-section extensions-toggle-row#allow-incognito').shadowRoot.querySelector('label#label input').click()");
</code>```

Continue Reading, if you want to know how and why

Root Cause:

As part of enhancements to the chrome browser, google moved all the chrome option in to shadow dom. So you can not access allow in incognito toggle element as selenium find_element method which will point to the original dom of the page. So we have to switch to the shadow dom and access the elements in the shadow tree.

Details:

Shadow DOM:

Note: We will be referring to the terms shown in the picture. So please go through the picture for better understanding.

Solution:

In order to work with shadow element first we have to find the shadow host to which the shadow dom is attached. Here is the simple method to get the shadow root based on the shadowHost.

```<code>private static WebElement getShadowRoot(WebDriver driver,WebElement shadowHost) {
    JavascriptExecutor js = (JavascriptExecutor) driver;
    return (WebElement) js.executeScript("return arguments[0].shadowRoot", shadowHost);
}
</code>```

And then you can access the shadow tree element using the shadowRoot Element.

```<code>// get the shadowHost in the original dom using findElement
WebElement shadowHost = driver.findElement(By.cssSelector("shadowHost_CSS"));
// get the shadow root
WebElement shadowRoot = getShadowRoot(driver,shadowHost);
// access shadow tree element
WebElement shadowTreeElement = shadowRoot.findElement(By.cssSelector("shadow_tree_element_css"));
</code>```

In order to simplify all the above steps created the below method.

```<code>public static WebElement getShadowElement(WebDriver driver,WebElement shadowHost, String cssOfShadowElement) {
    WebElement shardowRoot = getShadowRoot(driver, shadowHost);
    return shardowRoot.findElement(By.cssSelector(cssOfShadowElement));
}
</code>```

Now you can get the shadowTree Element with single method call

```<code>WebElement shadowHost = driver.findElement(By.cssSelector("shadowHost_CSS_Goes_here));
WebElement shadowTreeElement = getShadowElement(driver,shadowHost,"shadow_tree_element_css");
</code>```

And perform the operations as usual like .click(), .getText().

```<code>shadowTreeElement.click()
</code>```

This Looks simple when you have only one level of shadow DOM. But here, in this case we have multiple levels of shadow doms. So we have to access the element by reaching each shadow host and root.

Below is the snippet using the methods that mentioned above (getShadowElement and getShadowRoot)

```<code>// Locate shadowHost on the current dom
WebElement shadowHostL1 = driver.findElement(By.cssSelector("extensions-manager"));

// now locate the shadowElement by traversing all shadow levels
WebElement shadowElementL1 = getShadowElement(driver, shadowHostL1, "#viewManager > extensions-detail-view.active");
WebElement shadowElementL2 = getShadowElement(driver, shadowElementL1,"div#container.page-container > div.page-content > div#options-section extensions-toggle-row#allow-incognito");
WebElement allowToggle = shadowElementL2.findElement(By.cssSelector("label#label input"));
allowToggle.click();
</code>```

You can achieve all the above steps in single js call as at mentioned at the beginning of the answer (added below just to reduce the confusion).

```<code>WebElement allowToggle = (WebElement) js.executeScript("return document.querySelector('extensions-manager').shadowRoot.querySelector('#viewManager > extensions-detail-view.active').shadowRoot.querySelector('div#container.page-container > div.page-content > div#options-section extensions-toggle-row#allow-incognito').shadowRoot.querySelector('label#label input')");
</code>```

Body:
Here is the solution that will work with the latest version of Chrome 74.

Navigate to chrome://extensions

Click on Details button for your desired extension

Copy the url (This contains your extension id)

Now we have to navigate to the above url and then click on the  allow in incognito toggle.

Java:

driver.get("chrome://extensions/?id=bhghoamapcdpbohphigoooaddinpkbai");
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.querySelector('extensions-manager').shadowRoot.querySelector('#viewManager > extensions-detail-view.active').shadowRoot.querySelector('div#container.page-container > div.page-content > div#options-section extensions-toggle-row#allow-incognito').shadowRoot.querySelector('label#label input').click()");

Python:

driver.get("chrome://extensions/?id=bhghoamapcdpbohphigoooaddinpkbai")
driver.execute_script("return document.querySelector('extensions-manager').shadowRoot.querySelector('#viewManager > extensions-detail-view.active').shadowRoot.querySelector('div#container.page-container > div.page-content > div#options-section extensions-toggle-row#allow-incognito').shadowRoot.querySelector('label#label input').click()");

Continue Reading, if you want to know how and why

Root Cause:

As part of enhancements to the chrome browser, google moved all the chrome option in to shadow dom. So you can not access allow in incognito toggle element as selenium find_element method which will point to the original dom of the page. So we have to switch to the shadow dom and access the elements in the shadow tree.

Details:

Shadow DOM:

Note: We will be referring to the terms shown in the picture. So please go through the picture for better understanding.

Solution:

In order to work with shadow element first we have to find the shadow host to which the shadow dom is attached. Here is the simple method to get the shadow root based on the shadowHost.

private static WebElement getShadowRoot(WebDriver driver,WebElement shadowHost) {
    JavascriptExecutor js = (JavascriptExecutor) driver;
    return (WebElement) js.executeScript("return arguments[0].shadowRoot", shadowHost);
}

And then you can access the shadow tree element using the shadowRoot Element.

// get the shadowHost in the original dom using findElement
WebElement shadowHost = driver.findElement(By.cssSelector("shadowHost_CSS"));
// get the shadow root
WebElement shadowRoot = getShadowRoot(driver,shadowHost);
// access shadow tree element
WebElement shadowTreeElement = shadowRoot.findElement(By.cssSelector("shadow_tree_element_css"));

In order to simplify all the above steps created the below method.

public static WebElement getShadowElement(WebDriver driver,WebElement shadowHost, String cssOfShadowElement) {
    WebElement shardowRoot = getShadowRoot(driver, shadowHost);
    return shardowRoot.findElement(By.cssSelector(cssOfShadowElement));
}

Now you can get the shadowTree Element with single method call

WebElement shadowHost = driver.findElement(By.cssSelector("shadowHost_CSS_Goes_here));
WebElement shadowTreeElement = getShadowElement(driver,shadowHost,"shadow_tree_element_css");

And perform the operations as usual like .click(), .getText().

shadowTreeElement.click()

This Looks simple when you have only one level of shadow DOM. But here, in this case we have multiple levels of shadow doms. So we have to access the element by reaching each shadow host and root.

Below is the snippet using the methods that mentioned above (getShadowElement and getShadowRoot)

// Locate shadowHost on the current dom
WebElement shadowHostL1 = driver.findElement(By.cssSelector("extensions-manager"));

// now locate the shadowElement by traversing all shadow levels
WebElement shadowElementL1 = getShadowElement(driver, shadowHostL1, "#viewManager > extensions-detail-view.active");
WebElement shadowElementL2 = getShadowElement(driver, shadowElementL1,"div#container.page-container > div.page-content > div#options-section extensions-toggle-row#allow-incognito");
WebElement allowToggle = shadowElementL2.findElement(By.cssSelector("label#label input"));
allowToggle.click();

You can achieve all the above steps in single js call as at mentioned at the beginning of the answer (added below just to reduce the confusion).

WebElement allowToggle = (WebElement) js.executeScript("return document.querySelector('extensions-manager').shadowRoot.querySelector('#viewManager > extensions-detail-view.active').shadowRoot.querySelector('div#container.page-container > div.page-content > div#options-section extensions-toggle-row#allow-incognito').shadowRoot.querySelector('label#label input')");


问:
Is it better practice to performSegueWithIdentifier or presentViewController
If I am using storyboards, is it better practice to create a segue and use performSegueWithIdentifier or just use presentViewController to move the user from one View Controller to the next.

For this example, let's assume we are using Swift 5 and I have 2 view controllers: a TableView of Contacts on MainViewController and the details of that Contact on DetailViewController.

In my code, I am using presentViewController, but as I am new to iOS development, I'm not sure if this is the best approach.

答:
Let's assume for purposes of illustration that the situation in the storyboard is as follows:

```<code>ViewController1
    |----> modal segue "toVC2" emanating from ViewController1
        |----> ViewController2, identifier "VC2"
</code>```

Then in ViewController1 code there is absolutely no functional or effective difference between these two things:

Call performSegue with identifier "toVC2"

Call instantiateViewController on the storyboard with identifier "VC2" and call present

Having said that, I will make a case for each way being "better" than the other.

Why the segue might be better

The segue in my example doesn't look much better because we still have to use code to call performSegue. However, suppose that the segue emanates not from the view controller but from a button in the view controller's view. That is an action segue and now the segue will be performed automatically when the user taps our button, with no code needed to perform it. You don't even need to know the identifier. (String identifiers are a great way to make a mistake.)

Why instantiate and present might be better

There is something very horrible about segues, whether it's an action segue or a manually triggered segue with performSegue — namely, when (as so often happens) you want to pass data from the first view controller to the second. If you use a segue, you must do the data-passing in an implementation of prepare(for:sender:). This is very messy because you have to check the segue identifier and cast the destination to the correct class. Moreover, if there is more than one segue, prepare becomes a messy bottleneck. And if we also called performSegue, we are operating in two different places — the method where we called performSegue, and the separate implementation of prepare.

By contrast, if we call instantiateViewController, what comes back to us is the view controller instance itself. We still have to cast, but now we can pass the data right then and there, without "waiting" for prepare and without passing through a bottleneck. Thus this is a far more legible and encapsulated way of proceeding.

Also, this may seem obvious, but a nice thing about saying present is that this tells us right there in the code what the transition is. If you just use a segue identifier, the fact that this is a modal segue is hidden off in the storyboard.

Which do I prefer?

Neither. I prefer not to use storyboards at all for presented view controllers if I can help it. I use a view controller and eponymous nib. That way, I simply instantiate the view controller itself and pass it the data and present it, with no need to cast and no need for any identifiers.

So am I saying that storyboards are no good at all?

No. Storyboards have the virtue of mapping out the scene structure of your app, especially if you do use segues. If you are not going to use a segue to a view controller, however, then I don't really see the point of keeping that view controller in a storyboard in the first place. The eponymous nib mechanism is clearer and cleaner. Moreover, I regard the prepare(for:sender:) mechanism as a near-fatal flaw in the entire storyboard architecture; a huge majority of mistakes shown on Stack Overflow are a consequence of this flaw.

[EDIT Note that a lot of my objections to segues will fall away in iOS 13, where the source view controller will be able to use code to call an initializer of the destination view controller.]

Body:
Let's assume for purposes of illustration that the situation in the storyboard is as follows:

ViewController1
    |----> modal segue "toVC2" emanating from ViewController1
        |----> ViewController2, identifier "VC2"

Then in ViewController1 code there is absolutely no functional or effective difference between these two things:

Call performSegue with identifier "toVC2"

Call instantiateViewController on the storyboard with identifier "VC2" and call present

Having said that, I will make a case for each way being "better" than the other.

Why the segue might be better

The segue in my example doesn't look much better because we still have to use code to call performSegue. However, suppose that the segue emanates not from the view controller but from a button in the view controller's view. That is an action segue and now the segue will be performed automatically when the user taps our button, with no code needed to perform it. You don't even need to know the identifier. (String identifiers are a great way to make a mistake.)

Why instantiate and present might be better

There is something very horrible about segues, whether it's an action segue or a manually triggered segue with performSegue — namely, when (as so often happens) you want to pass data from the first view controller to the second. If you use a segue, you must do the data-passing in an implementation of prepare(for:sender:). This is very messy because you have to check the segue identifier and cast the destination to the correct class. Moreover, if there is more than one segue, prepare becomes a messy bottleneck. And if we also called performSegue, we are operating in two different places — the method where we called performSegue, and the separate implementation of prepare.

By contrast, if we call instantiateViewController, what comes back to us is the view controller instance itself. We still have to cast, but now we can pass the data right then and there, without "waiting" for prepare and without passing through a bottleneck. Thus this is a far more legible and encapsulated way of proceeding.

Also, this may seem obvious, but a nice thing about saying present is that this tells us right there in the code what the transition is. If you just use a segue identifier, the fact that this is a modal segue is hidden off in the storyboard.

Which do I prefer?

Neither. I prefer not to use storyboards at all for presented view controllers if I can help it. I use a view controller and eponymous nib. That way, I simply instantiate the view controller itself and pass it the data and present it, with no need to cast and no need for any identifiers.

So am I saying that storyboards are no good at all?

No. Storyboards have the virtue of mapping out the scene structure of your app, especially if you do use segues. If you are not going to use a segue to a view controller, however, then I don't really see the point of keeping that view controller in a storyboard in the first place. The eponymous nib mechanism is clearer and cleaner. Moreover, I regard the prepare(for:sender:) mechanism as a near-fatal flaw in the entire storyboard architecture; a huge majority of mistakes shown on Stack Overflow are a consequence of this flaw.

[EDIT Note that a lot of my objections to segues will fall away in iOS 13, where the source view controller will be able to use code to call an initializer of the destination view controller.]


问:
Send function(with parameters) inside the JSON object
I am trying to pass function(with parameter) to another function inside the json object. It always undefined and I couldn't find the reason.

First triggering packtNs.graduateForm.loadEvent function. Then sending
packtNs.common.populateWithTodaysDate("packt_supervisor", "packt_postgraduatestartdate") function to packtNs.common.wireOnChangeEvents function.

Here is my code:

```<code>var packtNs = packtNs || {};

packtNs.common = packtNs.common || {};

/**
* A method that populates the post graduate start date
* when the supervisor lookup is populated.
* @returns {Void}
*/

packtNs.common.populateWithTodaysDate = function(attributeToMonitor, dateAttributeToChange)
{
    console.log("Populatewithtodaysdate function triggered");
}

packtNs.common.wireOnChangeEvents =
    function(eventAttributeTuples){
        debugger;
        for (var i in eventAttributeTuples) {
           console.log(eventAttributeTuples[i].attribute);
           ////attribute is OK
           console.log(eventAttributeTuples[i].function);
           ////function is always undefined. eventAttributeTuples[0] object doesnt have function - tried different names
        }

}

packtNs.graduateForm = packtNs.graduateForm || {};

packtNs.graduateForm.loadEvent = function(){
    packtNs.common.wireOnChangeEvents([
        {
            attribute: "packt_supervisor",
            function:packtNs.common.populateWithTodaysDate("packt_supervisor", "packt_postgraduatestartdate")
        }
    ]);
    debugger;
}
</code>```

答: First thing, as pointed out in comments under your question, change attribute name from "function" to something different. Then I'll recommend you to try call passed string representation of function into eval method (see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval)</p>

Body:
I am trying to pass function(with parameter) to another function inside the json object. It always undefined and I couldn't find the reason.

First triggering packtNs.graduateForm.loadEvent function. Then sending
packtNs.common.populateWithTodaysDate("packt_supervisor", "packt_postgraduatestartdate") function to packtNs.common.wireOnChangeEvents function.

Here is my code:

var packtNs = packtNs || {};

packtNs.common = packtNs.common || {};

/**
* A method that populates the post graduate start date
* when the supervisor lookup is populated.
* @returns {Void}
*/

packtNs.common.populateWithTodaysDate = function(attributeToMonitor, dateAttributeToChange)
{
    console.log("Populatewithtodaysdate function triggered");
}

packtNs.common.wireOnChangeEvents =
    function(eventAttributeTuples){
        debugger;
        for (var i in eventAttributeTuples) {
           console.log(eventAttributeTuples[i].attribute);
           ////attribute is OK
           console.log(eventAttributeTuples[i].function);
           ////function is always undefined. eventAttributeTuples[0] object doesnt have function - tried different names
        }

}

packtNs.graduateForm = packtNs.graduateForm || {};

packtNs.graduateForm.loadEvent = function(){
    packtNs.common.wireOnChangeEvents([
        {
            attribute: "packt_supervisor",
            function:packtNs.common.populateWithTodaysDate("packt_supervisor", "packt_postgraduatestartdate")
        }
    ]);
    debugger;
}


问:
How to get HH:MM:SS difference using milliseconds in javascript?
I have two times like one is 145:02:31 and another one is 01:00:00 and I want to calculate the difference between these two times like 144:02:31 but right now I am getting 13:02:31 which is wrong.

Please help me thank you.

答:
// Convert time in format H:mm:ss to seconds
function hrsToSecs(hrs) {
  var b = hrs.split(':');
  return b[0]*3600 + b[1]*60 + +b[2];
}

// Convert seconds to time in format H:mm:ss
function secsToHrs(secs) {
  var z = n => (n<10? '0':'') + n;
  return (secs/3600 | 0) + ':' +
         z(secs%3600/60 | 0) + ':' +
         z(secs%60);
}

// Get different between times in H:mm:ss format
// Subtract first time from second
function timeDiff(t0, t1) {
  var diff = hrsToSecs(t1) - hrsToSecs(t0);
  return (diff < 0? '-' : '') + secsToHrs(Math.abs(diff));
}

console.log(timeDiff('1:01:01','0:01:00'))
console.log(timeDiff('01:00:00','145:02:31'));```


问:
array manipulation
So i'm trying to avoid using vectors to do this, i know it would make it easier, but i'm trying to better my understanding of pointers and arrays. So is there a way to expand and shift an array without using the vectors? Here is what i have so far:</p>

```<code>int *expand(int *&arr, int size)
{
    int *newArray;

    size = size * 2;

    newArray = new int[size * 2];
    for (int index = 0; index < size; index++)
        newArray[index] = arr[index];
    return newArray;

}
</code>```

答:
You're allocating twice as much memory as you need.

You're not deleting the old array.

You're not assigning the new pointer to arr - passing it as reference indicates that's what you intended - or that you intended to delete[] arr and assign 0 to it.

Title: array manipulation

Body:
So i'm trying to avoid using vectors to do this, i know it would make it easier, but i'm trying to better my understanding of pointers and arrays. So is there a way to expand and shift an array without using the vectors? Here is what i have so far:

int *expand(int *&arr, int size)
{
    int *newArray;

    size = size * 2;

    newArray = new int[size * 2];
    for (int index = 0; index < size; index++)
        newArray[index] = arr[index];
    return newArray;

}


问:
Check whether string in palindrome : C# code efficiency
I am coming from C background and recently started writing in C# so please don't mind if my question seems somewhat basic. Basically, i want to write a function which will return true if string is palindrome and false if not.

The string may contain characters like space, ',', ':' which i have to ignore. I have written the code as below

```<code>    static bool IsPalindrome(string s)
    {
        s = s.Replace(" ", "");
        s = s.Replace(",", "");
        s = s.Replace(":", "");

        int j = s.Length - 1;

        for(int i = 0; i < s.Length/2; i++)
        {
            if(s[i].ToString().Equals(s[j].ToString(),StringComparison.InvariantCultureIgnoreCase))
            {
                j--;
            }
            else
            {
                return false;
            }
        }
        return true;

    }
</code>```

where the function will be invoked with the following string

```<code>string s = "A man, a plan, a canal: Panama";
</code>```

I read in the documentation that in C#, string are immutable so each time i do a operation like replace or ToString, a new copy is getting created.

So i wanted to check that
i).  Is this code efficient?
ii). If not, how to make it more efficient.

答:
The obligatory short but inefficient LINQ solution:</p>

```<code>static bool IsPalindrome(string s)
{
    return s.Where(Char.IsLetterOrDigit).Take(s.Length / 2)
        .SequenceEqual(s.Reverse().Where(Char.IsLetterOrDigit).Take(s.Length / 2));
}
</code>```

Body:
I am coming from C background and recently started writing in C# so please don't mind if my question seems somewhat basic. Basically, i want to write a function which will return true if string is palindrome and false if not.

The string may contain characters like space, ',', ':' which i have to ignore. I have written the code as below

    static bool IsPalindrome(string s)
    {
        s = s.Replace(" ", "");
        s = s.Replace(",", "");
        s = s.Replace(":", "");

        int j = s.Length - 1;

        for(int i = 0; i < s.Length/2; i++)
        {
            if(s[i].ToString().Equals(s[j].ToString(),StringComparison.InvariantCultureIgnoreCase))
            {
                j--;
            }
            else
            {
                return false;
            }
        }
        return true;

    }

where the function will be invoked with the following string

string s = "A man, a plan, a canal: Panama";

I read in the documentation that in C#, string are immutable so each time i do a operation like replace or ToString, a new copy is getting created.

So i wanted to check that
i).  Is this code efficient?
ii). If not, how to make it more efficient.

Body:
The obligatory short but inefficient LINQ solution:

static bool IsPalindrome(string s)
{
    return s.Where(Char.IsLetterOrDigit).Take(s.Length / 2)
        .SequenceEqual(s.Reverse().Where(Char.IsLetterOrDigit).Take(s.Length / 2));
}


问:
LINQ Group elements that are equal together
I have a simple question on LINQ and haven't found an answer that directly addresses my question. Say I have an arbitrary collection of objects: {cat, apple, orange, cat, orange, apple, cat}. I want to order to use LINQ to order these lists by equality, e.g. so now the collection reads {apple, apple, orange, orange, cat, cat, cat}. It doesn't matter what order the types are (i.e. whether apple comes first or cat, for example), only that they are appropriately grouped.

Say I have access to Equals() or some boolean method to determine if any two instances are equal. How would I do this?

答:
As you can access the Equals() and it works, the GetHashCode() have to be rewritten and could work now. So, you can order by object.GetHashCode(), it will give you the result.

The code will just like @zhulien's answer.

```<code>collection.OrderBy(o => o.GetHashCode());
</code>```

Body:
As you can access the Equals() and it works, the GetHashCode() have to be rewritten and could work now. So, you can order by object.GetHashCode(), it will give you the result.

The code will just like @zhulien's answer.

collection.OrderBy(o => o.GetHashCode());