问:
Using IObservable (Rx) as a INotifyCollectionChanged Replacement for MVVM?
I have been looking into using Rx in an MVVM framework.  The idea is to use 'live' LINQ queries over in-memory datasets to project data into View Models to bind with.

Previously this has been possible with the use of INotifyPropertyChanged/INotifyCollectionChanged and an open source library called CLINQ.  The potential with Rx and IObservable is to move to a much more declarative ViewModel using Subject classes to propagate changed events from the source model through to the View.  A conversion from IObservable to the regular databinding interfaces would be needed for the last step.

The problem is that Rx doesn't seem to support the notification that an entity has been removed from the stream.  Example below.

The code shows a POCO which uses BehaviorSubject class for the field state.  The code goes onto to create a collection of these entities and use Concat to merge the filter streams together.  This means that any changes to the POCOs are reported to a single stream.

A filter for this stream is setup to filter for Rating==0. The subscription simply outputs the result to the debug window when an even occurs.

Settings Rating=0 on any element will trigger the event.  But setting Rating back to 5 will not see any events.

In the case of CLINQ the output of the query will support INotifyCollectionChanged - so that items added and removed from the query result will fire the correct event to indicate the query result has changed (an item added or removed).

The only way I can think of address this is to set-up two streams with oppossite (dual) queries.  An item added to the opposite stream implies removal from the resultset.  Failing that, I could just use FromEvent and not make any of the entity models observable - which makes Rx more of just an Event Aggregator.  Any pointers?

```<code>using System;
using System.ComponentModel;
using System.Linq;
using System.Collections.Generic;

namespace RxTest
{

    public class TestEntity : Subject<TestEntity>, INotifyPropertyChanged
    {
        public IObservable<string> FileObservable { get; set; }
        public IObservable<int> RatingObservable { get; set; }

        public string File
        {
            get { return FileObservable.First(); }
            set { (FileObservable as IObserver<string>).OnNext(value); }
        }

        public int Rating
        {
            get { return RatingObservable.First(); }
            set { (RatingObservable as IObserver<int>).OnNext(value); }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public TestEntity()
        {
            this.FileObservable = new BehaviorSubject<string>(string.Empty);
            this.RatingObservable = new BehaviorSubject<int>(0);
            this.FileObservable.Subscribe(f => { OnNotifyPropertyChanged("File"); });
            this.RatingObservable.Subscribe(f => { OnNotifyPropertyChanged("Rating"); });
        }

        private void OnNotifyPropertyChanged(string property)
        {
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(property));
            // update the class Observable
            OnNext(this);
        }

    }

    public class TestModel
    {
        private List<TestEntity> collection { get; set; }
        private IDisposable sub;

        public TestModel()
        {
            this.collection = new List<TestEntity>() {
            new TestEntity() { File = "MySong.mp3", Rating = 5 },
            new TestEntity() { File = "Heart.mp3", Rating = 5 },
            new TestEntity() { File = "KarmaPolice.mp3", Rating = 5 }};

            var observableCollection = Observable.Concat<TestEntity>(this.collection.Cast<IObservable<TestEntity>>());
            var filteredCollection = from entity in observableCollection
                                     where entity.Rating==0
                                     select entity;
            this.sub = filteredCollection.Subscribe(entity =>
                {
                    System.Diagnostics.Debug.WriteLine("Added :" + entity.File);
                }
            );
            this.collection[0].Rating = 0;
            this.collection[0].Rating = 5;
        }
    };
}
</code>```

答: What's wrong with using an ObservableCollection<T>? Rx is a very easy framework to overuse; I find that if you find yourself fighting against the basic premise of an asynchronous stream, you probably shouldn't be using Rx for that particular problem.

Body:
I have been looking into using Rx in an MVVM framework.  The idea is to use 'live' LINQ queries over in-memory datasets to project data into View Models to bind with.

Previously this has been possible with the use of INotifyPropertyChanged/INotifyCollectionChanged and an open source library called CLINQ.  The potential with Rx and IObservable is to move to a much more declarative ViewModel using Subject classes to propagate changed events from the source model through to the View.  A conversion from IObservable to the regular databinding interfaces would be needed for the last step.

The problem is that Rx doesn't seem to support the notification that an entity has been removed from the stream.  Example below.

The code shows a POCO which uses BehaviorSubject class for the field state.  The code goes onto to create a collection of these entities and use Concat to merge the filter streams together.  This means that any changes to the POCOs are reported to a single stream.

A filter for this stream is setup to filter for Rating==0. The subscription simply outputs the result to the debug window when an even occurs.

Settings Rating=0 on any element will trigger the event.  But setting Rating back to 5 will not see any events.

In the case of CLINQ the output of the query will support INotifyCollectionChanged - so that items added and removed from the query result will fire the correct event to indicate the query result has changed (an item added or removed).

The only way I can think of address this is to set-up two streams with oppossite (dual) queries.  An item added to the opposite stream implies removal from the resultset.  Failing that, I could just use FromEvent and not make any of the entity models observable - which makes Rx more of just an Event Aggregator.  Any pointers?

using System;
using System.ComponentModel;
using System.Linq;
using System.Collections.Generic;

namespace RxTest
{

    public class TestEntity : Subject<TestEntity>, INotifyPropertyChanged
    {
        public IObservable<string> FileObservable { get; set; }
        public IObservable<int> RatingObservable { get; set; }

        public string File
        {
            get { return FileObservable.First(); }
            set { (FileObservable as IObserver<string>).OnNext(value); }
        }

        public int Rating
        {
            get { return RatingObservable.First(); }
            set { (RatingObservable as IObserver<int>).OnNext(value); }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public TestEntity()
        {
            this.FileObservable = new BehaviorSubject<string>(string.Empty);
            this.RatingObservable = new BehaviorSubject<int>(0);
            this.FileObservable.Subscribe(f => { OnNotifyPropertyChanged("File"); });
            this.RatingObservable.Subscribe(f => { OnNotifyPropertyChanged("Rating"); });
        }

        private void OnNotifyPropertyChanged(string property)
        {
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(property));
            // update the class Observable
            OnNext(this);
        }

    }

    public class TestModel
    {
        private List<TestEntity> collection { get; set; }
        private IDisposable sub;

        public TestModel()
        {
            this.collection = new List<TestEntity>() {
            new TestEntity() { File = "MySong.mp3", Rating = 5 },
            new TestEntity() { File = "Heart.mp3", Rating = 5 },
            new TestEntity() { File = "KarmaPolice.mp3", Rating = 5 }};

            var observableCollection = Observable.Concat<TestEntity>(this.collection.Cast<IObservable<TestEntity>>());
            var filteredCollection = from entity in observableCollection
                                     where entity.Rating==0
                                     select entity;
            this.sub = filteredCollection.Subscribe(entity =>
                {
                    System.Diagnostics.Debug.WriteLine("Added :" + entity.File);
                }
            );
            this.collection[0].Rating = 0;
            this.collection[0].Rating = 5;
        }
    };
}


来源: stackexchange

问:
I am facing some issue during pyrocms installation, Anyone can help me?
```<code> I am using below command for installation: composer create-project pyrocms/pyrocms pyrocms-demo
</code>```

But I am getting below error:

Potential causes:
- A typo in the package name
- The package is not available in a stable-enough version according to your min
imum-stability setting
  see https://getcomposer.org/doc/04-schema.md#minimum-stability for more det
ails.

Read https://getcomposer.org/doc/articles/troubleshooting.md for further commo
n problems.
 To enable extensions, verify that they are enabled in your .ini files:
   - C:\xampp\php\php.ini
 You can also run php --ini inside terminal to see which files are used by PH
P in CLI mode.

答:
I always use

```<code>$ composer create-project pyrocms/pyrocms .
</code>```

when you are already inside the project root.

Also, check your system for requirements form here https://pyrocms.com/documentation/pyrocms/latest#installation/server-requirements

ContentLicense: CC BY-SA 3.0

Body:
 I am using below command for installation: composer create-project pyrocms/pyrocms pyrocms-demo

But I am getting below error:

Potential causes:
- A typo in the package name
- The package is not available in a stable-enough version according to your min
imum-stability setting
  see https://getcomposer.org/doc/04-schema.md#minimum-stability for more det
ails.

Read https://getcomposer.org/doc/articles/troubleshooting.md for further commo
n problems.
 To enable extensions, verify that they are enabled in your .ini files:
   - C:\xampp\php\php.ini
 You can also run php --ini inside terminal to see which files are used by PH
P in CLI mode.

Body:
I always use

$ composer create-project pyrocms/pyrocms .

when you are already inside the project root.

Also, check your system for requirements form here https://pyrocms.com/documentation/pyrocms/latest#installation/server-requirements


问:
select on nvarchar(max) column really slow
SQL Server 2008 R2. I'm doing a select on a table with ~70,000 rows.
If I try to query an nvarchar(max) column, where the longest string is 2,433 characters, it takes 66 seconds.

```<code>select Comment from StudentAssessmentComments
</code>```

Filtering by an indexed column to 17,000 rows still takes ~17 seconds.

```<code>select Comment from StudentAssessmentComments where FileYear = 2016
</code>```

If I query a different, unindexed column, its immediate (< 1sec).

```<code>select StaffID from StudentAssessmentComments
</code>```

Is it normal for an nvarchar(max) column to perform so badly? If not, does anyone have any suggestions? Thanks for any help.

答:
I am going to guess that you have a relatively slow network connection to the database.  The two timings you give are both pretty close to 1,000 rows per second.

If a typical row had 1,000 characters, then this would be about 2,000 bytes (wide characters) and about 2 Mbytes/second.  That seems on the slow side, but it is not unreasonable.

So, my best guess is that this is your "network" connection to the database, so there is not much you can do about it if you need tens of thousands of rows with the full comments.

Body:
SQL Server 2008 R2. I'm doing a select on a table with ~70,000 rows.
If I try to query an nvarchar(max) column, where the longest string is 2,433 characters, it takes 66 seconds.

select Comment from StudentAssessmentComments

Filtering by an indexed column to 17,000 rows still takes ~17 seconds.

select Comment from StudentAssessmentComments where FileYear = 2016

If I query a different, unindexed column, its immediate (< 1sec).

select StaffID from StudentAssessmentComments

