问:
Java Style / Best Practice - passing fields to methods vs accessing directly
In Java, given the following class:

```<code>public class MyClass {
   private final Dependency dependency;
   public MyClass(Dependency dependency)
   {
       this.dependency = dependency;
   }

   public void doWork()
   {
       // validate dependency...
   }
</code>```

The doWork method needs to invoke a method that uses dependency.

Which of the following two variations is considered "best practice", and why?

```<code>   // Access dependency directly
   void validateDependency()
   {
        this.dependency.something();
   }

   // access dependency as passed to the method
   void validateDependency(Dependency dependency)
   {
       dependency.something();
   }
</code>```

I find myself favouring the latter, passing the dependency directly to the method, as it makes the method easier to test in isolation (albeit, marginally).

However, I'm interested in the java convention / best practice here.

答:
Well, in your example you are asking the function to do something with Dependency which lends itself to a static function, not a member function.

My rule of thumb is: Use members directly when calling a method on an object that owns the member but pass references when doing/testing something directly related to the dependency and favor static methods for the latter

That a bit verbose but I hope it helps. As always try to "do the right thing" and differences this small won't likely make a huge impact on maintenance or readability of your code.

Body:
In Java, given the following class:

public class MyClass {
   private final Dependency dependency;
   public MyClass(Dependency dependency)
   {
       this.dependency = dependency;
   }

   public void doWork()
   {
       // validate dependency...
   }

The doWork method needs to invoke a method that uses dependency.

Which of the following two variations is considered "best practice", and why?

   // Access dependency directly
   void validateDependency()
   {
        this.dependency.something();
   }

   // access dependency as passed to the method
   void validateDependency(Dependency dependency)
   {
       dependency.something();
   }

I find myself favouring the latter, passing the dependency directly to the method, as it makes the method easier to test in isolation (albeit, marginally).

However, I'm interested in the java convention / best practice here.


来源: stackexchange

问:
passing dates in Python
I have the following issue with python with script in linux:
I am executing my_query.py passing as a parameter the date 2017-03-01

```<code>python my_query.py 2017-03-01
</code>```

How can I create a loop to iterate over that date so it cover the entire month (from date 1 to end of month).

Thanks!

答:
You can use monthrange from calendar

```<code>import sys
from calendar import monthrane

datestr = sys.argv[1]

year, month, day = datestr.split('-')

for day in xrange(1, monthrange(int(year), int(month))[1] + 1):

    print day
</code>```

ContentLicense: CC BY-SA 3.0

Title: passing dates in Python

Body:
I have the following issue with python with script in linux:
I am executing my_query.py passing as a parameter the date 2017-03-01

python my_query.py 2017-03-01

How can I create a loop to iterate over that date so it cover the entire month (from date 1 to end of month).

Thanks!

Body:
You can use monthrange from calendar

import sys
from calendar import monthrane

datestr = sys.argv[1]

year, month, day = datestr.split('-')

for day in xrange(1, monthrange(int(year), int(month))[1] + 1):

    print day


问:
Error with Stack Function in R
I'm relatively new to R and have been trying to find a solution to an error I am getting when I attempt to stack data. I'm trying to run a one-way anova with three variables. When I attempt to stack the data with stack("Combined_Groups") I get the following error:

Error in rep.int(names(x), lengths(x)) :
       unimplemented type 'NULL' in 'rep3'

I've copied my R syntax below in case that is helpful.

```<code>rpeople1 <- c(.74, .70,  .36, .29, .33, .51, .34)
rmixed1  <- c(.58, .40,  .02, .12, .32, .06, .26)
rthing1  <- c(.25, .05, -.06, .07, .10, .13, .19)

summary(rpeople1)
#   Min.  1st Qu. Median    Mean 3rd Qu.    Max.
# 0.2900  0.3350  0.3600  0.4671  0.6050  0.7400

Combined_Groups <- data.frame(cbind("rpeople1, rmixed1, rthing1"))
Combined_Groups
# cbind..rpeople1..rmixed1..rthing1..
# 1          rpeople1, rmixed1, rthing1
summary(Combined_Groups)
#         cbind..rpeople1..rmixed1..rthing1..
# rpeople1, rmixed1, rthing1:1

Stacked_Groups <-stack("Combined_Groups")
# Error in rep.int(names(x), lengths(x)) :
#  unimplemented type 'NULL' in 'rep3'
</code>```

答:
Since you are using the inverted commas " " around your created objects, R interprets them as a character vector.
The function stack expects a proper data.frame and yours is only one observation of one column.
Removing the " " from your code in the construction of the data.frame and the stack call yields the solution:

```<code>rpeople1 <- c(.74,.70,.36,.29,.33,.51,.34)
rmixed1 <- c(.58,.40,.02,.12,.32,.06,.26)
rthing1 <- c(.25,.05,-.06,.07,.10,.13,.19)

Combined_Groups <- data.frame(cbind(rpeople1, rmixed1, rthing1))
Combined_Groups
Stacked_Groups <- stack(Combined_Groups)
Stacked_Groups
</code>```

Title: Error with Stack Function in R

Body:
I'm relatively new to R and have been trying to find a solution to an error I am getting when I attempt to stack data. I'm trying to run a one-way anova with three variables. When I attempt to stack the data with stack("Combined_Groups") I get the following error:

Error in rep.int(names(x), lengths(x)) :
       unimplemented type 'NULL' in 'rep3'

I've copied my R syntax below in case that is helpful.

rpeople1 <- c(.74, .70,  .36, .29, .33, .51, .34)
rmixed1  <- c(.58, .40,  .02, .12, .32, .06, .26)
rthing1  <- c(.25, .05, -.06, .07, .10, .13, .19)

summary(rpeople1)
#   Min.  1st Qu. Median    Mean 3rd Qu.    Max.
# 0.2900  0.3350  0.3600  0.4671  0.6050  0.7400

Combined_Groups <- data.frame(cbind("rpeople1, rmixed1, rthing1"))
Combined_Groups
# cbind..rpeople1..rmixed1..rthing1..
# 1          rpeople1, rmixed1, rthing1
summary(Combined_Groups)
#         cbind..rpeople1..rmixed1..rthing1..
# rpeople1, rmixed1, rthing1:1

Stacked_Groups <-stack("Combined_Groups")
# Error in rep.int(names(x), lengths(x)) :
#  unimplemented type 'NULL' in 'rep3'

Body:
Since you are using the inverted commas " " around your created objects, R interprets them as a character vector.
The function stack expects a proper data.frame and yours is only one observation of one column.
Removing the " " from your code in the construction of the data.frame and the stack call yields the solution:

rpeople1 <- c(.74,.70,.36,.29,.33,.51,.34)
rmixed1 <- c(.58,.40,.02,.12,.32,.06,.26)
rthing1 <- c(.25,.05,-.06,.07,.10,.13,.19)

Combined_Groups <- data.frame(cbind(rpeople1, rmixed1, rthing1))
Combined_Groups
Stacked_Groups <- stack(Combined_Groups)
Stacked_Groups


问:
mongo chunk not delete after documents TTL

mongo config infomations:

mongo version: 3.2.10

mongo shard with key: {secretTaskId:1, time: 1}

TTL index: {time: 1}, {expireAfterSeconds: 60 * 60 * 24 * 8, background: true} # 8 days

mongo balancer is enable & running: sh.isBalancerRunning() ===> true

problem description

The TTL config works correctly, and the documents are auto removed on timeout. But the chunks in config database got not updated (deleted), the chunks remained as the documents are gone.

e.g. :
js
// chunks in config database
// As the date is 2017-06-07 now, documents create in 2016 had removed, but the chunks for them are still remain. ( more old chunks can be found, not single.)
{
    "_id": "****",
    "lastmod": Timestamp(3, 0),
    "lastmodEpoch": ObjectId("58253bbffbb3d96a85eccef1"),
    "ns": "***",
    "min": {"secretTaskId": "***", "time": ISODate("2016-11-11T03:32:40.045Z")},
    "max": {"secretTaskId": "***", "time": ISODate("2016-11-14T09:20:45.684Z")},
    "shard": "***"
}

As the chunks not delete, the mongo shard cluster is not balance property. I think the balancer get no ideal about the actual documents distributed, and work uncorrectly base on the errror chunks.

I got no solution after lots search. Anyone can help? Thanks.

答:
Chunk ranges in MongoDB do not disappear when the documents contained in them are removed. Think of chunk ranges as buckets, even though you emptied the water from the bucket, the bucket itself still exists. Chunks are very similar. They will get split as they fill up to support better balancing, but they do not automatically go away when emptied.

If you wish to "get rid" of these chunks, you must merge them. You can find more information on merging chunks using the mergeChunks command in the MongoDB Docs.


问:
How can I convert float to int?
```<code>cube1.name = string.Format("Terrain_{0}_{1}",
    (int)Terrain.activeTerrain.transform.position.x + tilePositionInLocalSpace.x,
    (int)Terrain.activeTerrain.transform.position.z + tilePositionInLocalSpace.y);
</code>```

Tried to cast it for int but it didn't change much.
The name of each cube is still for example: Terrain_6.5_5.5. But I want the name to be Terrain_6_5.

tilePositionInLocalSpace is vector3 type and both x are float type.

答:
Just cast the result of the addition:

```<code>(int) (x + y);
</code>```

And then string.format ()...

Title: How can I convert float to int?

Body:
cube1.name = string.Format("Terrain_{0}_{1}",
    (int)Terrain.activeTerrain.transform.position.x + tilePositionInLocalSpace.x,
    (int)Terrain.activeTerrain.transform.position.z + tilePositionInLocalSpace.y);

Tried to cast it for int but it didn't change much.
The name of each cube is still for example: Terrain_6.5_5.5. But I want the name to be Terrain_6_5.

tilePositionInLocalSpace is vector3 type and both x are float type.

Body:
Just cast the result of the addition:

(int) (x + y);

And then string.format ()...


问:
Display only some of the page numbers by django pagination
I am using the django paginator in the template. Its working ok, but not good when there's large numbers of pages.

views.py:

```<code>def blog(request):
    blogs_list = Blog.objects.all()

    paginator = Paginator(blogs_list, 1)

    try:
        page = int(request.GET.get('page', '1'))
    except:
        page = 1

    try:
        blogs = paginator.page(page)
    except(EmptyPage, InvalidPage):
        blogs = paginator.page(page)
    return render(request, 'blogs.html', {
        'blogs':blogs
        })
</code>```

snippet of the template:

```<code>  <div class="prev_next">

    {% if blogs.has_previous %}
      <a class="prev btn btn-info" href="?page={{blogs.previous_page_number}}">Prev</a>
    {% endif %}
    {% if blogs.has_next %}
      <a class="next btn btn-info" href="?page={{blogs.next_page_number}}">Next</a>
    {% endif %}
    <div class="pages">
      <ul>
      {% for pg in blogs.paginator.page_range %}
        {% if blogs.number == pg %}
          <li><a href="?page={{pg}}" class="btn btn-default">{{pg}}</a></li>
        {% else %}
          <li><a href="?page={{pg}}" class="btn">{{pg}}</a></li>
        {% endif %}
      {% endfor %}
      </ul>
    </div>
    <span class="clear_both"></span>

  </div>
</code>```

Now it looks like this:

What do I do to display only 7 page numbers and not all of it ranging from the current page number, like this:

```<code>Prev 1 (2) 3 4 5 Next
</code>```

I hope I was clear, if not please ask. Your help and guidance will be very much appreciated. Thank you.

答:
You could also extend Paginator class.

```<code>class BootstrapPaginator(Paginator):
    def __init__(self, *args, **kwargs):
        """
        :param wing_pages: How many pages will be shown before and after current page.
        """
        self.wing_pages = kwargs.pop('wing_pages', 3)
        super(BootstrapPaginator, self).__init__(*args, **kwargs)

    def _get_page(self, *args, **kwargs):
        self.page = super(BootstrapPaginator, self)._get_page(*args, **kwargs)
        return self.page

    @property
    def page_range(self):
        return range(max(self.page.number - self.wing_pages, 1),
                     min(self.page.number + self.wing_pages + 1, self.num_pages + 1))
</code>```

Then in template:

```<code>{% for num in action_list.paginator.page_range %}
    {% if action_list.number == num %}
         <li class="active"><a href="?page={{ num }}">{{ num }}</a></li>
    {% else %}
         <li><a href="?page={{ num }}">{{ num }}</a></li>
    {% endif %}
{% endfor %}
</code>```

Now page_range will only consist of 7 items. wing_pages + current page + wing_pagescustom django paginator for bootstrap

Body:
I am using the django paginator in the template. Its working ok, but not good when there's large numbers of pages.

views.py:

def blog(request):
    blogs_list = Blog.objects.all()