Is it normal for an nvarchar(max) column to perform so badly? If not, does anyone have any suggestions? Thanks for any help.


问:
Failed to launch IBCocoaTouchImageCatalogTool via CoreSimulator spawn
I have an Xcode project which was downloaded from the internet so I don't know which Xcode version was used to write it but the language is Swift 2. I opened it in Xcode 7.1 beta 1 and I get the following compile time error.

Failed to launch IBCocoaTouchImageCatalogTool via CoreSimulator spawn

I deleted the DerviedData foler, cleaned and build the project several times. Tried converting the project to latest Swift syntax but it says there's nothing to convert.

I'm all outta ideas. Suggestions?

答:
Maybe you have just cleaned Logs directory...Then you can try this:

```<code>sudo chmod 777 /Users/[YourUserName]/Library/Logs
</code>```

Body:
Maybe you have just cleaned Logs directory...Then you can try this:

sudo chmod 777 /Users/[YourUserName]/Library/Logs


问:
No mapping file found named 'MyBundle.Entity.Review.php' for class 'MyyBundle\Entity\Review'
Im new in symfony2 and I have a big problem here, when I tried to save some data for a entity I got this error

No mapping file found named 'MyBundle.Entity.Review.php' for class 'MyBundle\Entity\Review'

I have read all the answers related to this issue and I can not find the solution. Please, can you help me?

here is my entity code.

```<code><?php

namespace MyBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Review
 */
class Review
{
/**
 * @var int
 */
private $id;

/**
 * @var string
 */
private $content;

/**
 * @var string
 */
private $score;

/**
 * @var int
 */
private $total;

/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * Set content
 *
 * @param string $content
 * @return Review
 */
public function setContent($content)
{
    $this->content = $content;

    return $this;
}

/**
 * Get content
 *
 * @return string
 */
public function getContent()
{
    return $this->content;
}

/**
 * Set score
 *
 * @param string $score
 * @return Review
 */
public function setScore($score)
{
    $this->score = $score;

    return $this;
}

/**
 * Get score
 *
 * @return string
 */
public function getScore()
{
    return $this->score;
}

/**
 * Set total
 *
 * @param integer $total
 * @return Review
 */
public function setTotal($total)
{
    $this->total = $total;

    return $this;
}

/**
 * Get total
 *
 * @return integer
 */
public function getTotal()
{
    return $this->total;
}
</code>```

}

This is my controller

```<code>public function saveReviewAction() {
$request = Request::createFromGlobals();
$request->getPathInfo();
$method = $request->getMethod();

$em = $this->getDoctrine()->getManager();

$review = new Review();
$review->setContent('CONTENT');

// tells Doctrine you want to (eventually) save the Review (no queries yet)
$em->persist($review);

// actually executes the queries (i.e. the INSERT query)
$em->flush();

  return new JsonResponse(array('msg' => 'Json','method' => $review->getContent()));
</code>```

}

If I tried php app/console doctrine:mapping:info i got:

[Exception]

    You do not have any mapped Doctrine ORM entities according to the current configuration. If you have enti

    ties or mapping files you should check your mapping configuration for errors.

Thanks

答:
No mapping file found named 'MyBundle.Entity.Review.php' for class 'MyyBundle\Entity\Review'

According to this error. Sure there should be an importing related issue. because, Your class is inside MyBundle. App is searching for MyyBundle(there are two 'y's in your My). Check the bundle name and importing lines again.

Body:
Im new in symfony2 and I have a big problem here, when I tried to save some data for a entity I got this error

No mapping file found named 'MyBundle.Entity.Review.php' for class 'MyBundle\Entity\Review'

I have read all the answers related to this issue and I can not find the solution. Please, can you help me?

here is my entity code.

<?php

namespace MyBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Review
 */
class Review
{
/**
 * @var int
 */
private $id;

/**
 * @var string
 */
private $content;

/**
 * @var string
 */
private $score;

/**
 * @var int
 */
private $total;

/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * Set content
 *
 * @param string $content
 * @return Review
 */
public function setContent($content)
{
    $this->content = $content;

    return $this;
}

/**
 * Get content
 *
 * @return string
 */
public function getContent()
{
    return $this->content;
}

/**
 * Set score
 *
 * @param string $score
 * @return Review
 */
public function setScore($score)
{
    $this->score = $score;

    return $this;
}

/**
 * Get score
 *
 * @return string
 */
public function getScore()
{
    return $this->score;
}

/**
 * Set total
 *
 * @param integer $total
 * @return Review
 */
public function setTotal($total)
{
    $this->total = $total;

    return $this;
}

/**
 * Get total
 *
 * @return integer
 */
public function getTotal()
{
    return $this->total;
}

}

This is my controller

public function saveReviewAction() {
$request = Request::createFromGlobals();
$request->getPathInfo();
$method = $request->getMethod();

$em = $this->getDoctrine()->getManager();

$review = new Review();
$review->setContent('CONTENT');

// tells Doctrine you want to (eventually) save the Review (no queries yet)
$em->persist($review);

// actually executes the queries (i.e. the INSERT query)
$em->flush();

  return new JsonResponse(array('msg' => 'Json','method' => $review->getContent()));

}

If I tried php app/console doctrine:mapping:info i got:

[Exception]

    You do not have any mapped Doctrine ORM entities according to the current configuration. If you have enti

    ties or mapping files you should check your mapping configuration for errors.

Thanks


问:
How to give execute privilege to gradlew file before checking to git
Can someone let me know how to give execute privilege to gradlew file so that the shell script inside concourse server can execute ./gradlew test?

Thanks!

答:
This depends on how the ./gradlew gets to the concourse container. If it is part of a git resource, which I assume is the most likely way you are using it, then you have to commit the permissions on your own machine and then push, as github picks up the permissions of every file on your local file system. So...

```<code>chmod +x gradlew
git add .
git ci -m "fix permissions for gradlew"
git push
</code>```

Body:
This depends on how the ./gradlew gets to the concourse container. If it is part of a git resource, which I assume is the most likely way you are using it, then you have to commit the permissions on your own machine and then push, as github picks up the permissions of every file on your local file system. So...

chmod +x gradlew
git add .
git ci -m "fix permissions for gradlew"
git push


问:
Conditional sumif for dynamically change range
I want to use

```<code>=if((sumif(c1:c15,"ukw",b1:b15)>=12),(sumif(cX:c15,"ukw",bX:b15)),(sumif(c1:c15,"ukw",b1:b15))
</code>```

Now I want X in cX should automatically change to C cell  number which when added satisfied the condition >=12.How to achieve it?

答:
You will have to make use of INDIRECT function along with the SUMIF.

Have a look at the following sites. They have some examples which explain the use. Give it a try - you should be able to resolve your problem with this.

https://www.thoughtco.com/excel-sum-indirect-dynamic-range-formula-3124100

https://superuser.com/questions/934329/how-to-use-indirect-with-a-sumif-formula-for-a-date-range

Hope this Helps.

Body:
I want to use

=if((sumif(c1:c15,"ukw",b1:b15)>=12),(sumif(cX:c15,"ukw",bX:b15)),(sumif(c1:c15,"ukw",b1:b15))

Now I want X in cX should automatically change to C cell  number which when added satisfied the condition >=12.How to achieve it?


问:
Thread 3: Fatal error: Index out of range
I am trying to make to extract weather data but I get an out of range error. can anyone help? My friend told me its a problem with my array but I was sure to use a string separator.

My main goal is to retrieve the weather data from the website and then add it to a variable called message

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    let url = URL(string: "https://weather.weatherbug.com/weather-forecast/now/salt-lake-city")!
    let request = NSMutableURLRequest(url: url)

    let task = URLSession.shared.dataTask(with: request as URLRequest){
        data, response, error in

        var message = ""
        if  error != nil{
            print(error.debugDescription)
        }else{
            if let unwrappedData = data {
                let dataString = NSString(data: unwrappedData, encoding: String.Encoding.utf8.rawValue)

                var stringSeperator = "<span class=\"value ng-binding ng-scope\" ng-if=\"widget.ObservationAggregate.Observation.FeelsLike\" ng-bind=\"UnitUtility.convertTemp(widget.ObservationAggregate.Observation.FeelsLike)\">"

                if let contentArray = dataString?.components(separatedBy: stringSeperator){
                    if contentArray.count > 0 {
                       stringSeperator = "</span>"

                       let newContentArray = contentArray[1].components(separatedBy: stringSeperator)

                       if newContentArray.count > 0 {
                           message = newContentArray[0]
                           print(newContentArray[0])
                       }
                    }
                }
            }
        }
    }

    task.resume()
}
</code>```

答:
When we want to get some info from a server it is recommended to get/parse a JSON or an XML. I see you are trying to parse an HTML from a website.

After clarifying that, if you don't have alternatives, I think you are reaching to those error: Index out of range since you are assuming your data will have always the format you think (normally you need to handle special cases)

You could update your internal validation to this:

```<code>if contentArray.count > 1 {
         stringSeperator = "</span>"
         let newContentArray = contentArray[1].components(separatedBy: stringSeperator)
         if newContentArray.count > 0 {
            message = newContentArray.first
            print(newContentArray.first)
         }
}
</code>```

You can group those if in a better way but this is just to guide you.

I hope this helps you.

Body:
I am trying to make to extract weather data but I get an out of range error. can anyone help? My friend told me its a problem with my array but I was sure to use a string separator.

My main goal is to retrieve the weather data from the website and then add it to a variable called message

override func viewDidLoad() {
    super.viewDidLoad()
    let url = URL(string: "https://weather.weatherbug.com/weather-forecast/now/salt-lake-city")!
    let request = NSMutableURLRequest(url: url)

    let task = URLSession.shared.dataTask(with: request as URLRequest){
        data, response, error in

        var message = ""
        if  error != nil{
            print(error.debugDescription)
        }else{
            if let unwrappedData = data {
                let dataString = NSString(data: unwrappedData, encoding: String.Encoding.utf8.rawValue)

                var stringSeperator = ""

                if let contentArray = dataString?.components(separatedBy: stringSeperator){
                    if contentArray.count > 0 {
                       stringSeperator = ""

                       let newContentArray = contentArray[1].components(separatedBy: stringSeperator)

                       if newContentArray.count > 0 {
                           message = newContentArray[0]
                           print(newContentArray[0])
                       }
                    }
                }
            }
        }
    }

    task.resume()
}

Body:
When we want to get some info from a server it is recommended to get/parse a JSON or an XML. I see you are trying to parse an HTML from a website.

After clarifying that, if you don't have alternatives, I think you are reaching to those error: Index out of range since you are assuming your data will have always the format you think (normally you need to handle special cases)

You could update your internal validation to this:

if contentArray.count > 1 {
         stringSeperator = "</span>"
         let newContentArray = contentArray[1].components(separatedBy: stringSeperator)
         if newContentArray.count > 0 {
            message = newContentArray.first
            print(newContentArray.first)
         }
}

You can group those if in a better way but this is just to guide you.

I hope this helps you.


问:
Code works outside function, but not inside function (python)
I'm trying to print the number of lines in a file, when I use the code outside of a function, it works fine:

```<code>input_file_name = input("Please Enter the name of your text file: ")
infile = open(input_file_name, "r")

listOfLines = infile.readlines()
count = 0
char = " "

for line in listOfLines :
    text = line.rstrip()
    while char != "":
        char = infile.read(1)
    count = count + 1
print(count)

infile.close()
</code>```

but when I use the same code inside of a function it prints a value of 0 instead of 5 (which is the length of my test file).

```<code>def main():

    input_file_name = input("Please Enter the name of your text file: ")
    infile = open(input_file_name, "r")
    print()

    print_file(infile)
    count_lines(infile)

    infile.close()

def print_file(infile):
    listOfLines = infile.readlines()
    for line in listOfLines:
        text = line.rstrip()
        print(text)

def count_lines(infile):
    listOfLines = infile.readlines()
    count = 0
    char = " "

    for line in listOfLines :
        text = line.rstrip()
        while char != "":
            char = infile.read(1)
        count = count + 1
    print(count)

main()
</code>```

However, if I remove the function

```<code>def print_file(infile):
listOfLines = infile.readlines()
for line in listOfLines:
    text = line.rstrip()
    print(text)
</code>```

and the call for the function,

```<code>print_file(infile)
</code>```

it works fine. Why does the first function effect how the second function prints?

答:
The file object you create using infile = open(input_file_name, "r") is an iterator.  It can be looped over one time only.

Your print_file function performs the first iteration over the file, exhausting its content.  When you attempt the second iteration in count_lines, the iterator has ended, so nothing else occurs.

Body:
I'm trying to print the number of lines in a file, when I use the code outside of a function, it works fine:

input_file_name = input("Please Enter the name of your text file: ")
infile = open(input_file_name, "r")

listOfLines = infile.readlines()
count = 0
char = " "

for line in listOfLines :
    text = line.rstrip()
    while char != "":
        char = infile.read(1)
    count = count + 1
print(count)

infile.close()

but when I use the same code inside of a function it prints a value of 0 instead of 5 (which is the length of my test file).

def main():

    input_file_name = input("Please Enter the name of your text file: ")
    infile = open(input_file_name, "r")
    print()

    print_file(infile)
    count_lines(infile)

    infile.close()

def print_file(infile):
    listOfLines = infile.readlines()
    for line in listOfLines:
        text = line.rstrip()
        print(text)

def count_lines(infile):
    listOfLines = infile.readlines()
    count = 0
    char = " "

    for line in listOfLines :
        text = line.rstrip()
        while char != "":
            char = infile.read(1)
        count = count + 1
    print(count)

main()

However, if I remove the function

def print_file(infile):
listOfLines = infile.readlines()
for line in listOfLines:
    text = line.rstrip()
    print(text)

and the call for the function,

print_file(infile)

it works fine. Why does the first function effect how the second function prints?


问:
Stack pointer does not seem to increase when using pushad in recursive function
```<code>int x = 5;

void foo()
{
  long unsigned r[8];
  memset(&r, 0, sizeof(long unsigned) * 8);

  __asm {

    pushad;

    pop r[7];
    pop r[6];
    pop r[5];
    pop r[4];
    pop r[3];
    pop r[2];
    pop r[1];
    pop r[0];
  }

  printf("Register values: \n");

  printf("eax: %lu\n", r[0]);
  printf("ecx: %lu\n", r[1]);
  printf("edx: %lu\n", r[2]);
  printf("ebx: %lu\n", r[3]);
  printf("esp: %lu\n", r[4]);
  printf("ebp: %lu\n", r[5]);
  printf("esi: %lu\n", r[6]);
  printf("edi: %lu\n", r[7]);

  if (--x) { foo(); }
}

int main()
{
  foo();
  return 0;
}
</code>```

I just learned about the pushad/pusha operation and am trying to see how the GPRs change. However I seem to be getting a 0 print out for all of these except for r[0] which prints out numbers descending by 44 for each foo() call. Is that correct?

From what little I understand, shouldn't the esp register be moving every time I call a new function?

答:
This doesn't quite do you what you want:

```<code>pop r[7];
pop r[6];
pop r[5];
pop r[4];
pop r[3];
pop r[2];
pop r[1];
pop r[0];
</code>```

This doesn't actually compute the address of each LONG in the array r and pop the values to that location. it would have been like writing:

```<code>pop [r+7];
pop [r+6];
pop [r+5];
pop [r+4];
pop [r+3];
pop [r+2];
pop [r+1];
pop [r+0];
</code>```

The inline assembly doesn't take into account the size of an array data element. Adding a value to the base of an array increments as if the index was in bytes.

It may be more evident as to what has happened. r will be the base address of the array (since it is on the stack it will be relative to ebp). r+0 is the location of the first BYTE, r+1 is the location of the second BYTE etc. You need to do the math and compute the index for each LONG. So it should have looked something like:

```<code>pop r[28];
pop r[24];
pop r[20];
pop r[16];
pop r[12];
pop r[8];
pop r[4];
pop r[0];
</code>```

Body:
int x = 5;

void foo()
{
  long unsigned r[8];
  memset(&r, 0, sizeof(long unsigned) * 8);

  __asm {

    pushad;

    pop r[7];
    pop r[6];
    pop r[5];
    pop r[4];
    pop r[3];
    pop r[2];
    pop r[1];
    pop r[0];
  }

  printf("Register values: \n");

  printf("eax: %lu\n", r[0]);
  printf("ecx: %lu\n", r[1]);
  printf("edx: %lu\n", r[2]);
  printf("ebx: %lu\n", r[3]);
  printf("esp: %lu\n", r[4]);
  printf("ebp: %lu\n", r[5]);
  printf("esi: %lu\n", r[6]);
  printf("edi: %lu\n", r[7]);

  if (--x) { foo(); }
}

int main()
{
  foo();
  return 0;
}

I just learned about the pushad/pusha operation and am trying to see how the GPRs change. However I seem to be getting a 0 print out for all of these except for r[0] which prints out numbers descending by 44 for each foo() call. Is that correct?

From what little I understand, shouldn't the esp register be moving every time I call a new function?

Body:
This doesn't quite do you what you want:

pop r[7];
pop r[6];
pop r[5];
pop r[4];
pop r[3];
pop r[2];
pop r[1];
pop r[0];

This doesn't actually compute the address of each LONG in the array r and pop the values to that location. it would have been like writing:

pop [r+7];
pop [r+6];
pop [r+5];
pop [r+4];
pop [r+3];
pop [r+2];
pop [r+1];
pop [r+0];

The inline assembly doesn't take into account the size of an array data element. Adding a value to the base of an array increments as if the index was in bytes.

It may be more evident as to what has happened. r will be the base address of the array (since it is on the stack it will be relative to ebp). r+0 is the location of the first BYTE, r+1 is the location of the second BYTE etc. You need to do the math and compute the index for each LONG. So it should have looked something like:

pop r[28];
pop r[24];
pop r[20];
pop r[16];
pop r[12];
pop r[8];
pop r[4];
pop r[0];


问:
How to get value from RecycleAdapter and set to MainActivity Text?
My Adapter Code looks like :

```<code>    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        GetSet getSet = allData.get(position);
        holder.tvId.setText(getSet.getId().toString());
        holder.tvName.setText(getSet.getName());

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        @BindView(R.id.tvId)
        TextView tvId;

        @BindView(R.id.tvName)
        TextView tvName;
</code>```

I have textview in MainActivity, my question is how to get value/text id and name to set in textview?

答:
If you want to get Id or name of an Item on Recyclerview You can write a public function in Adapter Code like this:

```<code>public GetSet getGetSetItem(int position){
  return allData.get(position);
}
</code>```

Then you call in MainActivity like this: adapter.getGetSetItem(1).getId(); or adapter.getGetSetItem(1).getName();

Body:
My Adapter Code looks like :

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        GetSet getSet = allData.get(position);
        holder.tvId.setText(getSet.getId().toString());
        holder.tvName.setText(getSet.getName());

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        @BindView(R.id.tvId)
        TextView tvId;

        @BindView(R.id.tvName)
        TextView tvName;

I have textview in MainActivity, my question is how to get value/text id and name to set in textview?

Body:
If you want to get Id or name of an Item on Recyclerview You can write a public function in Adapter Code like this:

public GetSet getGetSetItem(int position){
  return allData.get(position);
}

Then you call in MainActivity like this: adapter.getGetSetItem(1).getId(); or adapter.getGetSetItem(1).getName();


问:
Rejecting a $q.defer causing unhandled rejection error to be thrown
I have recently updated from 1.5 to 1.6.3 and have code where I am using deferred promise objects using the $q service which is now throwing the following errors in my unit test runs:

```<code>Possibly unhandled rejection: undefined thrown
</code>```

Here is the typical structure of a function I have in my code that uses a deferred promise:

```<code>public someFunction = () => {
    const deferred = this.$q.defer();
    if (someConditionIsTrue) {
        this.myService.getThings().then((response) => {
            deferred.resolve(response);
        });
    } else {
        deferred.reject();
    }
    return deferred.promise;
};
</code>```

When unit testing the else condition I get this error thrown (using karma\jasmine\phantomJS)

I already have the following configured also:

```<code>config(['$qProvider', ($qProvider) => {
        $qProvider.errorOnUnhandledRejections(false);
      }])