    paginator = Paginator(blogs_list, 1)

    try:
        page = int(request.GET.get('page', '1'))
    except:
        page = 1

    try:
        blogs = paginator.page(page)
    except(EmptyPage, InvalidPage):
        blogs = paginator.page(page)
    return render(request, 'blogs.html', {
        'blogs':blogs
        })

snippet of the template:

    {% if blogs.has_previous %}
      Prev
    {% endif %}
    {% if blogs.has_next %}
      Next
    {% endif %}

      {% for pg in blogs.paginator.page_range %}
        {% if blogs.number == pg %}

{{pg}}

        {% else %}

{{pg}}

        {% endif %}
      {% endfor %}

Now it looks like this:

What do I do to display only 7 page numbers and not all of it ranging from the current page number, like this:

Prev 1 (2) 3 4 5 Next

I hope I was clear, if not please ask. Your help and guidance will be very much appreciated. Thank you.

Body:
You could also extend Paginator class.

class BootstrapPaginator(Paginator):
    def __init__(self, *args, **kwargs):
        """
        :param wing_pages: How many pages will be shown before and after current page.
        """
        self.wing_pages = kwargs.pop('wing_pages', 3)
        super(BootstrapPaginator, self).__init__(*args, **kwargs)

    def _get_page(self, *args, **kwargs):
        self.page = super(BootstrapPaginator, self)._get_page(*args, **kwargs)
        return self.page

    @property
    def page_range(self):
        return range(max(self.page.number - self.wing_pages, 1),
                     min(self.page.number + self.wing_pages + 1, self.num_pages + 1))

Then in template:

{% for num in action_list.paginator.page_range %}
    {% if action_list.number == num %}
         <li class="active"><a href="?page={{ num }}">{{ num }}</a></li>
    {% else %}
         <li><a href="?page={{ num }}">{{ num }}</a></li>
    {% endif %}
{% endfor %}

Now page_range will only consist of 7 items. wing_pages + current page + wing_pagescustom django paginator for bootstrap


问:
How to get all links on a page that start with a https in link - PHP
I'm trying to get all the links on a page. So for example if a user types in https://laravel.com/ in the input field they will see all the links on that page.

I already got the concept working. Here is part of the code I have:

```<code>$website = request('website_url');

$pureURL = 'http://www.'.$website.'/';
$doc = new \DOMDocument;
@$doc->loadHTMLFile($pureURL);

foreach ($doc->getElementsByTagName('a') as $link){
    $linkDetail[] = array('url' => $link->getAttribute('href'));
}

$pageLinks = $linkDetail;

return view('api.index', compact('result'));
</code>```

My frontend code:

```<code>@foreach($pageLinks as $key => $link)
        {{ $link['url'] }}<br />
@endforeach
</code>```

This is what I get:

The problem is, I just want to get all the links that start with https. I want to avoid the links that have a /doc in them and so on.
How would I go about doing that. Im not really good with regex, but I know there is a way you can use that.

答:
```<code>$website = request('website_url');

$pureURL = 'http://www.'.$website.'/';
$doc = new \DOMDocument;
@$doc->loadHTMLFile($pureURL);

foreach ($doc->getElementsByTagName('a') as $link){
$url = $link->getAttribute('href');
    if (strpos($url, 'https') !== 0) {
        continue;
    }
    $linkDetail[] = array('url' => $url);
}

$pageLinks = $linkDetail;

return view('api.index', compact('result'));
</code>```

Body:
I'm trying to get all the links on a page. So for example if a user types in https://laravel.com/ in the input field they will see all the links on that page.

I already got the concept working. Here is part of the code I have:

$website = request('website_url');

$pureURL = 'http://www.'.$website.'/';
$doc = new \DOMDocument;
@$doc->loadHTMLFile($pureURL);

foreach ($doc->getElementsByTagName('a') as $link){
    $linkDetail[] = array('url' => $link->getAttribute('href'));
}

$pageLinks = $linkDetail;

return view('api.index', compact('result'));

My frontend code:

@foreach($pageLinks as $key => $link)
        {{ $link['url'] }}

@endforeach

This is what I get:

The problem is, I just want to get all the links that start with https. I want to avoid the links that have a /doc in them and so on.
How would I go about doing that. Im not really good with regex, but I know there is a way you can use that.


问:
Correctness of using std::atomic<bool> in combination with std::mutex
I have written a shared priority queue class.

To signal to stop serving data I use method Cancel(), which sets a sign done to false and application is not allowed to write / read any data from the queue. I am not sure about using std::atomic<bool> in combination with std::mutex and std::condition_variable. I am not sure, if my solution is thread safe or race condition can happen:

The original version of Enqueue method is:

```<code>std::deque<T> deque;
std::mutex mtx;
std::condition_variable cv;
std::atomic<bool> done;

SharedPriorityQueue() : done(false)
{
}

~SharedPriorityQueue()
{
    Cancel();
}

void Enqueue(T item)
{
    if (done)
    {
        return;
    }

    std::lock_guard<std::mutex> lock(mtx);
    deque.push_back(item);
    cv.notify_one();
}
</code>```

However, can be the variable done (atomic bool) separated from the locking mechanism by mutex?

To cancel the queue I use this construction:

```<code>void Cancel()
{
    if (done)
    {
        return;
    }
    done = true;

    cv.notify_all();
}
</code>```

What is the best solution of the designs bellow?

```<code>// A)
void Enqueue(T item)
{
    if (done)
    {
        return;
    }

    {
        std::lock_guard<std::mutex> lock(mtx); // lock is released before notify call
        deque.push_back(item);
    }
    cv.notify_one();
}

// B)
void Enqueue(T item)
{
    {
        std::lock_guard<std::mutex> lock(mtx); // done is atomic bool and protected by the lock along with data (deque)
        if (done) // atomic bool
        {
            return;
        }

        deque.push_back(item);
    }
    cv.notify_one();
}

// C)
void Enqueue(T item)
{
    {
        std::lock_guard<std::mutex> lock(mtx); // done is NOT atomic bool and is protected by the lock along with data (deque)
        if (done) // simple bool
        {
            return;
        }

        deque.push_back(item);
    }
    cv.notify_one();
}
</code>```

Waiting staff:

```<code>bool Dequeue(T& item)
{
    std::unique_lock<std::mutex> lock(mtx);
    while (!done && deque.empty())
    {
        cv.wait(lock);
    }

    if (!deque.empty())
    {
        item = deque.front();
        deque.pop_front();
    }

    if (done)
    {
        return false;
    }
    return true;
}
</code>```

答:
To ensure correctness you must modify the data pertaining to the "condition" holding the lock that the condition_variable acquires in the .wait(...).

While not normative the clearest statement of that I can find is:

Even if the shared variable is atomic, it must be modified under the
  mutex in order to correctly publish the modification to the waiting
  thread.

Here: http://en.cppreference.com/w/cpp/thread/condition_variable

It quite explicitly exactly answers your question!

Cancel() needs to hold mtx. At which point making it atomic stops helping.

I'm not sure where the normative statement is but I do know it is the case on MSVC++ Community.

You do not need to hold the lock when you notify_one() (or notify_all())but you must hold it when you modify 'the shared state' (in this case the queue or the flag).

Body:
I have written a shared priority queue class.

To signal to stop serving data I use method Cancel(), which sets a sign done to false and application is not allowed to write / read any data from the queue. I am not sure about using std::atomic<bool> in combination with std::mutex and std::condition_variable. I am not sure, if my solution is thread safe or race condition can happen:

The original version of Enqueue method is:

std::deque<T> deque;
std::mutex mtx;
std::condition_variable cv;
std::atomic<bool> done;

SharedPriorityQueue() : done(false)
{
}

~SharedPriorityQueue()
{
    Cancel();
}

void Enqueue(T item)
{
    if (done)
    {
        return;
    }

    std::lock_guard<std::mutex> lock(mtx);
    deque.push_back(item);
    cv.notify_one();
}

However, can be the variable done (atomic bool) separated from the locking mechanism by mutex?

To cancel the queue I use this construction:

void Cancel()
{
    if (done)
    {
        return;
    }
    done = true;

    cv.notify_all();
}

What is the best solution of the designs bellow?

// A)
void Enqueue(T item)
{
    if (done)
    {
        return;
    }

    {
        std::lock_guard<std::mutex> lock(mtx); // lock is released before notify call
        deque.push_back(item);
    }
    cv.notify_one();
}

// B)
void Enqueue(T item)
{
    {
        std::lock_guard<std::mutex> lock(mtx); // done is atomic bool and protected by the lock along with data (deque)
        if (done) // atomic bool
        {
            return;
        }

        deque.push_back(item);
    }
    cv.notify_one();
}

// C)
void Enqueue(T item)
{
    {
        std::lock_guard<std::mutex> lock(mtx); // done is NOT atomic bool and is protected by the lock along with data (deque)
        if (done) // simple bool
        {
            return;
        }

        deque.push_back(item);
    }
    cv.notify_one();
}

Waiting staff:

bool Dequeue(T& item)
{
    std::unique_lock<std::mutex> lock(mtx);
    while (!done && deque.empty())
    {
        cv.wait(lock);
    }

    if (!deque.empty())
    {
        item = deque.front();
        deque.pop_front();
    }

    if (done)
    {
        return false;
    }
    return true;
}


问:
how can I calculate the multi-label top k precisions with tensorflow?
My task is to predict the five most probable tags in a sentence. And now I've got unscaled logits from the output(dense connect) layer:

```<code>with tf.name_scope("output"):
    scores = tf.nn.xw_plus_b(self.h_drop, W,b, name="scores")
    predictions = tf.nn.top_k(self.scores, 5) # should be the k highest score
with tf.name_scope("accuracy"):
    labels = input_y  # its shape is (batch_size, num_classes)
    # calculate the top k accuracy
</code>```

now predictions are just like [3,1,2,50,12] (3,1... are indexes of the highest scores), while labels are in "multi-hot" form: [0,1,0,1,1,0...].
 In python, i can simply write

```<code>correct_preds = [input_y[i]==1 for i in predictions]
weighted = np.dot(correct_preds, [5,4,3,2,1]) # weighted by rank
recall  = sum(correct_preds) /sum(input_y)
precision =sum(correct_preds)/len(correct_preds)
</code>```

but in tensorflow, what form shoud I use to complete this task?

答:
Solution

I've coded up an example of how to do the calculations.  All of the inputs in this example are coded as tf.constant but of course you can substitute your variables.

The main trick is the matrix multiplications.  First is input_y reshaped to be 2d times a [1x5] ones matrix called to_top5.  The second is correct_preds by the weighted_matrix.

Code

```<code>import tensorflow as tf

input_y = tf.constant( [5,2,9,1] , dtype=tf.int32 )

predictions = tf.constant( [[9,3,5,2,1],[8,9,0,6,5],[1,9,3,4,5],[1,2,3,4,5]])

to_top5       = tf.constant( [[1,1,1,1,1]] , dtype=tf.int32 )
input_y_for_top5 = tf.matmul( tf.reshape(input_y,[-1,1]) , to_top5 )

correct_preds = tf.cast( tf.equal( input_y_for_top5 , predictions ) , dtype=tf.float16 )

weighted_matrix = tf.constant( [[5.],[4.],[3.],[2.],[1.]] , dtype=tf.float16 )

weighted = tf.matmul(correct_preds,weighted_matrix)

recall = tf.reduce_sum(correct_preds) / tf.cast( tf.reduce_sum(input_y) , tf.float16)
precision = tf.reduce_sum(correct_preds) / tf.constant(5.0,dtype=tf.float16)

## training
# Run tensorflow and print the result
with tf.Session() as sess:
  print "\n\n=============\n\n"
  print "\ninput_y_for_top5"
  print sess.run(input_y_for_top5)
  print "\ncorrect_preds"
  print sess.run(correct_preds)
  print "\nweighted"
  print sess.run(weighted)
  print "\nrecall"
  print sess.run(recall)
  print "\nprecision"
  print sess.run(precision)
  print "\n\n=============\n\n"
</code>```

Output

```<code>=============

input_y_for_top5
[[5 5 5 5 5]
 [2 2 2 2 2]
 [9 9 9 9 9]
 [1 1 1 1 1]]

correct_preds
[[ 0.  0.  1.  0.  0.]
 [ 0.  0.  0.  0.  0.]
 [ 0.  1.  0.  0.  0.]
 [ 1.  0.  0.  0.  0.]]

weighted
[[ 3.]
 [ 0.]
 [ 4.]
 [ 5.]]

recall
0.17651

precision
0.6001

=============
</code>```

Summary

The above examples shows a batch size of 4.

The first batch has a y_label of 5, which means that the element with an index of 5 is the correct label for the first batch.  Furthermore, the prediction for the first batch is [9,3,5,2,1] which means that the prediction function thinks that the 9th element is the most likely, then element 3 is the next most likely and so on.

Let's say we want an example of a batch size of 3, then use the following code

```<code>input_y = tf.constant( [5,2,9] , dtype=tf.int32 )
predictions = tf.constant( [[9,3,5,2,1],[8,9,0,6,5],[1,9,3,4,5]])
</code>```

If we substitute in the above lines to the program we can see that indeed it calculates everything for a batch size of 3 correctly.

Body:
My task is to predict the five most probable tags in a sentence. And now I've got unscaled logits from the output(dense connect) layer:

with tf.name_scope("output"):
    scores = tf.nn.xw_plus_b(self.h_drop, W,b, name="scores")
    predictions = tf.nn.top_k(self.scores, 5) # should be the k highest score
with tf.name_scope("accuracy"):
    labels = input_y  # its shape is (batch_size, num_classes)
    # calculate the top k accuracy

now predictions are just like [3,1,2,50,12] (3,1... are indexes of the highest scores), while labels are in "multi-hot" form: [0,1,0,1,1,0...].
 In python, i can simply write

correct_preds = [input_y[i]==1 for i in predictions]
weighted = np.dot(correct_preds, [5,4,3,2,1]) # weighted by rank
recall  = sum(correct_preds) /sum(input_y)
precision =sum(correct_preds)/len(correct_preds)

but in tensorflow, what form shoud I use to complete this task?

Body:
Solution

I've coded up an example of how to do the calculations.  All of the inputs in this example are coded as tf.constant but of course you can substitute your variables.

The main trick is the matrix multiplications.  First is input_y reshaped to be 2d times a [1x5] ones matrix called to_top5.  The second is correct_preds by the weighted_matrix.

Code

import tensorflow as tf

input_y = tf.constant( [5,2,9,1] , dtype=tf.int32 )

predictions = tf.constant( [[9,3,5,2,1],[8,9,0,6,5],[1,9,3,4,5],[1,2,3,4,5]])

to_top5       = tf.constant( [[1,1,1,1,1]] , dtype=tf.int32 )
input_y_for_top5 = tf.matmul( tf.reshape(input_y,[-1,1]) , to_top5 )

correct_preds = tf.cast( tf.equal( input_y_for_top5 , predictions ) , dtype=tf.float16 )

weighted_matrix = tf.constant( [[5.],[4.],[3.],[2.],[1.]] , dtype=tf.float16 )

weighted = tf.matmul(correct_preds,weighted_matrix)

recall = tf.reduce_sum(correct_preds) / tf.cast( tf.reduce_sum(input_y) , tf.float16)
precision = tf.reduce_sum(correct_preds) / tf.constant(5.0,dtype=tf.float16)

## training
# Run tensorflow and print the result
with tf.Session() as sess:
  print "\n\n=============\n\n"
  print "\ninput_y_for_top5"
  print sess.run(input_y_for_top5)
  print "\ncorrect_preds"
  print sess.run(correct_preds)
  print "\nweighted"
  print sess.run(weighted)
  print "\nrecall"
  print sess.run(recall)
  print "\nprecision"
  print sess.run(precision)
  print "\n\n=============\n\n"

Output

=============

input_y_for_top5
[[5 5 5 5 5]
 [2 2 2 2 2]
 [9 9 9 9 9]
 [1 1 1 1 1]]

correct_preds
[[ 0.  0.  1.  0.  0.]
 [ 0.  0.  0.  0.  0.]
 [ 0.  1.  0.  0.  0.]
 [ 1.  0.  0.  0.  0.]]

weighted
[[ 3.]
 [ 0.]
 [ 4.]
 [ 5.]]

recall
0.17651

precision
0.6001

=============

Summary

The above examples shows a batch size of 4.

The first batch has a y_label of 5, which means that the element with an index of 5 is the correct label for the first batch.  Furthermore, the prediction for the first batch is [9,3,5,2,1] which means that the prediction function thinks that the 9th element is the most likely, then element 3 is the next most likely and so on.

Let's say we want an example of a batch size of 3, then use the following code

input_y = tf.constant( [5,2,9] , dtype=tf.int32 )
predictions = tf.constant( [[9,3,5,2,1],[8,9,0,6,5],[1,9,3,4,5]])

If we substitute in the above lines to the program we can see that indeed it calculates everything for a batch size of 3 correctly.


问:
Two rows in one in SQL server
The answer is too close, Thanks
But
The problem is that if too many records to be entered

```<code>           |    id   |    name   |    age    |   Tel
------------------------------------------
      1    |    1   |   Frank   |    40     |   null
      2    |    1   |   null    |    50     |   7834xx
      3    |    1   |   Alex    |    null   |   null
      4    |    1   |   null    |    20     |   null
      5    |    2   |   James   |    null   |   4121xx
</code>```

Query return the Maximum value
Like:

```<code>           |    id   |   name    |    age    |   Tel
------------------------------------------
      1    |    1    |   Frank   |    50     |  7834xx
</code>```

i need Select Query like this:

```<code>           |    id   |   name    |    age    |   Tel
------------------------------------------
      1    |    1    |   Alex    |    20     |  7834xx
</code>```

what do I do? Plz?

答:
One simple way is to get max as below:</p>

```<code> Select Id, Max(name) as [Name], Max(age) as Age, Max(Tel) as Tel
 from yourtable
 Group by Id
</code>```

Title: Two rows in one in SQL server

Body:
The answer is too close, Thanks
But
The problem is that if too many records to be entered