</code>```

Can someone point me in the right direction please?

Thanks

答:
Angular is suggesting you to handle every possible route of the promise.

Currently you are missing this part:

```<code>public someFunction = () => {
    const deferred = this.$q.defer();
    if (someConditionIsTrue) {
        this.myService.getThings().then((response) => {
            deferred.resolve(response);
        });
        // what happen if this promise is rejected?
    } else {
        deferred.reject();
    }
    return deferred.promise;
};
</code>```

While you can add a .catch on the commented part, I would suggest changing the whole structure like this for cleaner code and easier maintenance:

```<code>public someFunction = () => {
    if (someConditionIsTrue) {
        return this.myService.getThings();
        // this will pass back whatever resolve/reject to upper layer
    } else {
        return $q.reject();
    }
};
</code>```

Body:
I have recently updated from 1.5 to 1.6.3 and have code where I am using deferred promise objects using the $q service which is now throwing the following errors in my unit test runs:

Possibly unhandled rejection: undefined thrown

Here is the typical structure of a function I have in my code that uses a deferred promise:

public someFunction = () => {
    const deferred = this.$q.defer();
    if (someConditionIsTrue) {
        this.myService.getThings().then((response) => {
            deferred.resolve(response);
        });
    } else {
        deferred.reject();
    }
    return deferred.promise;
};

When unit testing the else condition I get this error thrown (using karma\jasmine\phantomJS)

I already have the following configured also:

config(['$qProvider', ($qProvider) => {
        $qProvider.errorOnUnhandledRejections(false);
      }])

Can someone point me in the right direction please?

Thanks

Body:
Angular is suggesting you to handle every possible route of the promise.

Currently you are missing this part:

public someFunction = () => {
    const deferred = this.$q.defer();
    if (someConditionIsTrue) {
        this.myService.getThings().then((response) => {
            deferred.resolve(response);
        });
        // what happen if this promise is rejected?
    } else {
        deferred.reject();
    }
    return deferred.promise;
};

While you can add a .catch on the commented part, I would suggest changing the whole structure like this for cleaner code and easier maintenance:

public someFunction = () => {
    if (someConditionIsTrue) {
        return this.myService.getThings();
        // this will pass back whatever resolve/reject to upper layer
    } else {
        return $q.reject();
    }
};


问:
VSTO Unit Testing Office AddIn in C# .NET via RequestComAddInAutomationService
I have worked and read through various StackOverflow questions and other tutorials and documentation over the past weeks (N.B. some of them below) to try and find a way of unit testing a VSTO AddIn.

Unfortunately, it always results in an E_NOINTERFACE exception in my tests.

The code I am using is below - one extract of the ThisAddin partial class overriding the RequestComAddinAutomationService, another describing the test utility interface, the test itself, as well as an additional assembly extract proving that the AddIn assembly and its internals are visible to the test.

My question is: why is this not working?  I am pretty sure that this follows the generally accepted practices of VSTO testing.

If the below is not possible anymore, how should one go about testing VSTO?  Is .NET remoting/IPC the only solution?

ThisAddin.cs

```<code>public partial class ThisAddin
{
    #region Testing Utilities

    private AddinHelper _comAddinObject;

    protected override object RequestComAddInAutomationService()
    {
        // This is being called when I debug/run my project, but not when I run the tests
        return _comAddinObject ?? (_comAddinObject = new AddinHelper());
    }

    #endregion
}

#region Testing Utilities

[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface IAddinHelper
{
    Presentation GetPresentation();
    string GetString();
}

[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(IAddinHelper))]
public class AddinHelper : StandardOleMarshalObject, IAddinHelper
{
    public Presentation GetPresentation()
    {
        return Globals.ThisAddin... [...];
    }

    public string GetString()
    {
        return "Hello World!";
    }
}

#endregion
</code>```

AssemblyInfo.cs

```<code>[assembly: InternalsVisibleTo("MyProject.Tests")]
</code>```

MyUnitTest.cs (has a reference to MyProject)

```<code>[TestClass]
public class BasicTest
{
    [TestMethod]
    public void TestInstantiates()
    {
        var application = new Application();
        var doc = application.Presentations.Open(@"C:\Presentation.pptx",
            MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);
        var comAddins = application.COMAddIns;
        var comAddin = comAddins.Item("MyProject"); // Returns okay
        var comObject = (IAddinHelper) comAddin.Object; // Exception occurs

        Assert.AreEqual(true, true); // Never reached

        doc.Close();
    }
}
</code>```

Furthermore, the project's settings are set to "Register for COM interop" and Visual Studio runs elevated without errors - running it as non-admin results in the DLLs not being registered; therefore, I also know that the COM objects are registered.

Resulting Exception

An exception of type 'System.InvalidCastException' occurred in MyProject.Tests.dll but was not handled in user code
  Additional information: Unable to cast COM object of type 'System.__ComObject' to interface type 'MyProject.IAddinHelper'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{59977378-CC79-3B27-9093-82CD7A05CF74}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).

StackOverflow

How to call VSTO class from other c# project

Unit Testing VSTO projects

VSTO Add-ins, COMAddIns and RequestComAddInAutomationService (Register for COM Interop doesn't change anything)

Why cannot I cast my COM object to the interface it implements in C#? (the issue is likely not STAThread related)

https://sqa.stackexchange.com/questions/2545/how-do-i-unit-test-word-addin-written-in-c

Microsoft

https://blogs.msdn.microsoft.com/varsha/2010/08/17/writing-automated-test-cases-for-vsto-application/  <-- Even with this supposedly working sample project, I am getting the exact same error.

https://msdn.microsoft.com/en-us/library/bb608621.aspx

General workflow background: https://msdn.microsoft.com/en-us/library/bb386298.aspx

I honestly don't know how one is supposed to test VSTO Add-Ins without this working.

答:
Solution

The Project with methods to be Tested has to use the PIA Microsoft.Office.Interop.PowerPoint via the .Net reference tab.

In the Unit Test Project you have to use the Microsoft Powerpoint 1X.0 Object Library via the COM reference tab - its an ActiveX.

The confusing thing is in Solution Explorer they are both called: Microsoft.Office.Interop.Powerpoint

When you specify the correct References you'll see this error on the line where the exception occurs:

Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'

To solve that simply add a .Net reference to the Microsoft.CSharp.dll in the Unit Test project.

Next we will run into the error you're seeing.

Firstly add a unique GUID to the Interface & class (this will overcome the error):

```<code>[ComVisible(true)]
[Guid("B523844E-1A41-4118-A0F0-FDFA7BCD77C9")]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface IAddinHelper
{
    string GetPresentation();
    string GetString();
}

[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[Guid("A523844E-1A41-4118-A0F0-FDFA7BCD77C9")]
[ComSourceInterfaces(typeof(IAddinHelper))]
public class AddinHelper : StandardOleMarshalObject, IAddinHelper
</code>```

Secondly temporarily make the private AddinHelper _comAddinObject; public in Scope (you can do your [assembly: InternalsVisibleTo("MyProject.Tests")] later when its working).

Thirdly, check that Powerpoint has not disabled the COM add-in. This sometimes happens silently, without the Office App complaining.

Lastly, make sure Register for COM is ticked.

Viola:

Ref: I pulled my hair out working this out years ago helping this fellow SO'r: Moq & Interop Types: works in VS2012, fails in VS2010?

Body:
I have worked and read through various StackOverflow questions and other tutorials and documentation over the past weeks (N.B. some of them below) to try and find a way of unit testing a VSTO AddIn.

Unfortunately, it always results in an E_NOINTERFACE exception in my tests.

The code I am using is below - one extract of the ThisAddin partial class overriding the RequestComAddinAutomationService, another describing the test utility interface, the test itself, as well as an additional assembly extract proving that the AddIn assembly and its internals are visible to the test.

My question is: why is this not working?  I am pretty sure that this follows the generally accepted practices of VSTO testing.

If the below is not possible anymore, how should one go about testing VSTO?  Is .NET remoting/IPC the only solution?

ThisAddin.cs

public partial class ThisAddin
{
    #region Testing Utilities

    private AddinHelper _comAddinObject;

    protected override object RequestComAddInAutomationService()
    {
        // This is being called when I debug/run my project, but not when I run the tests
        return _comAddinObject ?? (_comAddinObject = new AddinHelper());
    }

    #endregion
}

#region Testing Utilities

[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface IAddinHelper
{
    Presentation GetPresentation();
    string GetString();
}

[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(IAddinHelper))]
public class AddinHelper : StandardOleMarshalObject, IAddinHelper
{
    public Presentation GetPresentation()
    {
        return Globals.ThisAddin... [...];
    }

    public string GetString()
    {
        return "Hello World!";
    }
}

#endregion

AssemblyInfo.cs

[assembly: InternalsVisibleTo("MyProject.Tests")]

MyUnitTest.cs (has a reference to MyProject)

[TestClass]
public class BasicTest
{
    [TestMethod]
    public void TestInstantiates()
    {
        var application = new Application();
        var doc = application.Presentations.Open(@"C:\Presentation.pptx",
            MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);
        var comAddins = application.COMAddIns;
        var comAddin = comAddins.Item("MyProject"); // Returns okay
        var comObject = (IAddinHelper) comAddin.Object; // Exception occurs

        Assert.AreEqual(true, true); // Never reached

        doc.Close();
    }
}

Furthermore, the project's settings are set to "Register for COM interop" and Visual Studio runs elevated without errors - running it as non-admin results in the DLLs not being registered; therefore, I also know that the COM objects are registered.

Resulting Exception

An exception of type 'System.InvalidCastException' occurred in MyProject.Tests.dll but was not handled in user code
  Additional information: Unable to cast COM object of type 'System.__ComObject' to interface type 'MyProject.IAddinHelper'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{59977378-CC79-3B27-9093-82CD7A05CF74}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).

StackOverflow

How to call VSTO class from other c# project

Unit Testing VSTO projects

VSTO Add-ins, COMAddIns and RequestComAddInAutomationService (Register for COM Interop doesn't change anything)

Why cannot I cast my COM object to the interface it implements in C#? (the issue is likely not STAThread related)

https://sqa.stackexchange.com/questions/2545/how-do-i-unit-test-word-addin-written-in-c

Microsoft

https://blogs.msdn.microsoft.com/varsha/2010/08/17/writing-automated-test-cases-for-vsto-application/  <-- Even with this supposedly working sample project, I am getting the exact same error.

https://msdn.microsoft.com/en-us/library/bb608621.aspx

General workflow background: https://msdn.microsoft.com/en-us/library/bb386298.aspx

I honestly don't know how one is supposed to test VSTO Add-Ins without this working.

Body:
Solution

The Project with methods to be Tested has to use the PIA Microsoft.Office.Interop.PowerPoint via the .Net reference tab.

In the Unit Test Project you have to use the Microsoft Powerpoint 1X.0 Object Library via the COM reference tab - its an ActiveX.

The confusing thing is in Solution Explorer they are both called: Microsoft.Office.Interop.Powerpoint

When you specify the correct References you'll see this error on the line where the exception occurs:

Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'

To solve that simply add a .Net reference to the Microsoft.CSharp.dll in the Unit Test project.

Next we will run into the error you're seeing.

Firstly add a unique GUID to the Interface & class (this will overcome the error):

[ComVisible(true)]
[Guid("B523844E-1A41-4118-A0F0-FDFA7BCD77C9")]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface IAddinHelper
{
    string GetPresentation();
    string GetString();
}

[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[Guid("A523844E-1A41-4118-A0F0-FDFA7BCD77C9")]
[ComSourceInterfaces(typeof(IAddinHelper))]
public class AddinHelper : StandardOleMarshalObject, IAddinHelper

Secondly temporarily make the private AddinHelper _comAddinObject; public in Scope (you can do your [assembly: InternalsVisibleTo("MyProject.Tests")] later when its working).

Thirdly, check that Powerpoint has not disabled the COM add-in. This sometimes happens silently, without the Office App complaining.

Lastly, make sure Register for COM is ticked.

Viola:

Ref: I pulled my hair out working this out years ago helping this fellow SO'r: Moq & Interop Types: works in VS2012, fails in VS2010?


问:
Twilio TaskRouter - ordering workers
I am trying to configure TaskRouter - Ordering Workers as explained in https://www.twilio.com/docs/api/taskrouter/ordering-workers.

However I couldn't find the order_by expression in WorkFlow or Task or TaskQueues from Twilio TaskRouter UI.

Where exactly do I need to configure order_by expression.

Thanks.

答:
Twilio developer evangelist here.

I'm afraid that the Task Router console hasn't caught up with those features just yet. The best way to add an order_by expression to your workflow would be by updating the JSON config through the API right now.

There is a ticket open to add this to the console though.

Update

Setting order_by expressions is now possible through the Twilio TaskRouter UI.

Title: Twilio TaskRouter - ordering workers


问:
Interface to a webservice?
I have two webservices that have exactly the same methods and signatures but point at different servers (specifically the Virtual Earth production and staging environments). I wish to switch between using the production and staging services on the basis of a config setting and don't want to repeat myself and replicate each method where I call one of the services.

So what I need in effect is to create an interface which both of the services can implement and program against that. But I don't know if this is advisable or even possible.

Or do I just need to reference one of the services and switch the url property depending on whether I want to use the production or staging environment?

答: If I understand you right, you have ONE webservice which is deployed in production and staging environments. In this case the only thing you have to do is to switch between them via the Url property.</p>

OwnerDisplayName: codeburns

ContentLicense: CC BY-SA 2.5

Title: Interface to a webservice?

OwnerDisplayName: Prensen


问:
Puppet : file resource only if file exists
What I want to do is quite simple :

1.

Copy /source/file to /target/file. I achieve this using the following:

```<code>file { 'my_file_copy':
  ensure   => file,
  source   => 'file:/source/file',
  path     => "/target/file",
}
</code>```

2.

However, if file /source/file does not exist, I do NOT want it to perform this task.

I am really struggling with this logic. I attempted the solution below but it throws exceptions during puppet run.

puppet: if one file exists then copy another file over

Is there a better way of achieving this task ?
Ideally, I would like to only use "file" and avoid using "exec". But at this point I would settle for a solution !

答:
Because Puppet is a declarative language where only the end-state is declared, imperative logic such as what you've described - if A, do X - is often hard to express.

Personally, I would try to simply avoid this requirement of having file B copied if and only if file A exists. Often there's a better way.

If the requirement needs to stay, however, then use of Exec here sounds like a pretty good option to me.

```<code>exec { 'my_file_copy':
  command => 'cp /source/file /target/file',
  onlyif  => 'test -e /source/file',
  creates => '/target/file',
  path    => '/bin',
}
</code>```

Body:
What I want to do is quite simple :

1.

Copy /source/file to /target/file. I achieve this using the following:

file { 'my_file_copy':
  ensure   => file,
  source   => 'file:/source/file',
  path     => "/target/file",
}

2.

However, if file /source/file does not exist, I do NOT want it to perform this task.

I am really struggling with this logic. I attempted the solution below but it throws exceptions during puppet run.

puppet: if one file exists then copy another file over

Is there a better way of achieving this task ?
Ideally, I would like to only use "file" and avoid using "exec". But at this point I would settle for a solution !

Body:
Because Puppet is a declarative language where only the end-state is declared, imperative logic such as what you've described - if A, do X - is often hard to express.

Personally, I would try to simply avoid this requirement of having file B copied if and only if file A exists. Often there's a better way.

If the requirement needs to stay, however, then use of Exec here sounds like a pretty good option to me.

exec { 'my_file_copy':
  command => 'cp /source/file /target/file',
  onlyif  => 'test -e /source/file',
  creates => '/target/file',
  path    => '/bin',
}


问:
Using a smooth scroll snippet, center element in page
I am using this script.

```<code>$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});
</code>```

It is working well, except for one thing. When I click on the anchor, and get scrolled down, half of the text is cut off. I want to make an offset or something, so there is a little whitespace at the top of the screen above the text, like this:

Currently, it looks like this:

答:
Try something like:

```<code>scrollTop: target.offset().top - target.height()
</code>```

To let a little space at top...

Or you could do something like (not sure, need to be tested):

```<code>var video = target.next() // considering that is the video block
var centerizeHeight = $(window).height() - (target.height() + video.height())
centerizeHeight = (centerizeHeight > 0) centerizeHeight : 1
//...
scrollTop: target.offset().top - (centerizeHeight/2)
</code>```

Note: be sure your doctype is in your page

Body:
I am using this script.

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

It is working well, except for one thing. When I click on the anchor, and get scrolled down, half of the text is cut off. I want to make an offset or something, so there is a little whitespace at the top of the screen above the text, like this:

Currently, it looks like this:

Body:
Try something like:

scrollTop: target.offset().top - target.height()

To let a little space at top...

Or you could do something like (not sure, need to be tested):

var video = target.next() // considering that is the video block
var centerizeHeight = $(window).height() - (target.height() + video.height())
centerizeHeight = (centerizeHeight > 0) centerizeHeight : 1
//...
scrollTop: target.offset().top - (centerizeHeight/2)

Note: be sure your doctype is in your page


问:
How to let user decide the increment of a series bounded by a range?
I want to print a list of number which is bounded by the range -2 <= x <= 2 in an incremental value such that the list always start with -2 and ends with 2 or vice versa. I'm looking to let the user input an increment value i.e. 0.5 or 0.05. From the range given above it is evident that the largest increment would be 4.

I'm looking to prompt an error message whenever the user inputs an increment value that's > 4 and also when they input an increment value that doesn't allow the list to start printing from 2 and finishes at -2 i.e. when the increment value is 0.23.

The way I thought I could do would be to use the modulus operator where if (4%increment value) = str() i.e. a whole number means that the given increment value is valid for that range. However I'm slightly stuck since when I run my code I end up in a never ending loop. Below is what I've done so far, so hoping somebody can help me out here:

```<code>def IncCheck():
    while True:
        try:     #I first check if the user inputs me a string then an error message would come up
            c = float(input("For the range -2 <= x <= 2, please input the increment you wish to display: "))
            break
        except ValueError:
            print("Invalid input. The increment has to be a number.")
    while 4%c != int():    #Here I wanna check the validity of the increment value so ideally it'd be < 4 and be a value that prints a list that starts with -2 and ends with 2.
        print("Your selected increment is not valid for -2 <= x <= 2. It should be a divisible increment of 4(the range). Please try again.")
        if c > 4:
            print("Your increment is too high. The maximum increment for the given range is 4. Please try again.")
    return c

print(IncCheck())
</code>```

As you can see I've tried to create a function which checks the increment. In the end I'm looking to print the list using something like

```<code>import numpy as np
for i in np.arange(2, -2-c, -c): #c is the increment value the users input
    print i