           |    id   |    name   |    age    |   Tel
------------------------------------------
      1    |    1   |   Frank   |    40     |   null
      2    |    1   |   null    |    50     |   7834xx
      3    |    1   |   Alex    |    null   |   null
      4    |    1   |   null    |    20     |   null
      5    |    2   |   James   |    null   |   4121xx

Query return the Maximum value
Like:

           |    id   |   name    |    age    |   Tel
------------------------------------------
      1    |    1    |   Frank   |    50     |  7834xx

i need Select Query like this:

           |    id   |   name    |    age    |   Tel
------------------------------------------
      1    |    1    |   Alex    |    20     |  7834xx

what do I do? Plz?

Body:
One simple way is to get max as below:

 Select Id, Max(name) as [Name], Max(age) as Age, Max(Tel) as Tel
 from yourtable
 Group by Id


问:
JavaScript change style of a specific child div from another child div
Let's say that we have a loop which result 3 divs with other 4 divs inside each, like this:

```<code><div class="one">
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
</div>

<div class="one">
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
</div>

<div class="one">
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
</div>
</code>```

Now, I want to change the style css with javascript. How can I make something like this in javascript and work?

document.getElementsByClassName('one')[2].document.getElementsByClassName('two')[3].style.cssText {...};

I want to change the style css of the class .two from child [3] which is inside class .one from child [2]

答:
I'm not sure if you absolutely want to do this with JS, but just in case, here's a pure CSS approach :

.one:nth-child(3) .two:nth-child(4){
  background-color : red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="one">
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
</div>

<div class="one">
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
</div>

<div class="one">
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
</div></code>```

(nth-child is 1-based)

Body:
Let's say that we have a loop which result 3 divs with other 4 divs inside each, like this:

second class

second class

second class

second class

second class

second class

second class

second class

second class

second class

second class

second class

Now, I want to change the style css with javascript. How can I make something like this in javascript and work?

document.getElementsByClassName('one')[2].document.getElementsByClassName('two')[3].style.cssText {...};

I want to change the style css of the class .two from child [3] which is inside class .one from child [2]

Body:
I'm not sure if you absolutely want to do this with JS, but just in case, here's a pure CSS approach :

.one:nth-child(3) .two:nth-child(4){
  background-color : red;
}

<div class="one">
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
</div>

<div class="one">
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
</div>

<div class="one">
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
</div>

(nth-child is 1-based)


问:
get xpath from xsl variable
I am trying to get some xpath from xsl variable using xsl ver 1.0 .
That’s  my variable:

```<code>  <xsl:variable name ="myVar">
        <RefData RefTag="test1" bbb="false" />
        <RefData RefTag="test2" bbb="false" />
        <RefData RefTag="test3" bbb="false" />
        <RefData RefTag="test4" bbb="true"  />
        <RefData RefTag="test5" bbb="false" />
        <RefData RefTag="test6" bbb="false" />
  </xsl:variable>
</code>```

I am trying to get bbb attribure value using the RefTag value:

```<code><xsl:if test="$myVar/RefData[@RefTag = 'test3']/@bbb">
</code>```

this is not working.

VS XSL Debugger returns an error:
"To use a result tree fragment in a path expression, first convert it to a node-set using the msxsl:node-set() function."

I don't understand how to use msxsl:node-set() function, and anyway I prefer not to use msxsl namesapce.

Can anyone help here?

答:
Assuming this XML:

```<code><test1>
  <RefData RefTag="test1"/>
  <RefData RefTag="test2"/>
  <RefData RefTag="test3"/>
  <RefData RefTag="test4"/>
  <RefData RefTag="test5"/>
  <RefData RefTag="test6"/>
</test1>
</code>```

Something like this could work:

```<code><xsl:template match="/">
  <xsl:apply-templates select="test1/RefData"/>
</xsl:template>

  <xsl:template match="RefData">
    <xsl:variable name="myVar">
      <xsl:choose>
        <xsl:when test="@RefTag = 'test1'">false</xsl:when>
        <xsl:when test="@RefTag = 'test2'">false</xsl:when>
        <xsl:when test="@RefTag = 'test3'">false</xsl:when>
        <xsl:when test="@RefTag = 'test4'">true</xsl:when>
        <xsl:when test="@RefTag = 'test5'">false</xsl:when>
        <xsl:when test="@RefTag = 'test6'">false</xsl:when>
        <xsl:otherwise>true</xsl:otherwise>
      </xsl:choose>
    </xsl:variable>
    <!--<text x="{$myVar}"/>-->
  </xsl:template>
</code>```

OwnerDisplayName: Schwartser

ContentLicense: CC BY-SA 2.5

Title: get xpath from xsl variable

Body:
I am trying to get some xpath from xsl variable using xsl ver 1.0 .
That’s  my variable:

  <xsl:variable name ="myVar">
        <RefData RefTag="test1" bbb="false" />
        <RefData RefTag="test2" bbb="false" />
        <RefData RefTag="test3" bbb="false" />
        <RefData RefTag="test4" bbb="true"  />
        <RefData RefTag="test5" bbb="false" />
        <RefData RefTag="test6" bbb="false" />
  </xsl:variable>

I am trying to get bbb attribure value using the RefTag value:

<xsl:if test="$myVar/RefData[@RefTag = 'test3']/@bbb">

this is not working.

VS XSL Debugger returns an error:
"To use a result tree fragment in a path expression, first convert it to a node-set using the msxsl:node-set() function."

I don't understand how to use msxsl:node-set() function, and anyway I prefer not to use msxsl namesapce.

Can anyone help here?

Body:
Assuming this XML:

<test1>
  <RefData RefTag="test1"/>
  <RefData RefTag="test2"/>
  <RefData RefTag="test3"/>
  <RefData RefTag="test4"/>
  <RefData RefTag="test5"/>
  <RefData RefTag="test6"/>
</test1>

Something like this could work:

<xsl:template match="/">
  <xsl:apply-templates select="test1/RefData"/>
</xsl:template>

  <xsl:template match="RefData">
    <xsl:variable name="myVar">
      <xsl:choose>
        <xsl:when test="@RefTag = 'test1'">false</xsl:when>
        <xsl:when test="@RefTag = 'test2'">false</xsl:when>
        <xsl:when test="@RefTag = 'test3'">false</xsl:when>
        <xsl:when test="@RefTag = 'test4'">true</xsl:when>
        <xsl:when test="@RefTag = 'test5'">false</xsl:when>
        <xsl:when test="@RefTag = 'test6'">false</xsl:when>
        <xsl:otherwise>true</xsl:otherwise>
      </xsl:choose>
    </xsl:variable>
    <!--<text x="{$myVar}"/>-->
  </xsl:template>

OwnerDisplayName: Andrew Cowenhoven


问:
select names of students, whose GPA is greater than the average GPA on course and specialty
I have table "student":

```<code>+-----+---------+---------+------------+-------+
| id  |  name   | course  | specialty  |  gpa  |
+-----+---------+---------+------------+-------+
</code>```

How can I select names of students, whose GPA is greater than the average GPA on their course and specialty?

Thanks a lot

答:
Some thing like this should work. Here we calculate the averages per course and speciality, join back onto students and filter from there.</p>

```<code>Select s.name
from students s
inner join
(Select course, speciality, avg(gpa) as avg_gpa from students
group by course, speciality) a
on a.course = s.course and a.speciality = s.speciality
where s.gpa > a.avg_gpa
</code>```

Body:
I have table "student":

+-----+---------+---------+------------+-------+
| id  |  name   | course  | specialty  |  gpa  |
+-----+---------+---------+------------+-------+

How can I select names of students, whose GPA is greater than the average GPA on their course and specialty?

Thanks a lot

Body:
Some thing like this should work. Here we calculate the averages per course and speciality, join back onto students and filter from there.

Select s.name
from students s
inner join
(Select course, speciality, avg(gpa) as avg_gpa from students
group by course, speciality) a
on a.course = s.course and a.speciality = s.speciality
where s.gpa > a.avg_gpa


问:
Angular - Trouble incrementing in array
I've come to a problem on my Angular project. In my program, I have the user select an employee from a combo box. When that happens, the array for that employee is chosen and set to selectedEmployee. From there, in a different component, the details about the employee will be displayed from the array. Now, I've run into a problem where I need to have first, next, previous, and last buttons to iterate through the different employees and I am not sure how to do that. I've tried to mess around with some things, but I'm really stuck at this point.

Note: my array is being sorted and then displayed so I cannot just simply take the direct index of whatever was selected in the combo box because it won't be the same employee in the other component.

Here's my tracker.component.ts

import { Component, OnInit, Input} from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { PTODataService } from './pto-data.service';
import { PTOData } from './pto-data';
import { EmpInfoService } from './emp-info.service';
import { EmpInfo } from './emp-info';

@Component({
    selector: 'pto-tracker',
    templateUrl: `./tracker.component.html`,
    styleUrls: ['./tracker.component.css']
})

export class TrackerComponent implements OnInit{
    empInfo: EmpInfo[] = new Array<EmpInfo>();
    ptoData: PTOData[];
    isHidden: boolean = false;
    selectedEmployee: number = 0;

    public selectedType: string = "PTO";

    constructor(
        private empInfoService: EmpInfoService,
        private ptoDataService: PTODataService) { }

    getEmpInfo(): void {
        this.empInfoService.getEmpInfos().then(
            empInfo => {
                this.empInfo = empInfo.sort((a, b) => a.LastName < b.LastName ? -1 : b.LastName  this.ptoData = ptoData
        );
    }

    ngOnInit(): void {
        this.getEmpInfo();
        this.getPTOData();
    }

    toggleSummary(): void {
        this.isHidden = !this.isHidden;
    }

    isNextValid() {
        if (this.selectedEmployee > 0) {
            return true;
        }
        else {
            return false;
        }
    }

    isPreviousValid() {
        if (this.selectedEmployee < this.empInfo.length - 1) {
            return true;
        }
        else {
            return false;
        }
    }

    nextEmployee(): void {
        this.selectedEmployee = this.selectedEmployee + 1;
    }

    previousEmployee(): void {
        this.selectedEmployee = this.selectedEmployee - 1;
    }

    firstEmployee(): void {
        this.selectedEmployee = 0;
    }

    lastEmployee(): void {
        this.selectedEmployee = this.empInfo.length - 1;
    }
}```
</div>
</div>
</p>

<p>my tracker.component.html</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div [ngClass]="{'col-xs-12':isHidden === true, 'col-xs-7': isHidden !== false}">
    <button class="btn btn-default btn-primary" style="width:50px; height: 50px; float:right; padding-bottom: 10px; padding-top: 10px;margin:5px;" (click)="toggleSummary()"><i class="fa fa-pencil-square-o fa-2x" aria-hidden="true"></i></button>

    <div class="col-xs-12 no-pad" style="padding-bottom:50px;">
      <div class="col-xs-3">
        <select class="form-control" id="empName" [(ngModel)]="selectedEmployee">
          <option selected="selected" disabled>Employee Name...</option>
          <option *ngFor="let emp of empInfo; let i = index" [ngValue]="i">{{i}} {{emp.EmpID}} - {{emp.FirstName}} {{emp.LastName}}</option>
        </select>
      </div>
      <div class="col-xs-2">
        <select class="form-control" id="PTOtype" [(ngModel)]="selectedType">
          <option selected="selected" value="PTO">PTO</option>
          <option value="etoEarned">ETO - Earned</option>
          <option value="etoUsed">ETO - Used</option>
          <option value="STDLTD">STD/LTD</option>
          <option value="Uncharged">Uncharged</option>
        </select>
      </div>
    </div>
    <div class="col-xs-12">
      <table class="table table-striped table-bordered">
        <thead>
          <tr>
            <th>Date</th>
            <th>Full/Half</th>
            <th>Hours</th>
            <th>Scheduled?</th>
            <th>Notes</th>
            <th>In P/R?</th>
          </tr>
        </thead>
        <tfoot *ngIf="empInfo && empInfo.length > selectedEmployee">
          <tr>
            <td colspan="6">
              <span class="requestText">Requests:</span>
              <button class="btn btn-default btn-primary btn-bargin" style="float: right;" (click)="lastEmployee()"><i class="fa fa-step-forward fa-lrg" aria-hidden="true"></i></button>
              <button [disabled]="!isPreviousValid()" class="btn btn-default btn-primary btn-margin" style="float:right;" (click)="nextEmployee()"><i class="fa fa-play fa-lrg" aria-hidden="true"></i></button>
              <div class="footertext">{{selectedEmployee+1}} of {{empInfo.length}}</div>
              <button [disabled]="!isNextValid()" class="btn btn-default btn-primary btn-margin" style="float: right;" (click)="previousEmployee()"><i class="fa fa-play fa-flip-horizontal fa-lrg" aria-hidden="true"></i></button>
              <button class="btn btn-default btn-primary btn-margin" style="float: right;" (click)="firstEmployee()"><i class="fa fa-step-backward fa-lrg" aria-hidden="true"></i></button>
            </td>
          </tr>
        </tfoot>
        <tbody>
          <tr *ngFor="let pto of ptoData">
            <ng-container *ngIf="pto.type === selectedType">
              <ng-container *ngIf="pto.EmpKey === empInfo[selectedEmployee].EmpKey">
                <td>{{pto.date | date: 'MM/dd/y'}}</td>
                <td>{{pto.fullhalf}}</td>
                <td>{{pto.hours}}</td>
                <td>{{pto.scheduled}}</td>
                <td>{{pto.notes}}</td>
                <td>{{pto.inPR}}</td>
              </ng-container>
            </ng-container>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
  <div *ngIf="isHidden" class="col-xs-5">
    <pto-summary [selectedEmployee]="selectedEmployee"></pto-summary>
  </div>
</div></code>```

my summary.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { EmpInfoService } from './emp-info.service';
import { TrackerComponent } from './tracker.component';
import { EmpInfo } from './emp-info';

@Component({
    selector: 'pto-summary',
    templateUrl: `./summary.component.html`,
    styleUrls: ['./summary.component.css']
})

export class SummaryComponent implements OnInit{

    empInfo: EmpInfo[];
    @Input() selectedEmployee: number;

    timeVar = " hours";
    checkboxValue = false;

    constructor(private empInfoService: EmpInfoService) { }

    getEmpInfo(): void {
        this.empInfoService.getEmpInfos().then(
            empInfo => {
                this.empInfo = empInfo.sort((a, b) => a.LastName < b.LastName ? -1 : b.LastName < a.LastName ? 1 : 0);
            });
    }

    ngOnInit(): void {
        this.getEmpInfo();
    }

    changeTime(): void {
        if (!this.checkboxValue)
        {
            this.timeVar = " hours"

            this.empInfo[this.selectedEmployee].STDLTD = this.empInfo[this.selectedEmployee].STDLTD * 8;
            this.empInfo[this.selectedEmployee].Uncharged = this.empInfo[this.selectedEmployee].Uncharged * 8;

            this.empInfo[this.selectedEmployee].PTOBase = this.empInfo[this.selectedEmployee].PTOBase * 8;
            this.empInfo[this.selectedEmployee].PTOCarry = this.empInfo[this.selectedEmployee].PTOCarry * 8;
            this.empInfo[this.selectedEmployee].PTOBorrowed = this.empInfo[this.selectedEmployee].PTOBorrowed * 8;
            this.empInfo[this.selectedEmployee].PTOBalance = this.empInfo[this.selectedEmployee].PTOBalance * 8;
            this.empInfo[this.selectedEmployee].PTORequests = this.empInfo[this.selectedEmployee].PTORequests * 8;
            this.empInfo[this.selectedEmployee].PTORemaining = this.empInfo[this.selectedEmployee].PTORemaining * 8;

            this.empInfo[this.selectedEmployee].ETOEarned = this.empInfo[this.selectedEmployee].ETOEarned * 8;
            this.empInfo[this.selectedEmployee].ETORequests = this.empInfo[this.selectedEmployee].ETORequests * 8;
            this.empInfo[this.selectedEmployee].ETORemaining = this.empInfo[this.selectedEmployee].ETORemaining * 8;
        }
        else
        {
            this.timeVar = " days"

            this.empInfo[this.selectedEmployee].STDLTD = this.empInfo[this.selectedEmployee].STDLTD / 8;
            this.empInfo[this.selectedEmployee].Uncharged = this.empInfo[this.selectedEmployee].Uncharged / 8;

            this.empInfo[this.selectedEmployee].PTOBase = this.empInfo[this.selectedEmployee].PTOBase / 8;
            this.empInfo[this.selectedEmployee].PTOCarry = this.empInfo[this.selectedEmployee].PTOCarry / 8;
            this.empInfo[this.selectedEmployee].PTOBorrowed = this.empInfo[this.selectedEmployee].PTOBorrowed / 8;
            this.empInfo[this.selectedEmployee].PTOBalance = this.empInfo[this.selectedEmployee].PTOBalance / 8;
            this.empInfo[this.selectedEmployee].PTORequests = this.empInfo[this.selectedEmployee].PTORequests / 8;
            this.empInfo[this.selectedEmployee].PTORemaining = this.empInfo[this.selectedEmployee].PTORemaining / 8;

            this.empInfo[this.selectedEmployee].ETOEarned = this.empInfo[this.selectedEmployee].ETOEarned / 8;
            this.empInfo[this.selectedEmployee].ETORequests = this.empInfo[this.selectedEmployee].ETORequests / 8;
            this.empInfo[this.selectedEmployee].ETORemaining = this.empInfo[this.selectedEmployee].ETORemaining / 8;
        }
    }
}```
</div>
</div>
</p>

<p>and my summary.component.html</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="panel panel-default">
  <div class="panel-heading">
    <h3 class="panel-title pull-left">{{empInfo[selectedEmployee].LastName | uppercase}} Summary</h3>
    <div style="float: right;">
      <div class="onoffswitch">
        <input [(ngModel)]="checkboxValue" (change)="changeTime()" type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked>
        <label class="onoffswitch-label" for="myonoffswitch">
          <span class="onoffswitch-inner"></span>
          <span class="onoffswitch-switch"></span>
        </label>
      </div>
    </div>
    <div class="clearfix"></div>
  </div>
  <div class="panel-body">
    <form class="form-horizontal" role="form" style="overflow-x:auto;">
      <fieldset>
        <div class="col-xs-6">
          <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
            <label class="col-xs-5"> Status </label>
            <div class="col-xs-7">
              <select class="form-control" id="empStatus" [(ngModel)]="empInfo[selectedEmployee].EmpStat" name="empStatus">
                <option value="Current">Current</option>
                <option value="Terminated">Terminated</option>
              </select>
            </div>
          </div>
        </div>
        <div class="col-xs-6">
          <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
            <label class="col-xs-5"> Anniversary </label>
            <div class="col-xs-7">
              <div class="input-group">
                <input class='form-control' type="text" id="empAnniversary" [(ngModel)]="empInfo[selectedEmployee].Anniversary" name="empAnniversary" />
                <span class="input-group-addon">years</span>
              </div>
            </div>
          </div>
         </div>
        <div class="col-xs-6">
          <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
            <label class="col-xs-5"> Start Date </label>
            <div class="col-xs-7">
              <input class='form-control' type="text" id="empStartDate" [ngModel]="empInfo[selectedEmployee].StartDate | date: 'MM/dd/y'" name="empStartDate"/>
            </div>
          </div>
        </div>
        <div class="col-xs-6">
          <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
            <label class="col-xs-5"> Adjusted Start </label>
            <div class="col-xs-7">
              <input class='form-control' type="text" id="empAdjustedStart" [ngModel]="empInfo[selectedEmployee].AdjustedStart | date: 'MM/dd/y'" name="empAdjustedStart"/>
            </div>
          </div>
        </div>
        <div class="col-xs-6">
          <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
            <label class="col-xs-5"> STD/LTD </label>
            <div class="col-xs-7">
              <div class="input-group">
                <input class='form-control' type="text" id="empSTDLTD" [(ngModel)]="empInfo[selectedEmployee].STDLTD" name="empSTDLTD" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="col-xs-6">
          <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
            <label class="col-xs-5"> Uncharged </label>
            <div class="col-xs-7">
              <div class="input-group">
                <input class='form-control' type="text" id="empUncharged" [(ngModel)]="empInfo[selectedEmployee].Uncharged" name="empUncharged" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
            </div>
          </div>
        </div>
      </fieldset>

      <fieldset>

        <h4>PTO</h4>
        <br />

        <div class="col-xs-12">
          <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
            <div class="col-xs-1"></div>
            <label class="col-xs-2"> Base </label>
            <div class="col-xs-3">
              <div class="input-group">
                <input class='form-control' type="text" id="ptoBase" [(ngModel)]="empInfo[selectedEmployee].PTOBase" name="ptoBase" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
            </div>
            <div class="col-xs-6">
            </div>
          </div>
        </div>
        <div class="col-xs-6">
          <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
            <label class="col-xs-2" style="font-weight: bold;"> + </label>
            <label class="col-xs-4"> Carryover </label>
            <div class="col-xs-6">
              <div class="input-group">
                <input class='form-control' type="text" id="ptoCarry" [(ngModel)]="empInfo[selectedEmployee].PTOCarry" name="ptoCarry" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="col-xs-6">
          <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
            <div class="col-xs-1"></div>
            <label class="col-xs-4"> Balance </label>
            <div class="col-xs-6">
              <div class="input-group">
                <input class='form-control' type="text" id="ptoBalance" [(ngModel)]="empInfo[selectedEmployee].PTOBalance" name="ptoBalance" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
            </div>
            <div class="col-xs-1"></div>
          </div>
        </div>
        <div class="col-xs-6">
          <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
            <label class="col-xs-2" style="font-weight: bold;"> ― </label>
            <label class="col-xs-4"> Borrowed </label>
            <div class="col-xs-6">
              <div class="input-group">
                <input class='form-control' type="text" id="ptoBorrowed" [(ngModel)]="empInfo[selectedEmployee].PTOBorrowed" name="ptoBorrowed" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
            </div>
          </div>
          <hr style="border: solid 1px black;border-bottom:1px solid black;clear:both" />
        </div>
        <div class="col-xs-6">
          <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
            <label class="col-xs-1" style="font-weight: bold;"> ― </label>
            <label class="col-xs-4"> Requests </label>
            <div class="col-xs-6">
              <div class="input-group">
                <input class='form-control' type="text" id="ptoRequests" [(ngModel)]="empInfo[selectedEmployee].PTORequests" name="ptoRequests" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
            </div>
            <div class="col-xs-1"></div>
          </div>
          <hr style="border: solid 1px black;border-bottom:1px solid black;clear:both" />
        </div>
        <div class="col-xs-6">
          <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
            <label class="col-xs-2" style="font-weight: bold;"> = </label>
            <label class="col-xs-4"> Balance </label>
            <div class="col-xs-6">
              <div class="input-group">
                <input class='form-control' type="text" id="ptoBalance" [(ngModel)]="empInfo[selectedEmployee].PTOBalance" name="ptoBalance" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="col-xs-6">
          <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
            <label class="col-xs-1" style="font-weight: bold;"> = </label>
            <label class="col-xs-4"> Available </label>
            <div class="col-xs-6">
              <div class="input-group">
                <input class='form-control' type="text" id="ptoRemaining" [(ngModel)]="empInfo[selectedEmployee].PTORemaining" name="ptoRemaining" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
            </div>
            <div class="col-xs-1"></div>
          </div>
        </div>
      </fieldset>

      <fieldset>

        <h4>ETO</h4>
        <br />

          <div class="col-xs-6">
            <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
              <div class="col-xs-2"></div>
              <label class="col-xs-4"> Earned </label>
              <div class="col-xs-6">
                <div class="input-group">
                  <input class='form-control' type="text" id="etoEarned" [(ngModel)]="empInfo[selectedEmployee].ETOEarned" name="etoEarned" />
                  <span class="input-group-addon">{{timeVar}}</span>
                </div>
              </div>
            </div>
            <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
              <label class="col-xs-2"> ― </label>
              <label class="col-xs-4"> Requests </label>
              <div class="col-xs-6">
              <div class="input-group">
                <input class='form-control' type="text" id="etoRequests" [(ngModel)]="empInfo[selectedEmployee].ETORequests" name="etoRequests" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
              </div>
            </div>
            <hr style="border: solid 1px black;border-bottom:1px solid black;clear:both" />
            <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
              <label class="col-xs-2"> = </label>
              <label class="col-xs-4"> Available </label>
              <div class="col-xs-6">
                <div class="input-group">
                  <input class='form-control' type="text" id="etoRemaining" [(ngModel)]="empInfo[selectedEmployee].ETORemaining" name="etoRemaining" />
                  <span class="input-group-addon">{{timeVar}}</span>
                </div>
              </div>
            </div>
          </div>
          <div class="col-xs-6"></div>

      </fieldset>
    </form>
  </div>
</div></code>```

EDIT - Updated Code

Now, everything works except for whenever I go to the summary tab, I'm getting an error in the browser that says "Cannot read property '...' of undefined" where the '...' is the index of whichever employee is selected.

答:
Instead of sorting the array in the template with a pipe, do the sorting in the component code when you get the data from the service. Try removing the orderByLastpipe in the template and modify the getEmpInfo() function like this:

```<code>getEmpInfo(): void {
   this.empInfoService.getEmpInfos().then(
       empInfo => {
           this.empInfo = empInfo.sort((a, b) =>
                a.LastName > b.LastName ? -1 : b.LastName > a.LastName ? 1 : 0);
   });
}
</code>```

This will allow you do use the index from the dropdown to select your employee.

Title: Angular - Trouble incrementing in array

Body:
I've come to a problem on my Angular project. In my program, I have the user select an employee from a combo box. When that happens, the array for that employee is chosen and set to selectedEmployee. From there, in a different component, the details about the employee will be displayed from the array. Now, I've run into a problem where I need to have first, next, previous, and last buttons to iterate through the different employees and I am not sure how to do that. I've tried to mess around with some things, but I'm really stuck at this point.

Note: my array is being sorted and then displayed so I cannot just simply take the direct index of whatever was selected in the combo box because it won't be the same employee in the other component.

Here's my tracker.component.ts

import { Component, OnInit, Input} from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { PTODataService } from './pto-data.service';
import { PTOData } from './pto-data';
import { EmpInfoService } from './emp-info.service';
import { EmpInfo } from './emp-info';

@Component({
    selector: 'pto-tracker',
    templateUrl: `./tracker.component.html`,
    styleUrls: ['./tracker.component.css']
})

export class TrackerComponent implements OnInit{
    empInfo: EmpInfo[] = new Array<EmpInfo>();
    ptoData: PTOData[];
    isHidden: boolean = false;
    selectedEmployee: number = 0;

    public selectedType: string = "PTO";

    constructor(
        private empInfoService: EmpInfoService,
        private ptoDataService: PTODataService) { }

    getEmpInfo(): void {
        this.empInfoService.getEmpInfos().then(
            empInfo => {
                this.empInfo = empInfo.sort((a, b) => a.LastName < b.LastName ? -1 : b.LastName  this.ptoData = ptoData
        );
    }

    ngOnInit(): void {
        this.getEmpInfo();
        this.getPTOData();
    }

    toggleSummary(): void {
        this.isHidden = !this.isHidden;
    }

    isNextValid() {
        if (this.selectedEmployee > 0) {
            return true;
        }
        else {
            return false;
        }
    }

    isPreviousValid() {
        if (this.selectedEmployee < this.empInfo.length - 1) {
            return true;
        }
        else {
            return false;
        }
    }

    nextEmployee(): void {
        this.selectedEmployee = this.selectedEmployee + 1;
    }

    previousEmployee(): void {
        this.selectedEmployee = this.selectedEmployee - 1;
    }

    firstEmployee(): void {
        this.selectedEmployee = 0;
    }

    lastEmployee(): void {
        this.selectedEmployee = this.empInfo.length - 1;
    }
}

my tracker.component.html

    <button class="btn btn-default btn-primary" style="width:50px; height: 50px; float:right; padding-bottom: 10px; padding-top: 10px;margin:5px;" (click)="toggleSummary()"></button>

        <select class="form-control" id="empName" [(ngModel)]="selectedEmployee">
          <option selected="selected" disabled>Employee Name...</option>
          <option *ngFor="let emp of empInfo; let i = index" [ngValue]="i">{{i}} {{emp.EmpID}} - {{emp.FirstName}} {{emp.LastName}}</option>
        </select>

        <select class="form-control" id="PTOtype" [(ngModel)]="selectedType">
          <option selected="selected" value="PTO">PTO</option>
          <option value="etoEarned">ETO - Earned</option>
          <option value="etoUsed">ETO - Used</option>
          <option value="STDLTD">STD/LTD</option>
          <option value="Uncharged">Uncharged</option>
        </select>

            Date
            Full/Half
            Hours
            Scheduled?
            Notes
            In P/R?

 selectedEmployee">

              Requests:
              <button class="btn btn-default btn-primary btn-bargin" style="float: right;" (click)="lastEmployee()"></button>
              <button [disabled]="!isPreviousValid()" class="btn btn-default btn-primary btn-margin" style="float:right;" (click)="nextEmployee()"></button>

{{selectedEmployee+1}} of {{empInfo.length}}

              <button [disabled]="!isNextValid()" class="btn btn-default btn-primary btn-margin" style="float: right;" (click)="previousEmployee()"></button>
              <button class="btn btn-default btn-primary btn-margin" style="float: right;" (click)="firstEmployee()"></button>

            <ng-container *ngIf="pto.type === selectedType">
              <ng-container *ngIf="pto.EmpKey === empInfo[selectedEmployee].EmpKey">
                {{pto.date | date: 'MM/dd/y'}}
                {{pto.fullhalf}}
                {{pto.hours}}
                {{pto.scheduled}}
                {{pto.notes}}
                {{pto.inPR}}
              </ng-container>
            </ng-container>

    <pto-summary [selectedEmployee]="selectedEmployee"></pto-summary>

my summary.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { EmpInfoService } from './emp-info.service';
import { TrackerComponent } from './tracker.component';
import { EmpInfo } from './emp-info';

@Component({
    selector: 'pto-summary',
    templateUrl: `./summary.component.html`,
    styleUrls: ['./summary.component.css']
})

export class SummaryComponent implements OnInit{

    empInfo: EmpInfo[];
    @Input() selectedEmployee: number;

    timeVar = " hours";
    checkboxValue = false;

    constructor(private empInfoService: EmpInfoService) { }

    getEmpInfo(): void {
        this.empInfoService.getEmpInfos().then(
            empInfo => {
                this.empInfo = empInfo.sort((a, b) => a.LastName < b.LastName ? -1 : b.LastName < a.LastName ? 1 : 0);
            });
    }

    ngOnInit(): void {
        this.getEmpInfo();
    }

    changeTime(): void {
        if (!this.checkboxValue)
        {
            this.timeVar = " hours"

            this.empInfo[this.selectedEmployee].STDLTD = this.empInfo[this.selectedEmployee].STDLTD * 8;
            this.empInfo[this.selectedEmployee].Uncharged = this.empInfo[this.selectedEmployee].Uncharged * 8;

            this.empInfo[this.selectedEmployee].PTOBase = this.empInfo[this.selectedEmployee].PTOBase * 8;
            this.empInfo[this.selectedEmployee].PTOCarry = this.empInfo[this.selectedEmployee].PTOCarry * 8;
            this.empInfo[this.selectedEmployee].PTOBorrowed = this.empInfo[this.selectedEmployee].PTOBorrowed * 8;
            this.empInfo[this.selectedEmployee].PTOBalance = this.empInfo[this.selectedEmployee].PTOBalance * 8;
            this.empInfo[this.selectedEmployee].PTORequests = this.empInfo[this.selectedEmployee].PTORequests * 8;
            this.empInfo[this.selectedEmployee].PTORemaining = this.empInfo[this.selectedEmployee].PTORemaining * 8;

            this.empInfo[this.selectedEmployee].ETOEarned = this.empInfo[this.selectedEmployee].ETOEarned * 8;
            this.empInfo[this.selectedEmployee].ETORequests = this.empInfo[this.selectedEmployee].ETORequests * 8;
            this.empInfo[this.selectedEmployee].ETORemaining = this.empInfo[this.selectedEmployee].ETORemaining * 8;
        }
        else
        {
            this.timeVar = " days"

            this.empInfo[this.selectedEmployee].STDLTD = this.empInfo[this.selectedEmployee].STDLTD / 8;
            this.empInfo[this.selectedEmployee].Uncharged = this.empInfo[this.selectedEmployee].Uncharged / 8;

            this.empInfo[this.selectedEmployee].PTOBase = this.empInfo[this.selectedEmployee].PTOBase / 8;
            this.empInfo[this.selectedEmployee].PTOCarry = this.empInfo[this.selectedEmployee].PTOCarry / 8;
            this.empInfo[this.selectedEmployee].PTOBorrowed = this.empInfo[this.selectedEmployee].PTOBorrowed / 8;
            this.empInfo[this.selectedEmployee].PTOBalance = this.empInfo[this.selectedEmployee].PTOBalance / 8;
            this.empInfo[this.selectedEmployee].PTORequests = this.empInfo[this.selectedEmployee].PTORequests / 8;
            this.empInfo[this.selectedEmployee].PTORemaining = this.empInfo[this.selectedEmployee].PTORemaining / 8;

            this.empInfo[this.selectedEmployee].ETOEarned = this.empInfo[this.selectedEmployee].ETOEarned / 8;
            this.empInfo[this.selectedEmployee].ETORequests = this.empInfo[this.selectedEmployee].ETORequests / 8;
            this.empInfo[this.selectedEmployee].ETORemaining = this.empInfo[this.selectedEmployee].ETORemaining / 8;
        }
    }
}

and my summary.component.html

{{empInfo[selectedEmployee].LastName | uppercase}} Summary

        <input [(ngModel)]="checkboxValue" (change)="changeTime()" type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked>

    <form class="form-horizontal" role="form" style="overflow-x:auto;">
      <fieldset>

 selectedEmployee">
             Status

              <select class="form-control" id="empStatus" [(ngModel)]="empInfo[selectedEmployee].EmpStat" name="empStatus">
                <option value="Current">Current</option>
                <option value="Terminated">Terminated</option>
              </select>

 selectedEmployee">
             Anniversary

                <input class='form-control' type="text" id="empAnniversary" [(ngModel)]="empInfo[selectedEmployee].Anniversary" name="empAnniversary" />
                years

 selectedEmployee">
             Start Date

              <input class='form-control' type="text" id="empStartDate" [ngModel]="empInfo[selectedEmployee].StartDate | date: 'MM/dd/y'" name="empStartDate"/>

 selectedEmployee">
             Adjusted Start

              <input class='form-control' type="text" id="empAdjustedStart" [ngModel]="empInfo[selectedEmployee].AdjustedStart | date: 'MM/dd/y'" name="empAdjustedStart"/>

 selectedEmployee">
             STD/LTD

                <input class='form-control' type="text" id="empSTDLTD" [(ngModel)]="empInfo[selectedEmployee].STDLTD" name="empSTDLTD" />
                {{timeVar}}

 selectedEmployee">
             Uncharged

                <input class='form-control' type="text" id="empUncharged" [(ngModel)]="empInfo[selectedEmployee].Uncharged" name="empUncharged" />
                {{timeVar}}

      </fieldset>

      <fieldset>

PTO

 selectedEmployee">

             Base

                <input class='form-control' type="text" id="ptoBase" [(ngModel)]="empInfo[selectedEmployee].PTOBase" name="ptoBase" />
                {{timeVar}}

 selectedEmployee">
             +
             Carryover

                <input class='form-control' type="text" id="ptoCarry" [(ngModel)]="empInfo[selectedEmployee].PTOCarry" name="ptoCarry" />
                {{timeVar}}

 selectedEmployee">

             Balance

                <input class='form-control' type="text" id="ptoBalance" [(ngModel)]="empInfo[selectedEmployee].PTOBalance" name="ptoBalance" />
                {{timeVar}}

 selectedEmployee">
             ―
             Borrowed

                <input class='form-control' type="text" id="ptoBorrowed" [(ngModel)]="empInfo[selectedEmployee].PTOBorrowed" name="ptoBorrowed" />
                {{timeVar}}

 selectedEmployee">
             ―
             Requests

                <input class='form-control' type="text" id="ptoRequests" [(ngModel)]="empInfo[selectedEmployee].PTORequests" name="ptoRequests" />
                {{timeVar}}

 selectedEmployee">
             =
             Balance

                <input class='form-control' type="text" id="ptoBalance" [(ngModel)]="empInfo[selectedEmployee].PTOBalance" name="ptoBalance" />
                {{timeVar}}

 selectedEmployee">
             =
             Available

                <input class='form-control' type="text" id="ptoRemaining" [(ngModel)]="empInfo[selectedEmployee].PTORemaining" name="ptoRemaining" />
                {{timeVar}}

      </fieldset>

      <fieldset>

ETO

 selectedEmployee">

               Earned

                  <input class='form-control' type="text" id="etoEarned" [(ngModel)]="empInfo[selectedEmployee].ETOEarned" name="etoEarned" />
                  {{timeVar}}

 selectedEmployee">
               ―
               Requests

                <input class='form-control' type="text" id="etoRequests" [(ngModel)]="empInfo[selectedEmployee].ETORequests" name="etoRequests" />
                {{timeVar}}

 selectedEmployee">
               =
               Available

                  <input class='form-control' type="text" id="etoRemaining" [(ngModel)]="empInfo[selectedEmployee].ETORemaining" name="etoRemaining" />
                  {{timeVar}}

      </fieldset>
    </form>

EDIT - Updated Code

Now, everything works except for whenever I go to the summary tab, I'm getting an error in the browser that says "Cannot read property '...' of undefined" where the '...' is the index of whichever employee is selected.

Body:
Instead of sorting the array in the template with a pipe, do the sorting in the component code when you get the data from the service. Try removing the orderByLastpipe in the template and modify the getEmpInfo() function like this:

getEmpInfo(): void {
   this.empInfoService.getEmpInfos().then(
       empInfo => {
           this.empInfo = empInfo.sort((a, b) =>
                a.LastName > b.LastName ? -1 : b.LastName > a.LastName ? 1 : 0);
   });
}

This will allow you do use the index from the dropdown to select your employee.


问:
Intersection and union of ArrayLists in Java
Are there any methods to do so? I was looking but couldn't find any.

Another question: I need these methods so I can filter files.
Some are AND filters and some are OR filters (like in set theory), so I need to filter according to all files and the unite/intersects ArrayLists that holds those files.

Should I use a different data structure to hold the files? Is there anything else that would offer a better runtime?

答:
If the number matches  than I am checking it's occur first time or not with help of "indexOf()" if the number matches first time then print and save into in a string so, that when the next time same number matches then it's won't print because due to "indexOf()" condition will be false. </p>

```<code>class Intersection
{
public static void main(String[] args)
 {
  String s="";
    int[] array1 = {1, 2, 5, 5, 8, 9, 7,2,3512451,4,4,5 ,10};
    int[] array2 = {1, 0, 6, 15, 6, 5,4, 1,7, 0,5,4,5,2,3,8,5,3512451};

       for (int i = 0; i < array1.length; i++)
       {
           for (int j = 0; j < array2.length; j++)
           {
               char c=(char)(array1[i]);
               if(array1[i] == (array2[j])&&s.indexOf(c)==-1)
               {
                System.out.println("Common element is : "+(array1[i]));
                s+=c;
                }
           }
       }
}
</code>```

<p>}</p>

Body:
If the number matches  than I am checking it's occur first time or not with help of "indexOf()" if the number matches first time then print and save into in a string so, that when the next time same number matches then it's won't print because due to "indexOf()" condition will be false.

class Intersection
{
public static void main(String[] args)
 {
  String s="";
    int[] array1 = {1, 2, 5, 5, 8, 9, 7,2,3512451,4,4,5 ,10};
    int[] array2 = {1, 0, 6, 15, 6, 5,4, 1,7, 0,5,4,5,2,3,8,5,3512451};

       for (int i = 0; i < array1.length; i++)
       {
           for (int j = 0; j < array2.length; j++)
           {
               char c=(char)(array1[i]);
               if(array1[i] == (array2[j])&&s.indexOf(c)==-1)
               {
                System.out.println("Common element is : "+(array1[i]));
                s+=c;
                }
           }
       }
}

}


答:
Why don't you check if the String starts with HTTPS and only then push it into the array? For instance:</p>

```<code>foreach ($doc->getElementsByTagName('a') as $link){
   if (strpos($link, 'https://') !== FALSE)
      $linkDetail[] = array('url' => $link->getAttribute('href'));
}
</code>```

Title: How to get all links on a page that start with a https in link - PHP

Body:
Why don't you check if the String starts with HTTPS and only then push it into the array? For instance:

foreach ($doc->getElementsByTagName('a') as $link){
   if (strpos($link, 'https://') !== FALSE)
      $linkDetail[] = array('url' => $link->getAttribute('href'));
}


问:
iOS - How to predefine TextView line height
I've some UITextView declared as the following

```<code>lazy var inputTextView: UITextView = {
    let tv = UITextView()
    tv.tintColor = UIColor.darkGray
    tv.font = UIFont.systemFont(ofSize: 17)
    tv.backgroundColor = UIColor.white
    return tv
}()
</code>```

I've been searching how can I predefine the line height for this UITextView so whenever I write a long text, when it reaches the end of the line and goes to the following line, the spacing would be bigger than the default.

I've tried using the following inside the UITextView declaration:

```<code>let style = NSMutableParagraphStyle()
style.lineSpacing = 40
let attributes = [NSParagraphStyleAttributeName : style]
tv.attributedText = NSAttributedString(string: "", attributes:attributes)
</code>```

Which would become:

```<code>lazy var inputTextView: UITextView = {
    let tv = UITextView()
    tv.tintColor = UIColor.darkGray
    tv.font = UIFont.systemFont(ofSize: 17)
    tv.backgroundColor = UIColor.white
    let style = NSMutableParagraphStyle()
    style.lineSpacing = 40
    let attributes = [NSParagraphStyleAttributeName : style]
    tv.attributedText = NSAttributedString(string: "", attributes:attributes)
    return tv
}()
</code>```

It only works if I pre-insert some text in the attributedText property but since the text is empty in the beginning it will not use those properties and it will be set as default.

How can I increase the default line height and keep it whenever I'm writing in the UITextView?

Thanks ;)

答:
I solved the issue. The problem was that I shouldn't set the attributedText to be set according to the attributes because when we start typing the attributes are gone.

Instead I set the typingAttributes to be equal to what I desire so whenever I type in the attributes don't get lost.

Final version:

```<code>lazy var inputTextView: UITextView = {
    let tv = UITextView()
    tv.tintColor = UIColor.darkGray
    tv.font = UIFont.systemFont(ofSize: 17)
    tv.backgroundColor = UIColor.white
    let spacing = NSMutableParagraphStyle()
    spacing.lineSpacing = 4
    let attr = [NSParagraphStyleAttributeName : spacing]
    tv.typingAttributes = attr
    return tv
}()
</code>```

Body:
I've some UITextView declared as the following

lazy var inputTextView: UITextView = {
    let tv = UITextView()
    tv.tintColor = UIColor.darkGray
    tv.font = UIFont.systemFont(ofSize: 17)
    tv.backgroundColor = UIColor.white
    return tv
}()

I've been searching how can I predefine the line height for this UITextView so whenever I write a long text, when it reaches the end of the line and goes to the following line, the spacing would be bigger than the default.

I've tried using the following inside the UITextView declaration:

let style = NSMutableParagraphStyle()
style.lineSpacing = 40
let attributes = [NSParagraphStyleAttributeName : style]
tv.attributedText = NSAttributedString(string: "", attributes:attributes)

Which would become:

lazy var inputTextView: UITextView = {
    let tv = UITextView()
    tv.tintColor = UIColor.darkGray
    tv.font = UIFont.systemFont(ofSize: 17)
    tv.backgroundColor = UIColor.white
    let style = NSMutableParagraphStyle()
    style.lineSpacing = 40
    let attributes = [NSParagraphStyleAttributeName : style]
    tv.attributedText = NSAttributedString(string: "", attributes:attributes)
    return tv
}()

It only works if I pre-insert some text in the attributedText property but since the text is empty in the beginning it will not use those properties and it will be set as default.

How can I increase the default line height and keep it whenever I'm writing in the UITextView?

Thanks ;)

Body:
I solved the issue. The problem was that I shouldn't set the attributedText to be set according to the attributes because when we start typing the attributes are gone.

Instead I set the typingAttributes to be equal to what I desire so whenever I type in the attributes don't get lost.

Final version:

lazy var inputTextView: UITextView = {
    let tv = UITextView()
    tv.tintColor = UIColor.darkGray
    tv.font = UIFont.systemFont(ofSize: 17)
    tv.backgroundColor = UIColor.white
    let spacing = NSMutableParagraphStyle()
    spacing.lineSpacing = 4
    let attr = [NSParagraphStyleAttributeName : spacing]
    tv.typingAttributes = attr
    return tv
}()


问:
Why my scrapy ouput result is array
Scrapy seems will format my output from dict to array while all i need was just string object.The output:

{"title": ["some title some title"], "url": ["https://www.example.com/"], "upDate": ["2017/06/07 10:23:00"]}
```

<p>
and the code:</p>

<pre class="lang-html prettyprint-override"><code>    l = ItemLoader(item=RoomInfoItem(), response=response)
    updateStr = '2017-' + res.css('td[class="time"]::text').extract_first()
    l.add_value('upDate', upDateStr)
    ownerurl = response.css('span[class="from"] a::attr(href)').extract_first()
    l.add_value('ownerUrl', ownerurl)
    title = response.css('div[id="content"] h1::text').extract_first()
    l.add_value('title', title)
    yield l.load_item()
</code>```

the scrapy resource it seems like when add new value to item, scrapy will turn the argument to  an iterable by scrapy.utils.misc.arg_to_iter().
If there any other method can add values to the items while not change the value data struct?
The output i want may look like this:

{"title": "some title some title", "url": "https://www.example.com/", "upDate": "2017/06/07 10:23:00"}
```

答:
It's standart behaviour of ItemLoader object.
For change it you should create child Object and use default_output_processor = TakeFirst()

```<code>from scrapy.loader import ItemLoader
from scrapy.loader.processors import TakeFirst, MapCompose, Join

    ... YOUR CODE...

    l = YourLoader(item=RoomInfoItem(), response=response)

class YourLoader(ItemLoader):

    default_output_processor = TakeFirst()

    title_in = MapCompose(unicode.title)
    url_in = MapCompose(unicode.strip)
</code>```

You can check more in scrapy docs here.

Title: Why my scrapy ouput result is array

Body:
Scrapy seems will format my output from dict to array while all i need was just string object.The output:

{"title": ["some title some title"], "url": ["https://www.example.com/"], "upDate": ["2017/06/07 10:23:00"]}

and the code:

    l = ItemLoader(item=RoomInfoItem(), response=response)
    updateStr = '2017-' + res.css('td[class="time"]::text').extract_first()
    l.add_value('upDate', upDateStr)
    ownerurl = response.css('span[class="from"] a::attr(href)').extract_first()
    l.add_value('ownerUrl', ownerurl)
    title = response.css('div[id="content"] h1::text').extract_first()
    l.add_value('title', title)
    yield l.load_item()

the scrapy resource it seems like when add new value to item, scrapy will turn the argument to  an iterable by scrapy.utils.misc.arg_to_iter().
If there any other method can add values to the items while not change the value data struct?
The output i want may look like this:

{"title": "some title some title", "url": "https://www.example.com/", "upDate": "2017/06/07 10:23:00"}

Body:
It's standart behaviour of ItemLoader object.
For change it you should create child Object and use default_output_processor = TakeFirst()

from scrapy.loader import ItemLoader
from scrapy.loader.processors import TakeFirst, MapCompose, Join

    ... YOUR CODE...

    l = YourLoader(item=RoomInfoItem(), response=response)

class YourLoader(ItemLoader):

    default_output_processor = TakeFirst()

    title_in = MapCompose(unicode.title)
    url_in = MapCompose(unicode.strip)

You can check more in scrapy docs here.


问:
Print the entire expression object of sympy when changes in internal structure occur
So as the question says i want to print an entire expression object when internal structure of its tree changes, but as the sympy objects are immutable i cannot to do this with the name the object is bound to

Here is an example of Code on how i am changing the Internal Structure

```<code>from sympy import *
from sympy.abc import x,y

input = 'x*(x+4)+3*x'
expr = sympify(input,evaluate=False)

def traverse(expr):
    if(expr.is_Number):
        return 1,True
    oldexpr = expr
    args = expr.args
    sargs = []
    hit = False
    for arg in args:
        arg,arghit = traverse(arg)
        hit |= arghit
        sargs.append(arg)

    if(hit):
        expr = expr.func(*sargs)
        return expr,True
    else:
        return oldexpr,False

print(srepr(expr))
expr,hit = traverse(expr)
print(expr)
</code>```

here i am changing the number to 1 whenever i encounter a number in the expression tree. And i want to print the complete expression when i made the change like this: x*(x+1)+3*x and then x*(x+1)+x
Can anyone suggest me on how to achieve this.

答:
Just a slight mod to what you have might be what you are looking for:

```<code>def traverse(expr):
  if any(a.is_Number and abs(a) != 1 for a in expr.args):
    print(expr,'->',expr.func(*[(a if not a.is_Number else 1) for a in expr.args]))
  if expr.is_Number and abs(expr) != 1:
    return 1, True
  oldexpr = expr
  args = expr.args
  sargs = []
  hit = False
  for arg in args:
    arg,arghit = traverse(arg)
    hit |= arghit
    sargs.append(arg)

  if(hit):
    expr = expr.func(*sargs)
    return expr, True
  else:
    return oldexpr, False
</code>```

This produces

```<code>>>> traverse(2*x+3)
(2*x + 3, '->', 2*x + 1)
(2*x, '->', x)

(x + 1, True)
</code>```

/c

Body:
So as the question says i want to print an entire expression object when internal structure of its tree changes, but as the sympy objects are immutable i cannot to do this with the name the object is bound to

Here is an example of Code on how i am changing the Internal Structure

from sympy import *
from sympy.abc import x,y

input = 'x*(x+4)+3*x'
expr = sympify(input,evaluate=False)

def traverse(expr):
    if(expr.is_Number):
        return 1,True
    oldexpr = expr
    args = expr.args
    sargs = []
    hit = False
    for arg in args:
        arg,arghit = traverse(arg)
        hit |= arghit
        sargs.append(arg)

    if(hit):
        expr = expr.func(*sargs)
        return expr,True
    else:
        return oldexpr,False

print(srepr(expr))
expr,hit = traverse(expr)
print(expr)

here i am changing the number to 1 whenever i encounter a number in the expression tree. And i want to print the complete expression when i made the change like this: x*(x+1)+3*x and then x*(x+1)+x
Can anyone suggest me on how to achieve this.

Body:
Just a slight mod to what you have might be what you are looking for:

def traverse(expr):
  if any(a.is_Number and abs(a) != 1 for a in expr.args):
    print(expr,'->',expr.func(*[(a if not a.is_Number else 1) for a in expr.args]))
  if expr.is_Number and abs(expr) != 1:
    return 1, True
  oldexpr = expr
  args = expr.args
  sargs = []
  hit = False
  for arg in args:
    arg,arghit = traverse(arg)
    hit |= arghit
    sargs.append(arg)

  if(hit):
    expr = expr.func(*sargs)
    return expr, True
  else:
    return oldexpr, False

This produces

>>> traverse(2*x+3)
(2*x + 3, '->', 2*x + 1)
(2*x, '->', x)

(x + 1, True)

/c


问:
Constructor chaining in PowerShell - call other constructors in the same class
I was doing some testing and stumbled upon the following:

You can overload methods in PoShv5 as you wish. If you call the method without parameters, it can internally call the method with parameters, to keep your code non-redundant. I expected this to be also true for constructors.

In this example, the last constructor is working as expected. The other constructors only return objects without set values.

```<code>Class car {
    [string]$make
    [string]$model
    [int]$Speed
    [int]$Year

    speedUp (){
        $this.speedUp(5)
    }
    speedUp ([int]$velocity){
        $this.speed += $velocity
    }

    # Constructor
    car () {
        [car]::new('mall', $Null, $null)
    }

    car ([string]$make, [string]$model) {
        [car]::new($make, $model, 2017)
    }

    car ([string]$make, [string]$model, [int]$Year) {
        $this.make = $make
        $this.model = $model
        $this.Year = $year
    }
}

[car]::new() # returns "empty" car
[car]::new('Make', 'Nice model') # returns also an "empty" one
[car]::new( 'make', 'nice model', 2017) # returns a "filled" instance
</code>```

Is there a way to fix this? Did I miss something?

答:
To complement Mathias R. Jessen's helpful answer:

The recommended approach is to use hidden helper methods to compensate for the lack of constructor chaining:

```<code>Class car {

    [string]$Make
    [string]$Model
    [int]$Year

    speedUp (){
        $this.speedUp(5)
    }
    speedUp ([int]$velocity){
        $this.speed += $velocity
    }

    # Hidden, chained helper methods that the constructors must call.
    hidden Init([string]$make)                 { $this.Init($make, $null) }
    hidden Init([string]$make, [string]$model) { $this.Init($make, $model, 2017) }
    hidden Init([string]$make, [string]$model, [int] $year) {
        $this.make = $make
        $this.model = $model
        $this.Year = $year
    }

    # Constructors
    car () {
        $this.Init('Generic')
    }

    car ([string]$make) {
        $this.Init($make)
    }

    car ([string]$make, [string]$model) {
        $this.Init($make, $model)
    }

    car ([string]$make, [string]$model, [int]$year) {
        $this.Init($make, $model, $year)
    }
}

[car]::new()                          # use defaults for all fields
[car]::new('Fiat')                    # use defaults for model and year
[car]::new( 'Nissan', 'Altima', 2015) # specify values for all fields
</code>```

This yields:

```<code>Make    Model  Year
----    -----  ----
Generic        2017
Fiat           2017
Nissan  Altima 2015
</code>```

Note:

The hidden keyword is more of a convention that PowerShell itself observes (such as omitting such members when outputting); members tagged this way are technically still accessible, however.

While you can't call a constructor of the same class directly, it is possible to do so with a base-class constructor, using C#-like syntax.

Body:
I was doing some testing and stumbled upon the following:

You can overload methods in PoShv5 as you wish. If you call the method without parameters, it can internally call the method with parameters, to keep your code non-redundant. I expected this to be also true for constructors.

In this example, the last constructor is working as expected. The other constructors only return objects without set values.

Class car {
    [string]$make
    [string]$model
    [int]$Speed
    [int]$Year

    speedUp (){
        $this.speedUp(5)
    }
    speedUp ([int]$velocity){
        $this.speed += $velocity
    }

    # Constructor
    car () {
        [car]::new('mall', $Null, $null)
    }

    car ([string]$make, [string]$model) {
        [car]::new($make, $model, 2017)
    }

    car ([string]$make, [string]$model, [int]$Year) {
        $this.make = $make
        $this.model = $model
        $this.Year = $year
    }
}

[car]::new() # returns "empty" car
[car]::new('Make', 'Nice model') # returns also an "empty" one
[car]::new( 'make', 'nice model', 2017) # returns a "filled" instance

Is there a way to fix this? Did I miss something?

Body:
To complement Mathias R. Jessen's helpful answer:

The recommended approach is to use hidden helper methods to compensate for the lack of constructor chaining:

Class car {

    [string]$Make
    [string]$Model
    [int]$Year

    speedUp (){
        $this.speedUp(5)
    }
    speedUp ([int]$velocity){
        $this.speed += $velocity
    }

    # Hidden, chained helper methods that the constructors must call.
    hidden Init([string]$make)                 { $this.Init($make, $null) }
    hidden Init([string]$make, [string]$model) { $this.Init($make, $model, 2017) }
    hidden Init([string]$make, [string]$model, [int] $year) {
        $this.make = $make
        $this.model = $model
        $this.Year = $year
    }

    # Constructors
    car () {
        $this.Init('Generic')
    }

    car ([string]$make) {
        $this.Init($make)
    }

    car ([string]$make, [string]$model) {
        $this.Init($make, $model)
    }

    car ([string]$make, [string]$model, [int]$year) {
        $this.Init($make, $model, $year)
    }
}

[car]::new()                          # use defaults for all fields
[car]::new('Fiat')                    # use defaults for model and year
[car]::new( 'Nissan', 'Altima', 2015) # specify values for all fields

This yields:

Make    Model  Year
----    -----  ----
Generic        2017
Fiat           2017
Nissan  Altima 2015

Note:

The hidden keyword is more of a convention that PowerShell itself observes (such as omitting such members when outputting); members tagged this way are technically still accessible, however.

While you can't call a constructor of the same class directly, it is possible to do so with a base-class constructor, using C#-like syntax.


问:
Whats the Oracle equivalent of SELECT 'TEST' as MyColumn
In MSSQL I can type into script editor and execute the following:

```<code>SELECT 'TEST' AS MyColumn
</code>```

Which will output a single row containing TEST in a column called MyColumn

What is the equivalent in Oracle?

答:
it is:

```<code>SELECT 'TEST' AS MyColumn FROM dual;
</code>```

Dual is a table with one column and one record, built into Oracle especially for this purpose:

```<code>SELECT * FROM dual;
</code>```

yields

```<code>Dummy
-----
X
</code>```

If you would construct this table in other databases, queries on dual would also work. (I use this to unit test Oralcle-queries on Sqlite)

Body:
In MSSQL I can type into script editor and execute the following:

SELECT 'TEST' AS MyColumn

Which will output a single row containing TEST in a column called MyColumn

What is the equivalent in Oracle?

Body:
it is:

SELECT 'TEST' AS MyColumn FROM dual;

Dual is a table with one column and one record, built into Oracle especially for this purpose:

SELECT * FROM dual;

yields

Dummy
-----
X

If you would construct this table in other databases, queries on dual would also work. (I use this to unit test Oralcle-queries on Sqlite)


答:
You just need FROM DUAL:

```<code>SELECT 'TEST' AS MyColumn
FROM DUAL;
</code>```

DUAL is a special built-in table that has one row.

Title: Whats the Oracle equivalent of SELECT 'TEST' as MyColumn

Body:
You just need FROM DUAL:

SELECT 'TEST' AS MyColumn
FROM DUAL;

DUAL is a special built-in table that has one row.


问:
How to check if a file is a bash file with PHP?
I have a feature on my website that allow people to upload various types of files. I don't want people to upload bash files but I can't tell by just the file extension since a '.pdf' file could contain only bash code as far as I know. Is there a way to check for sure if a file could be run with bash ?</p>

答:
Use mime_content_type (http://php.net/manual/en/function.mime-content-type.php):</p>

```<code>// #!/bin/bash
$result = mime_content_type(/path/to/exmple);
$result = 'text/x-shellscrip';

// #!/bin/sh
$result = mime_content_type(/path/to/exmple);
$result = 'text/x-shellscrip';
</code>```

Body:
Use mime_content_type (http://php.net/manual/en/function.mime-content-type.php):

// #!/bin/bash
$result = mime_content_type(/path/to/exmple);
$result = 'text/x-shellscrip';

// #!/bin/sh
$result = mime_content_type(/path/to/exmple);
$result = 'text/x-shellscrip';


问:
Using Groovy-Eclipse plugin to develop in Grails
I am evaluating Groovy/Grails for a new project and I am wondering: Can the free Groovy-Eclipse plugin be used to develop Grails applications, and if so, what are the limitations? I am aware of the SpringSource Tool Suite, which includes full support for Grails in Eclipse, but it also includes a bunch of other stuff I don't care about, so I'm looking for a lighter-weight alternative. </p>

答:
No, Groovy-Eclipse only supports Groovy development. For Grails support you'll need either STS or the commercial version of IntelliJ (the free version of IntelliJ only supports Groovy).

If you're worried about the extra plugins in STS, you can probably exclude them when installing it.