</code>```

which I can use to do other things. I need to use these x values and plot them into an arctan(x) function that I've approximated using a Taylor Series with a N value i.e. the number of iterations in the Taylor Series and compare them side by side with a real arctan(x) function basically. And then graph them. Thanks in advance.

答:
let increment be c.

if c is less than 0, check

find X by evaluating: 2 + (cX) = -2

Check X by plugging it into the above equation and verify result

else if c is greater than 0, check

find X by evaluating: -2 + (cX) = 2

Check X by plugging it into the above equation and verify result

else, not possible - cannot go anywhere with an increment of zero. Throw an exception or print error message

Body:
I want to print a list of number which is bounded by the range -2 <= x <= 2 in an incremental value such that the list always start with -2 and ends with 2 or vice versa. I'm looking to let the user input an increment value i.e. 0.5 or 0.05. From the range given above it is evident that the largest increment would be 4.

I'm looking to prompt an error message whenever the user inputs an increment value that's > 4 and also when they input an increment value that doesn't allow the list to start printing from 2 and finishes at -2 i.e. when the increment value is 0.23.

The way I thought I could do would be to use the modulus operator where if (4%increment value) = str() i.e. a whole number means that the given increment value is valid for that range. However I'm slightly stuck since when I run my code I end up in a never ending loop. Below is what I've done so far, so hoping somebody can help me out here:

def IncCheck():
    while True:
        try:     #I first check if the user inputs me a string then an error message would come up
            c = float(input("For the range -2 <= x <= 2, please input the increment you wish to display: "))
            break
        except ValueError:
            print("Invalid input. The increment has to be a number.")
    while 4%c != int():    #Here I wanna check the validity of the increment value so ideally it'd be < 4 and be a value that prints a list that starts with -2 and ends with 2.
        print("Your selected increment is not valid for -2 <= x <= 2. It should be a divisible increment of 4(the range). Please try again.")
        if c > 4:
            print("Your increment is too high. The maximum increment for the given range is 4. Please try again.")
    return c

print(IncCheck())

As you can see I've tried to create a function which checks the increment. In the end I'm looking to print the list using something like

import numpy as np
for i in np.arange(2, -2-c, -c): #c is the increment value the users input
    print i

which I can use to do other things. I need to use these x values and plot them into an arctan(x) function that I've approximated using a Taylor Series with a N value i.e. the number of iterations in the Taylor Series and compare them side by side with a real arctan(x) function basically. And then graph them. Thanks in advance.


问:
Where does ASP.Net Core `cookies authentication` store a reference to that cookie?
Sometimes I used to see PHP developers passing an Id in their cookies, and save a reference in the database to that cookie (so they can authenticate the users by cookies). But in ASP.Net Core, I have never seen that.

How and where does ASP.Net Core know that this cookie is owned by this user? Is everything stored in memory (in some kind of objects)?

In case of yes, does that mean that the users should be logged in again if I restarted my application? Or is there any method that ASP.Net Core provides to persist the references to cookies even after restarting the application?

答: The ClaimsPrincipal is serialiazed, encrypted and sent to the client as a cookie.  Once a cookie is created, it becomes the single source of identity.  When the client makes a request it sends the cookie, which the server decrypts (which serves as validation) and deserializes into the HttpContext.</p>


问:
bootstrap list group scroll
```<code><div class="panel panel-primary" id="result_panel">
    <div class="panel-heading"><h3 class="panel-title">Result List</h3>
    </div>
    <div class="panel-body">
        <ul class="list-group">
            <li class="list-group-item"><strong>Signature
                Accommodations</strong>(1480m)
            </li>
            # many li here..
            <li class="list-group-item"><strong>The Barrington At Park
                Place</strong>(15210m)
            </li>
            <li class="list-group-item"><strong>Camden Huntingdon
                Apartments</strong>(15820m)
            </li>
            <li class="list-group-item"><strong>Enclave at Water's Edge
                Apartments</strong>(15830m)
            </li>
        </ul>
    </div>
</div>
</code>```

my html looks like this. I expect many item in the list. And most time it will exceed my window,

I tried to set my css like this:

```<code>.list-group{
    margin-bottom: 10px;
    overflow:scroll;
    -webkit-overflow-scrolling: touch;
}
</code>```

but it doesn't help, any ideas?

答:
Try adding max-height:

.list-group{
    max-height: 300px;
    margin-bottom: 10px;
    overflow:scroll;
    -webkit-overflow-scrolling: touch;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="panel panel-primary" id="result_panel">
    <div class="panel-heading"><h3 class="panel-title">Result List</h3>
    </div>
    <div class="panel-body">
        <ul class="list-group">
            <li class="list-group-item"><strong>Signature
                Accommodations</strong>(1480m)
            </li>
            <li class="list-group-item"><strong>Signature
                Accommodations</strong>(1480m)
            </li>
            <li class="list-group-item"><strong>Signature
                Accommodations</strong>(1480m)
            </li>
            <li class="list-group-item"><strong>Signature
                Accommodations</strong>(1480m)
            </li>
            <li class="list-group-item"><strong>Signature
                Accommodations</strong>(1480m)
            </li>
            <li class="list-group-item"><strong>Signature
                Accommodations</strong>(1480m)
            </li>
            <li class="list-group-item"><strong>Signature
                Accommodations</strong>(1480m)
            </li>
            <li class="list-group-item"><strong>Signature
                Accommodations</strong>(1480m)
            </li>
            <li class="list-group-item"><strong>Signature
                Accommodations</strong>(1480m)
            </li>
            <li class="list-group-item"><strong>Signature
                Accommodations</strong>(1480m)
            </li>
            <li class="list-group-item"><strong>Signature
                Accommodations</strong>(1480m)
            </li>
            <li class="list-group-item"><strong>Signature
                Accommodations</strong>(1480m)
            </li>
            <li class="list-group-item"><strong>Signature
                Accommodations</strong>(1480m)
            </li>
            <li class="list-group-item"><strong>Signature
                Accommodations</strong>(1480m)
            </li>
        </ul>
    </div>
</div></code>```

Title: bootstrap list group scroll

Body:
Result List

Signature
                Accommodations(1480m)

            # many li here..

The Barrington At Park
                Place(15210m)

Camden Huntingdon
                Apartments(15820m)

Enclave at Water's Edge
                Apartments(15830m)

my html looks like this. I expect many item in the list. And most time it will exceed my window,

I tried to set my css like this:

.list-group{
    margin-bottom: 10px;
    overflow:scroll;
    -webkit-overflow-scrolling: touch;
}

but it doesn't help, any ideas?

Body:
Try adding max-height:

.list-group{
    max-height: 300px;
    margin-bottom: 10px;
    overflow:scroll;
    -webkit-overflow-scrolling: touch;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="panel panel-primary" id="result_panel">
    <div class="panel-heading"><h3 class="panel-title">Result List</h3>
    </div>
    <div class="panel-body">
        <ul class="list-group">
            <li class="list-group-item"><strong>Signature
                Accommodations</strong>(1480m)
            </li>
            <li class="list-group-item"><strong>Signature
                Accommodations</strong>(1480m)
            </li>
            <li class="list-group-item"><strong>Signature
                Accommodations</strong>(1480m)
            </li>
            <li class="list-group-item"><strong>Signature
                Accommodations</strong>(1480m)
            </li>
            <li class="list-group-item"><strong>Signature
                Accommodations</strong>(1480m)
            </li>
            <li class="list-group-item"><strong>Signature
                Accommodations</strong>(1480m)
            </li>
            <li class="list-group-item"><strong>Signature
                Accommodations</strong>(1480m)
            </li>
            <li class="list-group-item"><strong>Signature
                Accommodations</strong>(1480m)
            </li>
            <li class="list-group-item"><strong>Signature
                Accommodations</strong>(1480m)
            </li>
            <li class="list-group-item"><strong>Signature
                Accommodations</strong>(1480m)
            </li>
            <li class="list-group-item"><strong>Signature
                Accommodations</strong>(1480m)
            </li>
            <li class="list-group-item"><strong>Signature
                Accommodations</strong>(1480m)
            </li>
            <li class="list-group-item"><strong>Signature
                Accommodations</strong>(1480m)
            </li>
            <li class="list-group-item"><strong>Signature
                Accommodations</strong>(1480m)
            </li>
        </ul>
    </div>
</div>


问:
Is there a Telnet library for JavaScript?
We have a network camera.  It has an HTTP server to provides the current image.  There is also a Telnet interface for controlling the camera (i.e. trigger, focus, etc.).  I would like to add an HTML page to the camera that would provide a simple interface (we already have client software we write).  I can "GET" the image and display that, but I would also like to have controls that use the Telnet interface to control the camera.  So a button might have JavaScript code behind it that connects to the camera via Telnet (logs in) and issues the command to trigger the camera.

I know that JavaScript/browsers support connecting to the same host via XMLHttpRequest.  In this case I would be looking to open a socket on port 23 and send text.  I also know that I can do this through Flash, Java, or some other technology, but I would prefer to use JavaScript only.  If that is possible.

答:
Currently there is no way to do socket connections with JavaScript only.

But what you are searching for is a socket connection ;)

https://developer.mozilla.org/en/XML_Extras


问:
WooCommerce Order Status & reduce Stock
i write a payment gateway for woocommerce and i change the order status after payment is success. If status change to processing i reduce the order stock. Everything goes well.

By the way in the plugin settings the admin can change the status for success payments... processing or completed (for physical or virtual products)

```<code>    function setOrderPaid($OrderID, $status){
        $order = new WC_Order($OrderID);
        if(!$order){
            return false;
            }else{
                    $order->update_status($status);
                    if($status=="processing") $order->reduce_order_stock();
                    WC()->cart->empty_cart();
                    return true;
                }
    }
</code>```

After a success payment with changing the order status to processing, i go and change the status manual to completed (backoffice woocommerce->orders) and the system reduce the order stock again.

I have to reduce the stock after the success payment, to prevent problems with other orders on the same product. How can i fix this order reduce problem?

I find this Woocommerce set_status. Maybe this helps... bool $manual_update is this a manual order status change? So the system knows that stock is already reduced???

答:
This has to do with what are considered as paid order statuses in woocommerce. You can customize the list of paid order statuses. The above function will trigger each time the order enters any of those paid order statuses.

Now, your first instinct would be to truncate the paid status list. This may be advisable in a few cases, but in this particular case the instinct is wrong.

What you need to do instead is check the current order status. If the status is not a paid status, only then you should trigger the reduce stock function. This assumes that the order won't jump between a paid and unpaid status repeatedly.

Title: WooCommerce Order Status & reduce Stock

Body:
i write a payment gateway for woocommerce and i change the order status after payment is success. If status change to processing i reduce the order stock. Everything goes well.

By the way in the plugin settings the admin can change the status for success payments... processing or completed (for physical or virtual products)

    function setOrderPaid($OrderID, $status){
        $order = new WC_Order($OrderID);
        if(!$order){
            return false;
            }else{
                    $order->update_status($status);
                    if($status=="processing") $order->reduce_order_stock();
                    WC()->cart->empty_cart();
                    return true;
                }
    }

After a success payment with changing the order status to processing, i go and change the status manual to completed (backoffice woocommerce->orders) and the system reduce the order stock again.

I have to reduce the stock after the success payment, to prevent problems with other orders on the same product. How can i fix this order reduce problem?

I find this Woocommerce set_status. Maybe this helps... bool $manual_update is this a manual order status change? So the system knows that stock is already reduced???


问:
Optimal approach for detecting leaf like shapes in opencv
I started to play around with OpenCV for a project I am working on.

For this project I am growing  plants in pots. Static pictures of different developmental stages are taken from above (see figure below).

The goal is to detect and ultimately measure (i.e. size) the leaves of the growing plants during different developmental stages.

I tried a naive approach of using Canny edge detecting, however it doesn't work that well (see figure below) because it also detects small edges in the soil (no matter what kind of threshold I used).

I think the better approach is to first segment the image by color and then use some edge detection algorithm to detect the leaves.

Is there a better way to do it?

The leaf structure is known beforehand. Could I use machine learning/classification algorithm to obtain even better results?

I also haven't thought about how to measure the size of the leaves? Are there any common patterns for measuring size and other descriptors? (maybe have a reference object with known size in the picture?).

Finally I also have to deal with occlusion to some extend. This is not visible in the pictures but in later development stages I might have to deal with overlapping leaves.
Are there any approaches to deal with that?

I can't bias the picture in my favor (i.e. blacking out the soil, etc) as there might be thousands of plants which have to be processed.

To summarize my questions:

What's the best approach to detect leafs in a soil (see figures) ?

Can Machine learning algorithm improve detection?

How can I measure the size of the leaves?

How to deal with occlusion/overlapping leaves?

I would be really thankful for some pointers or ideas.

Update (based on Jeff7 comments):

I first ran the mean shift color segmentation together with a floodfill algorithm and ended up with this picture:

When I now run the canny edge detection + findcontours on the that picture the results are much better:

答:
PlantCV points out that the more you control your setup, the less work you have to do in the software.

If you control your seeding position (rather than just scattering them over the tray), you can mask out around the seedlings and get rid of background clutter.  This is also a significant help for working with individual plants, and finding the same plant in different images.  Overlapping plants will make for an impossible situation, either when you scatter seed and the sprout next to each other, or when they exceed the size of your spacing.  You have to decide if you are planting for the best observations, or optimal growth.  The two are not mutually compatible.
In my experience, you are correct to use color (cv2.inRange)as the main step, then move on to Canny edge detection.  From there, you can get contours.
I am guessing you are using Arabadopsis, so you might look for a circular pattern to count leaves (doesn't work with lettuce).  Once you have separated your plants and have (outer) contours, you can then use cv2.contourArea and cv2.minAreaRectangle to get some basic metrics.
This is the route I am working.


问:
Stuck into a Notice: Undefined variable: c
I have this index.php file

```<code># Loading configurations.
loadConfiguration('database');
loadConfiguration('site');

# Initializing the database connection.
$db = new database($c['db']['host'], $c['db']['username'], $c['db']['password'], $c['db']['name']);
unset($c['db']['password']);
</code>```

And loadConfiguration() is set as follow:

```<code>function loadConfiguration($string) { require(path.'config/'.$string.'.con.php'); }
</code>```

I checked that database.con.php and site.con.php are into the config/ folder.
And the only error i get is a Notice: Undefined variable: c in the following line

```<code>$db = new database($c['db']['host'], $c['db']['username'], $c['db']['password'], $c['db']['name']);
</code>```

Here's the database.con.php

```<code># Ignore.
if (!defined('APP_ON')) { die('Feel the rain...'); }

$c['db']['host'] = 'localhost';
$c['db']['username'] = 'root';
$c['db']['password'] = '';
$c['db']['name'] = 'name';
</code>```

Here's the site.con.php

```<code># Ignore.
if (!defined('APP_ON')) { die('Feel the rain...'); }

/* Site informations */
$c['site']['name'] = 'Namek';
$c['site']['mail'] = 'mail@whocares.com';
$c['site']['enable-email'] = false;
$c['site']['debug-mode'] = true;
</code>```

What am i doing wrong?

答: Please don't use global variable according security purpose. you can set your variable in registry variable and then access it.</p>

Body:
I have this index.php file

# Loading configurations.
loadConfiguration('database');
loadConfiguration('site');

# Initializing the database connection.
$db = new database($c['db']['host'], $c['db']['username'], $c['db']['password'], $c['db']['name']);
unset($c['db']['password']);

And loadConfiguration() is set as follow:

function loadConfiguration($string) { require(path.'config/'.$string.'.con.php'); }

I checked that database.con.php and site.con.php are into the config/ folder.
And the only error i get is a Notice: Undefined variable: c in the following line

$db = new database($c['db']['host'], $c['db']['username'], $c['db']['password'], $c['db']['name']);

Here's the database.con.php

# Ignore.
if (!defined('APP_ON')) { die('Feel the rain...'); }

$c['db']['host'] = 'localhost';
$c['db']['username'] = 'root';
$c['db']['password'] = '';
$c['db']['name'] = 'name';

Here's the site.con.php

# Ignore.
if (!defined('APP_ON')) { die('Feel the rain...'); }

/* Site informations */
$c['site']['name'] = 'Namek';
$c['site']['mail'] = 'mail@whocares.com';
$c['site']['enable-email'] = false;
$c['site']['debug-mode'] = true;

What am i doing wrong?


问:
target class inside the current selected class
I'm researching about CSS3 flipping-card layouts. There's a lot of samples in CodePen but they include unnecessary clutter. I've managed to get the 'bare-bones' version, but I can't target the specific card. I thought of adding ids but selecting them in JS would require some string manipulation, and I think this is overkill and there's a simpler way that I'm missing.

This line is the problem:
$('.card_container>.card').toggleClass('flipped'); I want to say "select .card under this current .card_container that I'm clicking".

Codepen: https://codepen.io/reiallenramos/pen/bYWKyv

```<code>$('.card_container').on('click', function () {
  $('.card_container>.card').toggleClass('flipped'); #help me change this line
});
</code>```

--

```<code>body, html {
  margin: 0;
  background-color: tomato;
  font-size: 2em;
  font-family: sans-serif;
}

.wrapper{
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: minmax(100px, auto);
  grid-gap: 2px;
  margin: 10px;
  height: 100vh;
  align-items: center;
}

.card_container {
  cursor: pointer;
  position: relative;
  width: 300px;
  height: 200px;
}

.card {
  transform-style: preserve-3d;
  transition: transform 0.8s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  padding: 0px;
  position: absolute;
  height: 100%;
  width: 100%;
  div {
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    backface-visibility: hidden;
    background-color: #eee;
    height: 100%;
    width: 100%;
  }

  .back {
    transform: rotateY(180deg);
  }

  &.flipped{
    transform: rotateY(180deg);
  }
}
</code>```

--

```<code><div class="wrapper">
  <div class="card_container">
    <div class="card">
      <div class="front">flip</div>
      <div class="back">one</div>
    </div>
  </div>
  <div class="card_container">
    <div class="card">
      <div class="front">flip</div>
      <div class="back">two</div>
    </div>
  </div>
  <div class="card_container">
    <div class="card">
      <div class="front">flip</div>
      <div class="back">three</div>
    </div>
  </div>
  <div class="card_container">
    <div class="card">
      <div class="front">flip</div>
      <div class="back">four</div>
    </div>
  </div>
</div>
</code>```

答:
Add this changes into your jQuery codes, every-time when you click .card, jQuery this keyword toggles class on that clicked element and not on all .card.

```<code>$('.card_container > .card').on('click', function () {
  $(this).toggleClass('flipped');
});
</code>```

$('.card_container > .card').on('click', function () {
  $(this).toggleClass('flipped');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body, html {
  margin: 0;
  background-color: tomato;
  font-size: 2em;
  font-family: sans-serif;
}

.wrapper{
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: minmax(100px, auto);
  grid-gap: 2px;
  margin: 10px;
  height: 100vh;
  align-items: center;
}

.card_container {
  cursor: pointer;
  position: relative;
  width: 300px;
  height: 200px;
}

.card {
  transform-style: preserve-3d;
  transition: transform 0.8s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  padding: 0px;
  position: absolute;
  height: 100%;
  width: 100%;
  div {
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    backface-visibility: hidden;
    background-color: #eee;
    height: 100%;
    width: 100%;
  }

  .back {
    transform: rotateY(180deg);
  }

  &.flipped{
    transform: rotateY(180deg);
  }
}</code>```

flip

one

flip

two

flip

three

flip

four

```

Body:
I'm researching about CSS3 flipping-card layouts. There's a lot of samples in CodePen but they include unnecessary clutter. I've managed to get the 'bare-bones' version, but I can't target the specific card. I thought of adding ids but selecting them in JS would require some string manipulation, and I think this is overkill and there's a simpler way that I'm missing.

This line is the problem:
$('.card_container>.card').toggleClass('flipped'); I want to say "select .card under this current .card_container that I'm clicking".

Codepen: https://codepen.io/reiallenramos/pen/bYWKyv

$('.card_container').on('click', function () {
  $('.card_container>.card').toggleClass('flipped'); #help me change this line
});

--

body, html {
  margin: 0;
  background-color: tomato;
  font-size: 2em;
  font-family: sans-serif;
}

.wrapper{
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: minmax(100px, auto);
  grid-gap: 2px;
  margin: 10px;
  height: 100vh;
  align-items: center;
}

.card_container {
  cursor: pointer;
  position: relative;
  width: 300px;
  height: 200px;
}

.card {
  transform-style: preserve-3d;
  transition: transform 0.8s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  padding: 0px;
  position: absolute;
  height: 100%;
  width: 100%;
  div {
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    backface-visibility: hidden;
    background-color: #eee;
    height: 100%;
    width: 100%;
  }

  .back {
    transform: rotateY(180deg);
  }

  &.flipped{
    transform: rotateY(180deg);
  }
}

--

flip

one

flip

two

flip

three

flip

four

Body:
Add this changes into your jQuery codes, every-time when you click .card, jQuery this keyword toggles class on that clicked element and not on all .card.

$('.card_container > .card').on('click', function () {
  $(this).toggleClass('flipped');
});

$('.card_container > .card').on('click', function () {
  $(this).toggleClass('flipped');
});

body, html {
  margin: 0;
  background-color: tomato;
  font-size: 2em;
  font-family: sans-serif;
}

.wrapper{
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: minmax(100px, auto);
  grid-gap: 2px;
  margin: 10px;
  height: 100vh;
  align-items: center;
}

.card_container {
  cursor: pointer;
  position: relative;
  width: 300px;
  height: 200px;
}

.card {
  transform-style: preserve-3d;
  transition: transform 0.8s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  padding: 0px;
  position: absolute;
  height: 100%;
  width: 100%;
  div {
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    backface-visibility: hidden;
    background-color: #eee;
    height: 100%;
    width: 100%;
  }

  .back {
    transform: rotateY(180deg);
  }

  &.flipped{
    transform: rotateY(180deg);
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="card_container">
    <div class="card">
      <div class="front">flip</div>
      <div class="back">one</div>
    </div>
  </div>
  <div class="card_container">
    <div class="card">
      <div class="front">flip</div>
      <div class="back">two</div>
    </div>
  </div>
  <div class="card_container">
    <div class="card">
      <div class="front">flip</div>
      <div class="back">three</div>
    </div>
  </div>
  <div class="card_container">
    <div class="card">
      <div class="front">flip</div>
      <div class="back">four</div>
    </div>
  </div>
</div>


问:
Access a amazon s3 bucket subfolder using python
I am trying to access a bucket subfolder using python's boto3.

The problem is that I cannot find anywhere how to input the subfolder information inside the boto code.

All I find is how to put the bucket name, but I do not have access to the whole bucket, just to a specific subfolder. Can anyone give me a light?

What I did so far:

```<code> BUCKET = "folder/subfolder"
 conn = S3Connection(AWS_KEY, AWS_SECRET)
 bucket = conn.get_bucket(BUCKET)
 for key in bucket.list():
     print key.name.encode('utf-8')
</code>```

The error messages:

```<code>botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the ListBuckets operation: Access Denied
</code>```

I do not need to use boto for the operation, I just need to list/get the files inside this subfolder.

P.S.: I can access the files using cyberduck by putting the path folder/subfolder, which means I have access to the date.

Sincerely,

Israel

答:
I fixed the problem using something similar vtl suggested:

I had to put the prefix in my bucket and a delimiter. The final code was something like this:

```<code>objects = s3.list_objects(Bucket=bucketName, Prefix=bucketPath+'/', Delimiter='/')
</code>```

As he said, there's not folder structure, then you have to state a delimiter and also put it after the Prefix like I did.

Thanks for the reply.

Body:
I am trying to access a bucket subfolder using python's boto3.

The problem is that I cannot find anywhere how to input the subfolder information inside the boto code.

All I find is how to put the bucket name, but I do not have access to the whole bucket, just to a specific subfolder. Can anyone give me a light?

What I did so far:

 BUCKET = "folder/subfolder"
 conn = S3Connection(AWS_KEY, AWS_SECRET)
 bucket = conn.get_bucket(BUCKET)
 for key in bucket.list():
     print key.name.encode('utf-8')

The error messages:

botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the ListBuckets operation: Access Denied

I do not need to use boto for the operation, I just need to list/get the files inside this subfolder.

P.S.: I can access the files using cyberduck by putting the path folder/subfolder, which means I have access to the date.

Sincerely,

Israel

Body:
I fixed the problem using something similar vtl suggested:

I had to put the prefix in my bucket and a delimiter. The final code was something like this:

objects = s3.list_objects(Bucket=bucketName, Prefix=bucketPath+'/', Delimiter='/')

As he said, there's not folder structure, then you have to state a delimiter and also put it after the Prefix like I did.

Thanks for the reply.


问:
How to delete files recursively from an S3 bucket
I have the following folder structure in S3. Is there a way to recursively remove all files under a certain folder (say foo/bar1 or foo or foo/bar2/1 ..)

```<code>foo/bar1/1/..
foo/bar1/2/..
foo/bar1/3/..

foo/bar2/1/..
foo/bar2/2/..
foo/bar2/3/..
</code>```

答:
In case if you want to remove all objects with "foo/" prefix using Java AWS SDK 2.0</p>

```<code>import java.util.ArrayList;
import java.util.Iterator;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.*;

//...

ListObjectsRequest listObjectsRequest = ListObjectsRequest.builder()
    .bucket(bucketName)
    .prefix("foo/")
    .build()
;
ListObjectsResponse objectsResponse = s3Client.listObjects(listObjectsRequest);

while (true) {
    ArrayList<ObjectIdentifier> objects = new ArrayList<>();

    for (Iterator<?> iterator = objectsResponse.contents().iterator(); iterator.hasNext(); ) {
        S3Object s3Object = (S3Object)iterator.next();
        objects.add(
            ObjectIdentifier.builder()
                .key(s3Object.key())
                .build()
        );
    }

    s3Client.deleteObjects(
        DeleteObjectsRequest.builder()
            .bucket(bucketName)
            .delete(
                Delete.builder()
                    .objects(objects)
                    .build()
            )
            .build()
    );

    if (objectsResponse.isTruncated()) {
        objectsResponse = s3Client.listObjects(listObjectsRequest);
        continue;
    }

    break;
};
</code>```

Body:
I have the following folder structure in S3. Is there a way to recursively remove all files under a certain folder (say foo/bar1 or foo or foo/bar2/1 ..)

foo/bar1/1/..
foo/bar1/2/..
foo/bar1/3/..

foo/bar2/1/..
foo/bar2/2/..
foo/bar2/3/..

Body:
In case if you want to remove all objects with "foo/" prefix using Java AWS SDK 2.0

import java.util.ArrayList;
import java.util.Iterator;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.*;

//...

ListObjectsRequest listObjectsRequest = ListObjectsRequest.builder()
    .bucket(bucketName)
    .prefix("foo/")
    .build()
;
ListObjectsResponse objectsResponse = s3Client.listObjects(listObjectsRequest);

while (true) {
    ArrayList<ObjectIdentifier> objects = new ArrayList<>();

    for (Iterator<?> iterator = objectsResponse.contents().iterator(); iterator.hasNext(); ) {
        S3Object s3Object = (S3Object)iterator.next();
        objects.add(
            ObjectIdentifier.builder()
                .key(s3Object.key())
                .build()
        );
    }

    s3Client.deleteObjects(
        DeleteObjectsRequest.builder()
            .bucket(bucketName)
            .delete(
                Delete.builder()
                    .objects(objects)
                    .build()
            )
            .build()
    );

    if (objectsResponse.isTruncated()) {
        objectsResponse = s3Client.listObjects(listObjectsRequest);
        continue;
    }

    break;
};


问:
Selenium Webdriver java : unable to click on OK button (span tag in button tag)
HTML code:

```<code><div id="sieb-ui-popup-mvg-selected" class="AppletStylePopup">
    <form onsubmit="return false;" action="/ecom_enu/start.swe" method="post" name="SWEForm4_0">
        <div class="siebui-popup-btm siebui-mvg-btn-modifier">
            <span class="siebui-popup-button">
                <button id="s_4_1_79_0_Ctrl" class="siebui-ctrl-btn siebui-icon-closeapplet s_4_1_79_0 appletButton" aria-label="Responsibilities:OK" title="Responsibilities:OK" tabindex="0" data-display="OK" name="s_4_1_79_0" type="button">
                    <span>OK</span>
                </button>
            </span>
        </div>
    </form>
</div>
</code>```

I want to click on the OK button. Please help, Thanks!

I have tried with the below, but it does not work.

```<code>driver.findElement(By.cssSelector(".siebui-ctrl-btn.siebui-icon-closeapplet.appletButton")).click();
</code>```

Also tried likethis, it does not work.

```<code>driver.findElement(By.xpath(".//*button[@title='Responsibilities:OK']/span[contains(text(),'OK]")).click();
</code>```

Also tried the below, it does not work.

```<code>driver.findElement(By.xpath("//button[contains(span/text(), 'OK')]")).click();
</code>```

Also tried the below, it does not work. Timeout error occurred

```<code>WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("iframe-applicationname_ModalDialog_0"));
WebElement el = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//span[contains(text(), 'OK')]")));
el.click();
driver.switchTo().defaultContent();
</code>```

答:
Can you please try with below ways -

First get the root element and keep it to a WebElement object. Then find the Ok button element and a click.

```<code>WebElement elem = driver.findElement(By.cssSelector("#sieb-ui-popup-mvg-selected > form > div"));
makeWait(5);  //Set any value you need for wait until appearing Ok Button
elem.findElement(By.cssSelector("button[type='button']")).click();
</code>```

Create another local or global method for wait some moments

```<code>/*
 * make some wait the execution
 */
public void makeWait(int waitForSecond)
{
    try {
        //Thread.sleep(1000 * waitForSecond);
        Thread.currentThread().sleep(1000 * waitForSecond);
    } catch (InterruptedException ie) {
        System.out.println(ie.getMessage());
    }
}
</code>```

You can also try removing the makeWait() if you don't need. Probably It may be helpful.

Body:
HTML code:

    <form onsubmit="return false;" action="/ecom_enu/start.swe" method="post" name="SWEForm4_0">

                <button id="s_4_1_79_0_Ctrl" class="siebui-ctrl-btn siebui-icon-closeapplet s_4_1_79_0 appletButton" aria-label="Responsibilities:OK" title="Responsibilities:OK" tabindex="0" data-display="OK" name="s_4_1_79_0" type="button">
                    OK
                </button>

    </form>

I want to click on the OK button. Please help, Thanks!

I have tried with the below, but it does not work.

driver.findElement(By.cssSelector(".siebui-ctrl-btn.siebui-icon-closeapplet.appletButton")).click();

Also tried likethis, it does not work.

driver.findElement(By.xpath(".//*button[@title='Responsibilities:OK']/span[contains(text(),'OK]")).click();

Also tried the below, it does not work.

driver.findElement(By.xpath("//button[contains(span/text(), 'OK')]")).click();

Also tried the below, it does not work. Timeout error occurred

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("iframe-applicationname_ModalDialog_0"));
WebElement el = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//span[contains(text(), 'OK')]")));
el.click();
driver.switchTo().defaultContent();

Body:
Can you please try with below ways -

First get the root element and keep it to a WebElement object. Then find the Ok button element and a click.

WebElement elem = driver.findElement(By.cssSelector("#sieb-ui-popup-mvg-selected > form > div"));
makeWait(5);  //Set any value you need for wait until appearing Ok Button
elem.findElement(By.cssSelector("button[type='button']")).click();

Create another local or global method for wait some moments

/*
 * make some wait the execution
 */
public void makeWait(int waitForSecond)
{
    try {
        //Thread.sleep(1000 * waitForSecond);
        Thread.currentThread().sleep(1000 * waitForSecond);
    } catch (InterruptedException ie) {
        System.out.println(ie.getMessage());
    }
}

You can also try removing the makeWait() if you don't need. Probably It may be helpful.