问:
VB.NET Function Return
In order to return a value from a VB.NET function one can assign a value to the "Functions Name" or use "return value."

I sometimes see these inter-mixed in the same function.  Personally, I prefer the return.

My question is, what is the internal difference, if any, between the two?

答:
When Tools/Options/Text Editor/All Languages/Code Lens is activated, the Reference Count shows above each Sub, Function, or Property statement.

"Return Value" seems better than "assigning a value to the Functions Name".  In the latter case, "Code Lens" produces an inflated Reference Count.

```<code>' Code Lens reports "0 references" here for Sub Rosa().
Public Sub Rosa()
    Diagnostics.Debug.WriteLine(Test())
    Diagnostics.Debug.WriteLine(Test2())
End Sub

' Code Lens reports "2 references" here for Function Test().
Public Function Test() As String
    Test = "Test"       ' Code Lens counts this as a reference.
End Function

' Code Lens reports "1 reference" here for Function Test2().
Public Function Test2() As String
    Dim strTest2 as String = "Test"
    Return strTest2     ' Code Lens does NOT count this as a reference.
End Function
</code>```

ContentLicense: CC BY-SA 2.5

Title: VB.NET Function Return

Body:
When Tools/Options/Text Editor/All Languages/Code Lens is activated, the Reference Count shows above each Sub, Function, or Property statement.

"Return Value" seems better than "assigning a value to the Functions Name".  In the latter case, "Code Lens" produces an inflated Reference Count.

' Code Lens reports "0 references" here for Sub Rosa().
Public Sub Rosa()
    Diagnostics.Debug.WriteLine(Test())
    Diagnostics.Debug.WriteLine(Test2())
End Sub

' Code Lens reports "2 references" here for Function Test().
Public Function Test() As String
    Test = "Test"       ' Code Lens counts this as a reference.
End Function

' Code Lens reports "1 reference" here for Function Test2().
Public Function Test2() As String
    Dim strTest2 as String = "Test"
    Return strTest2     ' Code Lens does NOT count this as a reference.
End Function


来源: stackexchange

问:
Copy multiple files from one folder to another
I am trying to copy multiple files from one folder to another using the following code

```<code>val pathCorpus = Files.copy(
  Paths.get("src/main/resources/corpusDirectory/corpus.mallet"),
  Paths.get("src/main/resources/corpus.mallet"),
  StandardCopyOption.REPLACE_EXISTING
)

val pathInferencer = Files.copy(
  Paths.get("src/main/resources/corpusDirectory/inferencer"),
  Paths.get("src/main/resources/inferencer"),
  StandardCopyOption.REPLACE_EXISTING
)
</code>```

As I need to copy two files, I am using Files.copy twice.
The code is working but I believe there should be better way to write the code, like copying files recursively.

答:
better-files supports recursively copying directories via source.copyTo(destination) syntax. Here is a working example

```<code>import better.files._

object Hello extends App {
  val source = file"/your/sourceDir"
  val destination = file"/your/destinationDir"
  source.copyTo(destination)
}
</code>```

where we need the following dependency

```<code>libraryDependencies += "com.github.pathikrit" %% "better-files" % "3.8.0"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to copy multiple files from one folder to another using the following code

val pathCorpus = Files.copy(
  Paths.get("src/main/resources/corpusDirectory/corpus.mallet"),
  Paths.get("src/main/resources/corpus.mallet"),
  StandardCopyOption.REPLACE_EXISTING
)

val pathInferencer = Files.copy(
  Paths.get("src/main/resources/corpusDirectory/inferencer"),
  Paths.get("src/main/resources/inferencer"),
  StandardCopyOption.REPLACE_EXISTING
)

As I need to copy two files, I am using Files.copy twice.
The code is working but I believe there should be better way to write the code, like copying files recursively.

Body:
better-files supports recursively copying directories via source.copyTo(destination) syntax. Here is a working example

import better.files._

object Hello extends App {
  val source = file"/your/sourceDir"
  val destination = file"/your/destinationDir"
  source.copyTo(destination)
}

where we need the following dependency

libraryDependencies += "com.github.pathikrit" %% "better-files" % "3.8.0"


问:
Initialize an std::array algorithmically at compile time
Consider:

```<code>static constexpr unsigned num_points{ 7810 };
std::array< double, num_points > axis;

for (int i = 0; i < num_points; ++i)
{
    axis[i] = 180 + 0.1 * i;
}
</code>```

axis is a class-wide constant. I want to avoid initializing it like any other global variable. Can it be done at compile time?

This is the final class in its entirety:

```<code>// https://www.nist.gov/pml/atomic-spectroscopy-compendium-basic-ideas-notation-data-and-formulas/atomic-spectroscopy
// https://www.nist.gov/pml/atomic-spectra-database
struct Spectrum
{
    static constexpr unsigned _num_points{ 7810 };
    using Axis = std::array< double, _num_points >;

    static constexpr Axis _x{ [] ()            // wavelength, nm
        {
            Axis a {};
            for( unsigned i = 0; i < _num_points; ++i )
            {
                a[ i ] = 180 + 0.1 * i;
            }
            return a;
        } () };
    Axis _y {};                                // radiance, W·sr−1·m−2
};
</code>```

The mixing of code and variables is unsightly, but at least the formula is right in front of the reader's eyes. Any other solution involved a lot of typing in order to get the in-class defined constant and type.

Or if I change my heart, I can simply return the lambda at runtime.

答:
For completeness' sake, here's a version that does not require the definition of a function but instead uses a lambda. C++17 introduced the ability of using lambdas in constant expressions, so you can declare your array constexpr and use a lambda to initialize it:

```<code>static constexpr auto axis = [] {
    std::array<double, num_points> a{};
    for (int i = 0; i < num_points; ++i) {
        a[i] = 180 + 0.1 * i;
    }
    return a;
}();
</code>```

(Note the () in the last line, which calls the lambda right away.)

If you don't like the auto in the axis declaration because it makes it harder to read the actual type, but you don't want to repeat the type inside the lambda, you can instead do:

```<code>static constexpr std::array<double, num_points> axis = [] {
    auto a = decltype(axis){};
    for (int i = 0; i < num_points; ++i) {
        a[i] = 180 + 0.1 * i;
    }
    return a;
}();
</code>```

Body:
Consider:

static constexpr unsigned num_points{ 7810 };
std::array< double, num_points > axis;

for (int i = 0; i < num_points; ++i)
{
    axis[i] = 180 + 0.1 * i;
}

axis is a class-wide constant. I want to avoid initializing it like any other global variable. Can it be done at compile time?

This is the final class in its entirety:

// https://www.nist.gov/pml/atomic-spectroscopy-compendium-basic-ideas-notation-data-and-formulas/atomic-spectroscopy
// https://www.nist.gov/pml/atomic-spectra-database
struct Spectrum
{
    static constexpr unsigned _num_points{ 7810 };
    using Axis = std::array< double, _num_points >;

    static constexpr Axis _x{ [] ()            // wavelength, nm
        {
            Axis a {};
            for( unsigned i = 0; i < _num_points; ++i )
            {
                a[ i ] = 180 + 0.1 * i;
            }
            return a;
        } () };
    Axis _y {};                                // radiance, W·sr−1·m−2
};

The mixing of code and variables is unsightly, but at least the formula is right in front of the reader's eyes. Any other solution involved a lot of typing in order to get the in-class defined constant and type.

Or if I change my heart, I can simply return the lambda at runtime.

Body:
For completeness' sake, here's a version that does not require the definition of a function but instead uses a lambda. C++17 introduced the ability of using lambdas in constant expressions, so you can declare your array constexpr and use a lambda to initialize it:

static constexpr auto axis = [] {
    std::array<double, num_points> a{};
    for (int i = 0; i < num_points; ++i) {
        a[i] = 180 + 0.1 * i;
    }
    return a;
}();

(Note the () in the last line, which calls the lambda right away.)

If you don't like the auto in the axis declaration because it makes it harder to read the actual type, but you don't want to repeat the type inside the lambda, you can instead do:

static constexpr std::array<double, num_points> axis = [] {
    auto a = decltype(axis){};
    for (int i = 0; i < num_points; ++i) {
        a[i] = 180 + 0.1 * i;
    }
    return a;
}();


问:
make/Makefile: CLI option to "disable" a dependency from a target
I'm exploring a feature of some software that's used in a very mature Makefile to see if that feature can be incorporated into the flow. There is a target like the following:

```<code>my_target: dependency_1 dependency_2
        echo foo
        touch bar
        # etc...
</code>```

In regular use, dependency_2 would always be called before my_target's commands were executed. But for my exploration purposes, I want to selectively call dependency_2 from its own make command. And then make my_target after, possibly several times, without re-doing dependency_2 each time.

For the time being I just copy/pasted my_target into my_target_2 and removed the dependency from my_target_2 (easy enough), but I'm wondering if there's a command-line option to disable a target's dependency without modifying the file.

EDIT: dependency_2 is a PHONY target

答:
But for my exploration purposes, I want to selectively call dependency_2 from its own make command

This is done as easy as make dependency_2

And then make my_target after, possibly several times, without re-doing dependency_2 each time

Normally, dependency_2 should be a file on the disk, so make would skip rebuilding it until its own prerequisites (source files) are changed.

But if dependency_2 is a .PHONY target ("fake file"), it will be rebuilt on each run. In this case you still can fool it like this:

```<code>echo "dependency_2:;@:" | make -f Makefile -f -
</code>```

However, make will issue a warning about overriding a recipe for dependency_2.

Body:
I'm exploring a feature of some software that's used in a very mature Makefile to see if that feature can be incorporated into the flow. There is a target like the following:

my_target: dependency_1 dependency_2
        echo foo
        touch bar
        # etc...

In regular use, dependency_2 would always be called before my_target's commands were executed. But for my exploration purposes, I want to selectively call dependency_2 from its own make command. And then make my_target after, possibly several times, without re-doing dependency_2 each time.

For the time being I just copy/pasted my_target into my_target_2 and removed the dependency from my_target_2 (easy enough), but I'm wondering if there's a command-line option to disable a target's dependency without modifying the file.

EDIT: dependency_2 is a PHONY target

Body:
But for my exploration purposes, I want to selectively call dependency_2 from its own make command

This is done as easy as make dependency_2

And then make my_target after, possibly several times, without re-doing dependency_2 each time

Normally, dependency_2 should be a file on the disk, so make would skip rebuilding it until its own prerequisites (source files) are changed.

But if dependency_2 is a .PHONY target ("fake file"), it will be rebuilt on each run. In this case you still can fool it like this:

echo "dependency_2:;@:" | make -f Makefile -f -

However, make will issue a warning about overriding a recipe for dependency_2.


问:
Resolving PyCharm python error - dyld: Library not loaded
I am using PyCharm 2018.3.2 Community Edition, under macOS Sierra V. 10.12.6

Today I found the following error message in Python-Console:

```<code>dyld: Library not loaded: /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/Python
  Referenced from: /Users/tleis/PycharmProjects/BioInformaticsI/venv/bin/python
  Reason: image not found
</code>```

After some research, I doubt the reason is due to some commands I run related to HomeBrew.

答:
The error message smells like you've probably updated your Python version, which can occasionally break virtualenvs with those symptoms. </p>

<p>The easiest fix is to just delete and recreate the virtualenv. </p>

Body:
I am using PyCharm 2018.3.2 Community Edition, under macOS Sierra V. 10.12.6

Today I found the following error message in Python-Console:

dyld: Library not loaded: /usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/Python
  Referenced from: /Users/tleis/PycharmProjects/BioInformaticsI/venv/bin/python
  Reason: image not found

After some research, I doubt the reason is due to some commands I run related to HomeBrew.

Body:
The error message smells like you've probably updated your Python version, which can occasionally break virtualenvs with those symptoms.

The easiest fix is to just delete and recreate the virtualenv.


问:
Stop jquery function fade on mouseover
i have a html code like this:

```<code><div id="principal">
    <div id="quote1"> 1 Div </div>
    <div id="quote2"> 2 Div </div>
</div>
</code>```

And the function for fadein/fadeout those "quote" div's in a loop:

```<code>  jQuery(function () {
    var $els = $('div[id^=quote]'),
        i = 0,
        len = $els.length;

        $els.slice(1).hide();
        setInterval(function () {
            $els.eq(i).fadeOut(function () {
                i = (i + 1) % len
                $els.eq(i).fadeIn();
            })
        }, 4000)
    })
</code>```

The problem is: i want to stop the fadeIn/fadeOut animation on mouseover on  "Principal" div and return the animation on mouseleave.
How can i stop the animation and freeze the actual div?

答:
You could use a class to determine when the interval should appear to hault.  By adding and removing it on hover and hover out, then the interval can check to see if the elements have the class or not.  If they have the class, skip the operation that interval.

jQuery(function() {
  var $els = $('div[id^=quote]'),
    i = 0,
    len = $els.length;

  $els.slice(1).hide();

  setInterval(function() {
    if (!$els.hasClass('pause')) {
      $els.eq(i).fadeOut(function() {
        i = (i + 1) % len
        $els.eq(i).fadeIn();
      });
    }
  }, 2000);

  $els.on('mouseenter', function() {
    $els.addClass('pause')
  });
  $els.on('mouseleave', function() {
    $els.removeClass('pause')
  });
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="principal">
  <div id="quote1"> 1 Div </div>
  <div id="quote2"> 2 Div </div>
</div></code>```

Title: Stop jquery function fade on mouseover

Body:
i have a html code like this:

 1 Div

 2 Div

And the function for fadein/fadeout those "quote" div's in a loop:

  jQuery(function () {
    var $els = $('div[id^=quote]'),
        i = 0,
        len = $els.length;

        $els.slice(1).hide();
        setInterval(function () {
            $els.eq(i).fadeOut(function () {
                i = (i + 1) % len
                $els.eq(i).fadeIn();
            })
        }, 4000)
    })

The problem is: i want to stop the fadeIn/fadeOut animation on mouseover on  "Principal" div and return the animation on mouseleave.
How can i stop the animation and freeze the actual div?

Body:
You could use a class to determine when the interval should appear to hault.  By adding and removing it on hover and hover out, then the interval can check to see if the elements have the class or not.  If they have the class, skip the operation that interval.

jQuery(function() {
  var $els = $('div[id^=quote]'),
    i = 0,
    len = $els.length;

  $els.slice(1).hide();

  setInterval(function() {
    if (!$els.hasClass('pause')) {
      $els.eq(i).fadeOut(function() {
        i = (i + 1) % len
        $els.eq(i).fadeIn();
      });
    }
  }, 2000);

  $els.on('mouseenter', function() {
    $els.addClass('pause')
  });
  $els.on('mouseleave', function() {
    $els.removeClass('pause')
  });
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="principal">
  <div id="quote1"> 1 Div </div>
  <div id="quote2"> 2 Div </div>
</div>


问:
Why does returning a string slice instead of a usize prevent mutating a String?
This code compiles:

```<code>fn main() {
    let mut s = String::from("some_string");
    let n = f1(&s);
    s.clear();
    println!("n = {}", n);
}

fn f1(s: &String) -> usize {
    10
}

fn f2(s: &String) -> &str {
    "def"
}
</code>```

However, replacing the call to f1() by f2() causes a compilation failure. It appears to me that both f1() and f2() do an immutable borrow, and s.clear() does a mutable borrow, so I should get compilation error in both cases. What am I missing?

答:
f1 and f2 both take an immutable borrow. However, the lifetime of the borrow from f1 ends at the end of f1, because you're just returning a usize and not anything from the actual string.

However, f2 returns a &str, which is borrowing your underlying String, s. Since n stays alive, the immutable borrow of s continues until n is no longer used. Effectively, this prevents your call to s.clear() from "pulling the rug out from under" your pointer s.

Body:
This code compiles:

fn main() {
    let mut s = String::from("some_string");
    let n = f1(&s);
    s.clear();
    println!("n = {}", n);
}

fn f1(s: &String) -> usize {
    10
}

fn f2(s: &String) -> &str {
    "def"
}

However, replacing the call to f1() by f2() causes a compilation failure. It appears to me that both f1() and f2() do an immutable borrow, and s.clear() does a mutable borrow, so I should get compilation error in both cases. What am I missing?


问:
Get last n lines of a file, similar to tail
I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file.  The items in the file are line based with the newest item at the bottom.

So I need a tail() method that can read n lines from the bottom and support an offset.  This is hat I came up with:

```<code>def tail(f, n, offset=0):
    """Reads a n lines from f with an offset of offset lines."""
    avg_line_length = 74
    to_read = n + offset
    while 1:
        try:
            f.seek(-(avg_line_length * to_read), 2)
        except IOError:
            # woops.  apparently file is smaller than what we want
            # to step back, go to the beginning instead
            f.seek(0)
        pos = f.tell()
        lines = f.read().splitlines()
        if len(lines) >= to_read or pos == 0:
            return lines[-to_read:offset and -offset or None]
        avg_line_length *= 1.3
</code>```

Is this a reasonable approach?  What is the recommended way to tail log files with offsets?

答:
Several of these solutions have issues if the file doesn't end in \n or in ensuring the complete first line is read.</p>

```<code>def tail(file, n=1, bs=1024):
    f = open(file)
    f.seek(-1,2)
    l = 1-f.read(1).count('\n') # If file doesn't end in \n, count it anyway.
    B = f.tell()
    while n >= l and B > 0:
            block = min(bs, B)
            B -= block
            f.seek(B, 0)
            l += f.read(block).count('\n')
    f.seek(B, 0)
    l = min(l,n) # discard first (incomplete) line if l > n
    lines = f.readlines()[-l:]
    f.close()
    return lines
</code>```

OwnerDisplayName: Armin Ronacher

Body:
I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file.  The items in the file are line based with the newest item at the bottom.

So I need a tail() method that can read n lines from the bottom and support an offset.  This is hat I came up with:

def tail(f, n, offset=0):
    """Reads a n lines from f with an offset of offset lines."""
    avg_line_length = 74
    to_read = n + offset
    while 1:
        try:
            f.seek(-(avg_line_length * to_read), 2)
        except IOError:
            # woops.  apparently file is smaller than what we want
            # to step back, go to the beginning instead
            f.seek(0)
        pos = f.tell()
        lines = f.read().splitlines()
        if len(lines) >= to_read or pos == 0:
            return lines[-to_read:offset and -offset or None]
        avg_line_length *= 1.3

Is this a reasonable approach?  What is the recommended way to tail log files with offsets?

Body:
Several of these solutions have issues if the file doesn't end in \n or in ensuring the complete first line is read.

def tail(file, n=1, bs=1024):
    f = open(file)
    f.seek(-1,2)
    l = 1-f.read(1).count('\n') # If file doesn't end in \n, count it anyway.
    B = f.tell()
    while n >= l and B > 0:
            block = min(bs, B)
            B -= block
            f.seek(B, 0)
            l += f.read(block).count('\n')
    f.seek(B, 0)
    l = min(l,n) # discard first (incomplete) line if l > n
    lines = f.readlines()[-l:]
    f.close()
    return lines

ContentLicense: CC BY-SA 3.0


问:
Can I update the a Stripe Coupon from the Dashboard?
I've created a stripe coupon, but accidentally made the "maximum redemptions" field too low of a number.  I'd like to increase it.

Selecting edit in the dashboard only allows me to edit the name, and if I try to create a new coupon of the same name, I get an ID conflict error.

I'd like to not delete the previous coupon because it has valuable information (when it was used, etc.).

How can I update the current coupon?

答: If you delete the coupon then recreate a coupon of the same id (with different data), the event log appears to remain intact, although the redemption count does drop back to zero.</p>


问:
How to handle ProgressBar while image is uploading to firebase
I am uploading image to the firebase storage. But i am not able to handle the ProgressBar in my code.

Component

```<code>onSubmit(){
      const fileRef = this.storage.ref(filepath)
      this.storage.upload(filepath,this.selectedImage).snapshotChanges().pipe(
        finalize(() => {
          fileRef.getDownloadURL().subscribe((url) => {
            this.upSvc.insertImageDetails(this.daydetails.value);
            this.toaster.success("Submitted successfully")
            this.router.navigate(['../Home'],{relativeTo:this.activatedroute})
          })
        }),
      ).subscribe()
}
</code>```

HTML

```<code><div class="progress">
   <div class="progress-bar progress-bar-animated" [ngStyle]="{ 'width': progress + '%' }"></div>
</div>
Progress: {{progress}}% Complete
</code>```

答:
this.storage.upload() returns a AngularFireUploadTask.
This task has a percentageChanges() observable that will output what you need.

So something like

```<code>
uploadProgress$: Observable<number>

onSubmit(){
      const fileRef = this.storage.ref(filepath)
      const task = this.storage.upload(filepath,this.selectedImage)

      this.uploadProgress$ = task.percentageChanges()

      task.snapshotChanges().pipe(
        finalize(() => {
          fileRef.getDownloadURL().subscribe((url) => {
            this.upSvc.insertImageDetails(this.daydetails.value);
            this.toaster.success("Submitted successfully")
            this.router.navigate(['../Home'],{relativeTo:this.activatedroute})
          })
        }),
      ).subscribe()
}
</code>```

```

Body:
I am uploading image to the firebase storage. But i am not able to handle the ProgressBar in my code.

Component

onSubmit(){
      const fileRef = this.storage.ref(filepath)
      this.storage.upload(filepath,this.selectedImage).snapshotChanges().pipe(
        finalize(() => {
          fileRef.getDownloadURL().subscribe((url) => {
            this.upSvc.insertImageDetails(this.daydetails.value);
            this.toaster.success("Submitted successfully")
            this.router.navigate(['../Home'],{relativeTo:this.activatedroute})
          })
        }),
      ).subscribe()
}

HTML

Progress: {{progress}}% Complete

Body:
this.storage.upload() returns a AngularFireUploadTask.
This task has a percentageChanges() observable that will output what you need.

So something like

uploadProgress$: Observable<number>

onSubmit(){
      const fileRef = this.storage.ref(filepath)
      const task = this.storage.upload(filepath,this.selectedImage)

      this.uploadProgress$ = task.percentageChanges()

      task.snapshotChanges().pipe(
        finalize(() => {
          fileRef.getDownloadURL().subscribe((url) => {
            this.upSvc.insertImageDetails(this.daydetails.value);
            this.toaster.success("Submitted successfully")
            this.router.navigate(['../Home'],{relativeTo:this.activatedroute})
          })
        }),
      ).subscribe()
}

<div class="progress" *ngIf="uploadProgress$ | async as progress">
   <div class="progress-bar progress-bar-animated" [ngStyle]="{ 'width': progress + '%' }"></div>
</div>


问:
Intersect between two lists not working
I have two lists see below.....result is coming back as empty

```<code>List<Pay>olist = new List<Pay>();
List<Pay> nlist = new List<Pay>();
Pay oldpay = new Pay()
{
    EventId = 1,
    Number = 123,
    Amount = 1
};

olist.Add(oldpay);
Pay newpay = new Pay ()
{
   EventId = 1,
    Number = 123,
    Amount = 100
};
nlist.Add(newpay);
var Result = nlist.Intersect(olist);
</code>```

any clue why?

答:
As others have noted, you need to provide the appropriate overrides to get Intersect to work correctly.  But there is another way if you don't want to bother with overrides and your use case is simple.  This assumes you want to match items on EventId, but you can modify this to compare any property.  Note that this approach is likely more expensive than calling Intersect, but for small data sets it may not matter.

```<code>List<Pay> intersectedPays = new List<Pay>();

foreach (Pay o in olist)
{
    var intersectedPay = nlist.Where(n => n.EventId == o.EventId).SingleOrDefault();

    if (intersectedPay != null)
        intersectedPays.Add(intersectedPay);
}

List<Pay> result = intersectedPays;
</code>```

Title: Intersect between two lists not working

Body:
I have two lists see below.....result is coming back as empty

List<Pay>olist = new List<Pay>();
List<Pay> nlist = new List<Pay>();
Pay oldpay = new Pay()
{
    EventId = 1,
    Number = 123,
    Amount = 1
};

olist.Add(oldpay);
Pay newpay = new Pay ()
{
   EventId = 1,
    Number = 123,
    Amount = 100
};
nlist.Add(newpay);
var Result = nlist.Intersect(olist);

any clue why?

Body:
As others have noted, you need to provide the appropriate overrides to get Intersect to work correctly.  But there is another way if you don't want to bother with overrides and your use case is simple.  This assumes you want to match items on EventId, but you can modify this to compare any property.  Note that this approach is likely more expensive than calling Intersect, but for small data sets it may not matter.

List<Pay> intersectedPays = new List<Pay>();

foreach (Pay o in olist)
{
    var intersectedPay = nlist.Where(n => n.EventId == o.EventId).SingleOrDefault();

    if (intersectedPay != null)
        intersectedPays.Add(intersectedPay);
}

List<Pay> result = intersectedPays;


问:
Is it possible to have mocked object's method set value on reference type parameter?
I am using Moq to unit test a class. How can I setup the mocked IProcessor to set the Successful property on the CreateRequest parameter to true? Is this even possible? I have looked at the Callback functionality provided by the Moq framework but not sure it can do what I need in this scenario.</p>

```<code>public class CreateRequest
{
    public bool Successful { get; set; }
}

public interface IProcessor()
{
    public void Process(CreateRequest createRequest);
}

public class TheClassIAmUnitTesting()
{
    public void SomeMethod()
    {
        CreateRequest createRequest = new CreateRequest();
        processor.Process(createRequest);

        if (createRequest.Successful)
        {
             // do something
        }
        else
        {
             // do somethign else
        }
    }
}

[TestMethod]
public void TheUnitTest()
{
    Mock<IProcessor> mock = new Mock<IProcessor>

    this.mock.setup(x=>x.Process()) //<= what do i do here to have the mock set the boolean Successful property on the CreateRequest parameter to true?
}

</code>```

答:
You can try this</p>

```<code>mock.Setup(x=>x.Process(It.IsAny<CreateRequest>()))
  .Callback<CreateRequest>(cr => cr.Successful = true)
</code>```

Body:
I am using Moq to unit test a class. How can I setup the mocked IProcessor to set the Successful property on the CreateRequest parameter to true? Is this even possible? I have looked at the Callback functionality provided by the Moq framework but not sure it can do what I need in this scenario.

public class CreateRequest
{
    public bool Successful { get; set; }
}

public interface IProcessor()
{
    public void Process(CreateRequest createRequest);
}

public class TheClassIAmUnitTesting()
{
    public void SomeMethod()
    {
        CreateRequest createRequest = new CreateRequest();
        processor.Process(createRequest);

        if (createRequest.Successful)
        {
             // do something
        }
        else
        {
             // do somethign else
        }
    }
}

[TestMethod]
public void TheUnitTest()
{
    Mock<IProcessor> mock = new Mock<IProcessor>

    this.mock.setup(x=>x.Process()) //<= what do i do here to have the mock set the boolean Successful property on the CreateRequest parameter to true?
}

Body:
You can try this

mock.Setup(x=>x.Process(It.IsAny<CreateRequest>()))
  .Callback<CreateRequest>(cr => cr.Successful = true)


问:
Side-by-side boxplot of multiple columns of a pandas DataFrame
One year of sample data:

```<code>import pandas as pd
import numpy.random as rnd
import seaborn as sns
n = 365
df = pd.DataFrame(data = {"A":rnd.randn(n), "B":rnd.randn(n)+1},
                  index=pd.date_range(start="2017-01-01", periods=n, freq="D"))
</code>```

I want to boxplot these data side-by-side grouped by the month (i.e., two boxes per month, one for A and one for B).

For a single column sns.boxplot(df.index.month, df["A"]) works fine. However, sns.boxplot(df.index.month, df[["A", "B"]]) throws an error (ValueError: cannot copy sequence with size 2 to array axis with dimension 365). Melting the data by the index (pd.melt(df, id_vars=df.index, value_vars=["A", "B"], var_name="column")) in order to use seaborn's hue property as a workaround doesn't work either (TypeError: unhashable type: 'DatetimeIndex').

(A solution doesn't necessarily need to use seaborn, if it is easier using plain matplotlib.)

Edit

I found a workaround that basically produces what I want. However, it becomes somewhat awkward to work with once the DataFrame includes more variables than I want to plot. So if there is a more elegant/direct way to do it, please share!

```<code>df_stacked = df.stack().reset_index()
df_stacked.columns = ["date", "vars", "vals"]
df_stacked.index = df_stacked["date"]
sns.boxplot(x=df_stacked.index.month, y="vals", hue="vars", data=df_stacked)
</code>```

Produces:

答:
here's a solution using pandas melting and seaborn:</p>

```<code>import pandas as pd
import numpy.random as rnd
import seaborn as sns
n = 365
df = pd.DataFrame(data = {"A": rnd.randn(n),
                          "B": rnd.randn(n)+1,
                          "C": rnd.randn(n) + 10, # will not be plotted
                         },
                  index=pd.date_range(start="2017-01-01", periods=n, freq="D"))
df['month'] = df.index.month
df_plot = df.melt(id_vars='month', value_vars=["A", "B"])
sns.boxplot(x='month', y='value', hue='variable', data=df_plot)
</code>```

Body:
One year of sample data:

import pandas as pd
import numpy.random as rnd
import seaborn as sns
n = 365
df = pd.DataFrame(data = {"A":rnd.randn(n), "B":rnd.randn(n)+1},
                  index=pd.date_range(start="2017-01-01", periods=n, freq="D"))

I want to boxplot these data side-by-side grouped by the month (i.e., two boxes per month, one for A and one for B).

For a single column sns.boxplot(df.index.month, df["A"]) works fine. However, sns.boxplot(df.index.month, df[["A", "B"]]) throws an error (ValueError: cannot copy sequence with size 2 to array axis with dimension 365). Melting the data by the index (pd.melt(df, id_vars=df.index, value_vars=["A", "B"], var_name="column")) in order to use seaborn's hue property as a workaround doesn't work either (TypeError: unhashable type: 'DatetimeIndex').

(A solution doesn't necessarily need to use seaborn, if it is easier using plain matplotlib.)

Edit

I found a workaround that basically produces what I want. However, it becomes somewhat awkward to work with once the DataFrame includes more variables than I want to plot. So if there is a more elegant/direct way to do it, please share!

df_stacked = df.stack().reset_index()
df_stacked.columns = ["date", "vars", "vals"]
df_stacked.index = df_stacked["date"]
sns.boxplot(x=df_stacked.index.month, y="vals", hue="vars", data=df_stacked)

Produces:

Body:
here's a solution using pandas melting and seaborn:

import pandas as pd
import numpy.random as rnd
import seaborn as sns
n = 365
df = pd.DataFrame(data = {"A": rnd.randn(n),
                          "B": rnd.randn(n)+1,
                          "C": rnd.randn(n) + 10, # will not be plotted
                         },
                  index=pd.date_range(start="2017-01-01", periods=n, freq="D"))
df['month'] = df.index.month
df_plot = df.melt(id_vars='month', value_vars=["A", "B"])
sns.boxplot(x='month', y='value', hue='variable', data=df_plot)


问:
How do you debug heavily templated code in c++?
I find it very hard to figure out what is wrong with my code when using C++ template meta-programming. It might be that I am just not very good at understanding the error messages, but as far as I'm aware I can't resort to putting in print statements or breakpoints to figure out what's going on.

What tips or advice can you offer when trying to figure out why something is not compiling other than just picking through the code manually and hoping it will come to me?

答: If you're using gcc, I've found that colorgcc can help out a tiny bit.  The color coding makes it easier to mentally parse out warnings vs. errors vs. contextual information.</p>

OwnerDisplayName: Dan

LastEditorDisplayName: David Segonds

OwnerDisplayName: Mr Fooz


问:
Is there a way for a custom View to detect when its Activity is paused or stopped?
I'm writing a wrapper around ExoPlayer as a custom view. The goal is to create a very simple abstraction for our streams and ad logic so that we can distribute a JAR file to clients and they can drag-and-drop a "BFPlayer" into their custom apps, hand it an ID referencing one of our broadcasts, and everything will play like magic.

As ExoPlayer needs to be released whenever an activity is paused or stopped, if possible I would like to do this automatically. I would like to detect when the parent activity is paused, release ExoPlayer, then detect when it's unpaused and spin up a new ExoPlayer silently and resume the previous state.

I found this StackOverflow post, describing how to get the hosting Activity from a View, however once I have the activity I don't know of a way to register a function to run automatically when the activity is paused.

答:
Just wanted to add another solution I discovered for this that might be a bit cleaner. You can have your View implement the LifecycleListener interface then call getLifecycle().addListener(view) within the activity:

Activity.java:

```<code>public class MyActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        MyView myView = findViewById(R.id.myView);
        getLifecycle().addObserver(myView);
    }
}
</code>```

View.java:

```<code>public class MyView extends View implements LifecycleListener {
    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void onPause() {
        Log.i("LIFECYCLE EVENT", "Activity was paused");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void onResume() {
        Log.i("LIFECYCLE EVENT", "Activity was resumed");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onStop() {
        Log.i("LIFECYCLE EVENT", "Activity was stopped");
    }
}
</code>```

I like this solution because it minimizes the amount of code that must be added to the activity - reducing the cost to implement a library to a single additional line that must be pasted in rather than having to declare multiple lifecycle methods and delegate to the view manually.

Body:
Just wanted to add another solution I discovered for this that might be a bit cleaner. You can have your View implement the LifecycleListener interface then call getLifecycle().addListener(view) within the activity:

Activity.java:

public class MyActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        MyView myView = findViewById(R.id.myView);
        getLifecycle().addObserver(myView);
    }
}

View.java:

public class MyView extends View implements LifecycleListener {
    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void onPause() {
        Log.i("LIFECYCLE EVENT", "Activity was paused");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void onResume() {
        Log.i("LIFECYCLE EVENT", "Activity was resumed");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onStop() {
        Log.i("LIFECYCLE EVENT", "Activity was stopped");
    }
}

I like this solution because it minimizes the amount of code that must be added to the activity - reducing the cost to implement a library to a single additional line that must be pasted in rather than having to declare multiple lifecycle methods and delegate to the view manually.


问:
get() in picasso cannot be applied to (android.content.context)
I have the following code on android studio, after I followed a tutorial video. However, in the tutorial video, the uploader used:

implementation 'com.android.picasso:picasso:2.5.2'

while I had to use

```<code>implementation 'com.squareup.picasso:picasso:2.71828'
</code>```

Adapter Class

```<code>public class adapter extends RecyclerView.Adapter<adapter.viewHolder> {
    private Context mContext;
    private ArrayList<ItemActivity> mExampleList;

    public adapter(Context context, ArrayList<ItemActivity> exampleList)
    {
        mContext = context;
        mExampleList = exampleList;
    }

    @NonNull
    @Override
    public viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int
    viewType) {
            View v =
LayoutInflater.from(mContext).inflate(R.layout.itemlayout, parent, false);
        return new viewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull viewHolder holder, int position)
    {
        ItemActivity currentItem = mExampleList.get(position);

        String imageUrl = currentItem.getImageUrl();
        String creatorName = currentItem.getCreator();
        int likeCount = currentItem.getLikeCount();

        holder.mTextViewCreator.setText(creatorName);
        holder.mTextViewLikes.setText("Likes: "+likeCount);

        Picasso.get(mContext).load(imageUrl).
        fit().centerInside.into(holder.mImageView);//get() in picasso
                                                     cannot be applied to
                                                 (android.content.context)
    }

    @Override
    public int getItemCount() {
        return mExampleList.size();
    }

    public class viewHolder extends RecyclerView.ViewHolder
    {
        public ImageView mImageView;
        public TextView mTextViewCreator;
        public TextView mTextViewLikes;

        public viewHolder(@NonNull View itemView) {
            super(itemView);
            mTextViewCreator = itemView.findViewById(R.id.image_view);
            mImageView = itemView.findViewById(R.id.text_view_creator);
            mTextViewLikes = itemView.findViewById(R.id.text_view_likes);
        }
    }

}
</code>```

As stated above, the Picasso line gives me the error: get() in picasso cannot be applied to (android.content.context)

Thanks!

答:
Picasso with(Context) hast been renamed to get()

Check this commit

Body:
I have the following code on android studio, after I followed a tutorial video. However, in the tutorial video, the uploader used:

implementation 'com.android.picasso:picasso:2.5.2'

while I had to use

implementation 'com.squareup.picasso:picasso:2.71828'

Adapter Class

public class adapter extends RecyclerView.Adapter<adapter.viewHolder> {
    private Context mContext;
    private ArrayList<ItemActivity> mExampleList;

    public adapter(Context context, ArrayList<ItemActivity> exampleList)
    {
        mContext = context;
        mExampleList = exampleList;
    }

    @NonNull
    @Override
    public viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int
    viewType) {
            View v =
LayoutInflater.from(mContext).inflate(R.layout.itemlayout, parent, false);
        return new viewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull viewHolder holder, int position)
    {
        ItemActivity currentItem = mExampleList.get(position);

        String imageUrl = currentItem.getImageUrl();
        String creatorName = currentItem.getCreator();
        int likeCount = currentItem.getLikeCount();

        holder.mTextViewCreator.setText(creatorName);
        holder.mTextViewLikes.setText("Likes: "+likeCount);

        Picasso.get(mContext).load(imageUrl).
        fit().centerInside.into(holder.mImageView);//get() in picasso
                                                     cannot be applied to
                                                 (android.content.context)
    }

    @Override
    public int getItemCount() {
        return mExampleList.size();
    }

    public class viewHolder extends RecyclerView.ViewHolder
    {
        public ImageView mImageView;
        public TextView mTextViewCreator;
        public TextView mTextViewLikes;

        public viewHolder(@NonNull View itemView) {
            super(itemView);
            mTextViewCreator = itemView.findViewById(R.id.image_view);
            mImageView = itemView.findViewById(R.id.text_view_creator);
            mTextViewLikes = itemView.findViewById(R.id.text_view_likes);
        }
    }

}

As stated above, the Picasso line gives me the error: get() in picasso cannot be applied to (android.content.context)

Thanks!


问:
How to divide between groups of rows using dplyr with multiple columns?
My question is an extension of this question. I want to figure out how to divide between groups of rows using dplyr with multiple columns, instead of for a single variable.

I have this dataframe:

```<code>x <- data.frame(
    name = rep(letters[1:4], each = 2),
    condition = rep(c("A", "B"), times = 4),
    value1 = c(2,10,4,20,8,40,20,100),
    value2 = c(2,10,4,20,8,40,20,100)
)
#   name condition value1 value2
# 1    a         A     2       2
# 2    a         B    10       10
# 3    b         A     4       4
# 4    b         B    20       20
# 5    c         A     8       8
# 6    c         B    40       40
# 7    d         A    20       20
# 8    d         B   100       100
</code>```

I want to group by name and divide the value of rows with condition == "B" with those with condition == "A", to get this:

```<code>data.frame(
    name = letters[1:4],
    value1 = c(5,5,5,5),
    value2 = c(5,5,5,5)
)
#   name value1 value2
# 1    a     5       5
# 2    b     5       5
# 3    c     5       5
# 4    d     5       5
</code>```

There is the most upvoted answer there by Steven Beaupré for the original question with a single variable:

```<code>x %>%
group_by(name) %>%
summarise(value = value[condition == "B"] / value[condition == "A"])
</code>```

But that answer is for single value case, I don't know how to extend to "summarise_at" and "summarise_all". I tried to use "dot", but cannot figure out the correct syntax.

答:
I'm not sure if there is a way to automatically extend this function to every variable. I think you need to specify the summary function for each value case.</p>

```<code>x %>%
  group_by(name) %>%
  summarise(value1 = value1[condition == "B"] / value1[condition == "A"],
            value2 = value2[condition == "B"] / value2[condition == "A"])

#  name  value1 value2
#   <fct>  <dbl>  <dbl>
# 1 a          5      5
# 2 b          5      5
# 3 c          5      5
# 4 d          5      5
</code>```

Body:
My question is an extension of this question. I want to figure out how to divide between groups of rows using dplyr with multiple columns, instead of for a single variable.

I have this dataframe:

x <- data.frame(
    name = rep(letters[1:4], each = 2),
    condition = rep(c("A", "B"), times = 4),
    value1 = c(2,10,4,20,8,40,20,100),
    value2 = c(2,10,4,20,8,40,20,100)
)
#   name condition value1 value2
# 1    a         A     2       2
# 2    a         B    10       10
# 3    b         A     4       4
# 4    b         B    20       20
# 5    c         A     8       8
# 6    c         B    40       40
# 7    d         A    20       20
# 8    d         B   100       100

I want to group by name and divide the value of rows with condition == "B" with those with condition == "A", to get this:

data.frame(
    name = letters[1:4],
    value1 = c(5,5,5,5),
    value2 = c(5,5,5,5)
)
#   name value1 value2
# 1    a     5       5
# 2    b     5       5
# 3    c     5       5
# 4    d     5       5

There is the most upvoted answer there by Steven Beaupré for the original question with a single variable:

x %>%
group_by(name) %>%
summarise(value = value[condition == "B"] / value[condition == "A"])

But that answer is for single value case, I don't know how to extend to "summarise_at" and "summarise_all". I tried to use "dot", but cannot figure out the correct syntax.

Body:
I'm not sure if there is a way to automatically extend this function to every variable. I think you need to specify the summary function for each value case.

x %>%
  group_by(name) %>%
  summarise(value1 = value1[condition == "B"] / value1[condition == "A"],
            value2 = value2[condition == "B"] / value2[condition == "A"])

#  name  value1 value2
#   <fct>  <dbl>  <dbl>
# 1 a          5      5
# 2 b          5      5
# 3 c          5      5
# 4 d          5      5


问:
Changing Bootstrap 4.1 .btn-outline-primary background when clicked and active?
I am currently using a Bootstrap 4.1 button with the class being .btn-outline-primary. In its regular state, the button has a white background with blue text. However, when you hover over the button, the colors are inverted such that the background is blue and the text is white.

The active state of this button is only a highlighted border (with button styling the same as inactive state - white background blue text) and I would like to make it so that when the button is clicked, the button remains in the same style as when the button is hovered.

However, I do not have access to the hover class of the button since it is a bootstrap button and I am wondering how I can achieve this? Here is the button:

```<code><button class='btn btn-outline-primary max-w-250 mx-1 my-1' type='button' id='MyButton' name='happyButton'>
 <div class='d-flex flex-column justify-content-center align-items-center overflow-none'>
  <div class='ButtonText line-height-16'>"Text Line One"</div>
 </div>
</button>
</code>```

I have tried using css styling using :focus to change the background color, however, this just over-powers the text since the text does not invert and the background now matches the text color.

.btn-outline-primary:focus{
   background-color: #18f;
}
```

答:
I'm not a huge Bootstrap user or I'd look up the relevant classes for you. Instead, I'll walk you through the steps to find them yourself using DevTools. I'll be using Chrome, but the steps are similar for Firefox and Safari.

In a browser (again, preferably Chrome) where the button is rendered, right click on that button. From the menu, select Inspect.

The box that comes up should be on an elements tab, displaying your html. Confirm that the button is highlighted in that display. If it isn't, click on the button's html to highlight it.

The right side of the newly opened box should be a pane describing the selected element, and should be on the Styles tab. Confirm that the css rules that you'd expect to apply to the button are there.

Near the top of that pane, next to the filter box, there is a small button labeled :hov. Clicking that button displays the various pseudoclasses, like :hover, that can be applied to your element. Check the :hover checkbox.

The :hover rules should now display in the css rules list below. Find the relevant declaration (.btn-outline-primary:focus or something similar) and copy the rules it contains. You can then, in your own css, write

```<code>.btn-outline-primary:active {
  [whatever rules you copied]
}
</code>```

I have two addenda:

If that doesn't work, go through the first four steps again, this time selecting the :active pseudoclass. If the rules you added are showing up in your rules list (they may be way down!) but aren't working, you have an issue with css specificity and should look that up

I have written this assuming that, when talking about an active button, you were using the term in the technical css sense, which is a change that only lasts so long as the button is held down. If you want the button to change permanently after it is clicked, you will need to use something outside of css: either use some Javascript to update the classes on the button or change it up and use a checkbox

Body:
I am currently using a Bootstrap 4.1 button with the class being .btn-outline-primary. In its regular state, the button has a white background with blue text. However, when you hover over the button, the colors are inverted such that the background is blue and the text is white.

The active state of this button is only a highlighted border (with button styling the same as inactive state - white background blue text) and I would like to make it so that when the button is clicked, the button remains in the same style as when the button is hovered.

However, I do not have access to the hover class of the button since it is a bootstrap button and I am wondering how I can achieve this? Here is the button:

<button class='btn btn-outline-primary max-w-250 mx-1 my-1' type='button' id='MyButton' name='happyButton'>

"Text Line One"

</button>

I have tried using css styling using :focus to change the background color, however, this just over-powers the text since the text does not invert and the background now matches the text color.

.btn-outline-primary:focus{
   background-color: #18f;
}

Body:
I'm not a huge Bootstrap user or I'd look up the relevant classes for you. Instead, I'll walk you through the steps to find them yourself using DevTools. I'll be using Chrome, but the steps are similar for Firefox and Safari.

In a browser (again, preferably Chrome) where the button is rendered, right click on that button. From the menu, select Inspect.

The box that comes up should be on an elements tab, displaying your html. Confirm that the button is highlighted in that display. If it isn't, click on the button's html to highlight it.

The right side of the newly opened box should be a pane describing the selected element, and should be on the Styles tab. Confirm that the css rules that you'd expect to apply to the button are there.

Near the top of that pane, next to the filter box, there is a small button labeled :hov. Clicking that button displays the various pseudoclasses, like :hover, that can be applied to your element. Check the :hover checkbox.

The :hover rules should now display in the css rules list below. Find the relevant declaration (.btn-outline-primary:focus or something similar) and copy the rules it contains. You can then, in your own css, write

.btn-outline-primary:active {
  [whatever rules you copied]
}

I have two addenda:

If that doesn't work, go through the first four steps again, this time selecting the :active pseudoclass. If the rules you added are showing up in your rules list (they may be way down!) but aren't working, you have an issue with css specificity and should look that up

I have written this assuming that, when talking about an active button, you were using the term in the technical css sense, which is a change that only lasts so long as the button is held down. If you want the button to change permanently after it is clicked, you will need to use something outside of css: either use some Javascript to update the classes on the button or change it up and use a checkbox


答:
Use a call back and get access to the passed argument

```<code>[TestMethod]
public void TheUnitTest() {
    //Arrange
    Mock<IProcessor> mock = new Mock<IProcessor>();

    mock.Setup(_ => _.Process(It.IsAny<CreateRequest>()))
        .Callback((CreateRequest arg) => arg.Successful = true)
        .Verifiable();

    var subject = new TheClassIAmUnitTesting(mock.Object);

    //Act
    subject.SomeMethod();

    //Assert
    mock.VerifyAll();
}
</code>```

Reference Moq Quickstart: Callbacks

Title: Is it possible to have mocked object's method set value on reference type parameter?

Body:
Use a call back and get access to the passed argument

[TestMethod]
public void TheUnitTest() {
    //Arrange
    Mock<IProcessor> mock = new Mock<IProcessor>();

    mock.Setup(_ => _.Process(It.IsAny<CreateRequest>()))
        .Callback((CreateRequest arg) => arg.Successful = true)
        .Verifiable();

    var subject = new TheClassIAmUnitTesting(mock.Object);

    //Act
    subject.SomeMethod();

    //Assert
    mock.VerifyAll();
}

Reference Moq Quickstart: Callbacks


问:
Unexpected exception being raised when trying to convert an input string to float
I want to ask the user to input a value and then print its length, if the input is a string. If the user's input is an integer or a decimal, I want to print "Sorry, integers don't have length" or  "Sorry, floats don't have length", respectively.

I'm making use of exception while trying to convert the input into float or integer.

Here is my code:

```<code>c=input("enter a string: ")

def length(c):
    return len(c)

try:
    float(c)
    if float(c)==int(c):
        print("Sorry integers don't have length")
    else:
        print("Sorry floats don't have length")
except:
    print(length(c))
</code>```

The output results are as follows:

> enter a string: sfkelkrelte
11
> enter a string: 21
Sorry integers don't have length
> enter a string: 21.1
4
```

When I input an integer, the error message is displayed correctly, as the conversion float() is possible. But, in case of a floating point number, the interpreter goes to except block, though it should have executed the try block.

Why does this happen?

答:
The part that is raising the exception is int(c):

```<code>c = "21.1"
print(int(c))
# ValueError: invalid literal for int() with base 10: '21.1'
</code>```

One minor change would fix this for you:

```<code>c="21.1"

try:
    float(c)
    if "." not in c: #<---- check if "." is in the string c AFTER conversion to float
        print("Sorry integers don't have length")
    else:
        print("Sorry floats don't have length")
except:
    print(len(c))
# Sorry floats don't have length
</code>```

However, it's generally bad practice to blindly catch all exceptions. This would have the unintended side effect of any error in your program triggering the except block.

It would be more appropriate to catch only the one you are expecting.

```<code>c="21.aakdjs1"

try:
    float(c)
    if "." not in c:
        print("Sorry integers don't have length")
    else:
        print("Sorry floats don't have length")
except ValueError:
    print(len(c))
# 10
</code>```

For future debugging, you can always print the exception.

Body:
I want to ask the user to input a value and then print its length, if the input is a string. If the user's input is an integer or a decimal, I want to print "Sorry, integers don't have length" or  "Sorry, floats don't have length", respectively.

I'm making use of exception while trying to convert the input into float or integer.

Here is my code:

c=input("enter a string: ")

def length(c):
    return len(c)

try:
    float(c)
    if float(c)==int(c):
        print("Sorry integers don't have length")
    else:
        print("Sorry floats don't have length")
except:
    print(length(c))

The output results are as follows:

> enter a string: sfkelkrelte
11
> enter a string: 21
Sorry integers don't have length
> enter a string: 21.1
4

When I input an integer, the error message is displayed correctly, as the conversion float() is possible. But, in case of a floating point number, the interpreter goes to except block, though it should have executed the try block.

Why does this happen?

Body:
The part that is raising the exception is int(c):

c = "21.1"
print(int(c))
# ValueError: invalid literal for int() with base 10: '21.1'

One minor change would fix this for you:

c="21.1"

try:
    float(c)
    if "." not in c: #<---- check if "." is in the string c AFTER conversion to float
        print("Sorry integers don't have length")
    else:
        print("Sorry floats don't have length")
except:
    print(len(c))
# Sorry floats don't have length

However, it's generally bad practice to blindly catch all exceptions. This would have the unintended side effect of any error in your program triggering the except block.

It would be more appropriate to catch only the one you are expecting.

c="21.aakdjs1"

try:
    float(c)
    if "." not in c:
        print("Sorry integers don't have length")
    else:
        print("Sorry floats don't have length")
except ValueError:
    print(len(c))
# 10

For future debugging, you can always print the exception.


问:
django admin crashes when trying to update record but not when inserting a new one
I'm having a weird problem:

technical info for developemnt (production will be on linux/apache/Mysql)
macosx 2.6.6
python 2.6.1
django 1.3
mysql 5.1
and MySQLdb to connect the python to the MySQL...

I'm new at django as every one can see from past questions...but need to get really strong at it, really fast...the problem is that it is really not that smooth for me...

OK, for the question. I'm doing the django tutorial (not for fun, i need to learn it really fast because i need to develop a huge system with it).

I did all the the tutorial untill now and at the stage where i added the admin.

When i try to edit the poll record (if any one know the django 1.3 tutrial) the site crashes with the following exception:

Warning at /admin/polls/poll/2/
  Incorrect string value: '\xD7\xA9\xD7\x95\xD7\xA0...' for column 'change_message' at row 1

there is not problem with adding a new record to the same table, just to edit one....

if any one know's any thing about it....

```<code># Create your models here.
</code>```

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

```<code>def __unicode__(self):
    return self.question

def was_published_today(self):
    return self.pub_date.date() == datetime.date.today()
</code>```

This is the model, and another this i saw, my MySQL DB is latin1 and not UTF-8...python is unicode....maybe that is the problem....

But still, i can't figure out why i can add records but can't edit them....isn't that the weird part?

答:
Sounds like a database character set issue. Can you check the default character set of auth_message table in your database?

If your table can't handle utf8 it would throw this error.

Body:
I'm having a weird problem:

technical info for developemnt (production will be on linux/apache/Mysql)
macosx 2.6.6
python 2.6.1
django 1.3
mysql 5.1
and MySQLdb to connect the python to the MySQL...

I'm new at django as every one can see from past questions...but need to get really strong at it, really fast...the problem is that it is really not that smooth for me...

OK, for the question. I'm doing the django tutorial (not for fun, i need to learn it really fast because i need to develop a huge system with it).

I did all the the tutorial untill now and at the stage where i added the admin.

When i try to edit the poll record (if any one know the django 1.3 tutrial) the site crashes with the following exception:

Warning at /admin/polls/poll/2/
  Incorrect string value: '\xD7\xA9\xD7\x95\xD7\xA0...' for column 'change_message' at row 1

there is not problem with adding a new record to the same table, just to edit one....

if any one know's any thing about it....

# Create your models here.

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

def __unicode__(self):
    return self.question

def was_published_today(self):
    return self.pub_date.date() == datetime.date.today()

This is the model, and another this i saw, my MySQL DB is latin1 and not UTF-8...python is unicode....maybe that is the problem....

But still, i can't figure out why i can add records but can't edit them....isn't that the weird part?


问:
Does Microsoft Office 365 Business - Microsoft Store Version supports VSTO COM Add-ins?
Does Microsoft Office 365 Business - Microsoft Store Version supports VSTO COM Add-ins?

Add-in not listed on Disabled Add-ins list either.

I've created Dummy Add-in entry as registry key HKEY_CURRENT_USER\Software\Microsoft\Office\Word\Addins\Dummy with it's required values (Description, FriendlyName, LoadBehavior, Manifest).

I've put dummy contents for listed key pair values, with no Add-in being listed under COM Add-ins list (for Word in this case).

Add-in appears on COM Add-ins list under Microsoft Office 365 Business, Click-to-Run Version (another machine), but not appearing under Store Version.

Microsoft Office 365 Business, Microsoft Store Version was preinstalled on Dell Latitude laptop.

答:
The answer seems to be "No, it doesn't". Under the section "Is Office in the Microsoft Store any different than an existing Office desktop suite?" in the FAQ it says:

Some Office add-ins may not work if Office is installed via the
  Microsoft Store. We're working to make Office in the Microsoft Store
  compatible with more add-ins.

There is a UserVoice suggestion that requests this functionality.


问:
Text saved on a variable showing null values when i try to find a specific line
I saved a pdf content into a variable (called CCR) and when i print this variable, it shows the whole text, line by line correctly. Im trying to loop to find some lines that matches with a phrase but it shows me nothing. When i try to see what happens in this loop, i find that every line read from the variable looks empty.

```<code>#Extracting text and test

raw_CCR = parser.from_file(r'C:\Users\guerr\OneDrive\Documentos\PYTHON\ROOT_FILES\CCR.pdf')
CCR = raw_CCR['content']
print(CCR)

#Finding lines

key = "13.2"
linhas = 0
for line in CCR:
    linhas += 1
    print(linhas)
    if key in line:
        print("Found")
    else:
        print("Not Found")
</code>```

A part of the Loop. It finds nothing. The value "linhas" only helps me to know what is happening inside the loop

```<code>1
Not Found
2
Not Found
3
Not Found
4
Not Found
5
Not Found
6
Not Found
7
Not Found
8
Not Found
9
Not Found
10
Not Found
11
Not Found
12
Not Found
13
Not Found
14
Not Found
15
Not Found
16
Not Found
17
Not Found
18
Not Found
19
Not Found
20
Not Found
21
Not Found
22
Not Found
23
Not Found
24
Not Found
25
Not Found
26
Not Found
</code>```

答:
Your line variable is actually going char by char. So your line var would be something like t then h then e, etc.

Add .splitlines() if you want to do line by line. I just tried this with tika on a PDF and it worked fine.

```<code>for line in CCR.splitlines():
    linhas += 1
    print(linhas)
    if key in line:
        print("Found")
    else:
        print("Not Found")
</code>```

Body:
I saved a pdf content into a variable (called CCR) and when i print this variable, it shows the whole text, line by line correctly. Im trying to loop to find some lines that matches with a phrase but it shows me nothing. When i try to see what happens in this loop, i find that every line read from the variable looks empty.

#Extracting text and test

raw_CCR = parser.from_file(r'C:\Users\guerr\OneDrive\Documentos\PYTHON\ROOT_FILES\CCR.pdf')
CCR = raw_CCR['content']
print(CCR)

#Finding lines

key = "13.2"
linhas = 0
for line in CCR:
    linhas += 1
    print(linhas)
    if key in line:
        print("Found")
    else:
        print("Not Found")

A part of the Loop. It finds nothing. The value "linhas" only helps me to know what is happening inside the loop

1
Not Found
2
Not Found
3
Not Found
4
Not Found
5
Not Found
6
Not Found
7
Not Found
8
Not Found
9
Not Found
10
Not Found
11
Not Found
12
Not Found
13
Not Found
14
Not Found
15
Not Found
16
Not Found
17
Not Found
18
Not Found
19
Not Found
20
Not Found
21
Not Found
22
Not Found
23
Not Found
24
Not Found
25
Not Found
26
Not Found

Body:
Your line variable is actually going char by char. So your line var would be something like t then h then e, etc.

Add .splitlines() if you want to do line by line. I just tried this with tika on a PDF and it worked fine.

for line in CCR.splitlines():
    linhas += 1
    print(linhas)
    if key in line:
        print("Found")
    else:
        print("Not Found")


问:
How to convert wide data to long data based on three variables
I have a dataframe that is structure as such:

```<code>Item FY20 FY21 FY22 ...
Case High Low Base
Multiple 1.2 2.3 3.4
Cash 1.1 1.4 1.2
</code>```

I need the data to look like this:

```<code>Item Date Case Value
Cash FY20 High 1.1
Cash FY21 Low 1.4
Cash FY22 Base 1.2
</code>```

So I essentially want to transform the data from wide format to a long format based on "Case", the "FY"s and the item.

I've already tried using multi indexes and messed around a bit with pd.pivot but i'm honestly stumped here.

答:
IIUC, you can use this bit of code to reshape your dataframe:

```<code>df.set_index('Item')\ # move Item into dataframe index
  .T\  # transpose dataframe
  .rename_axis('Date')\  #rename index to Date
  .reset_index()\  #move index into dataframe as column
  .melt(['Date', 'Case'])  #melt dataframe to get to long format
</code>```

Output:

```<code>   Date  Case      Item value
0  FY20  High  Multiple   1.2
1  FY21   Low  Multiple   2.3
2  FY22  Base  Multiple   3.4
3  FY20  High      Cash   1.1
4  FY21   Low      Cash   1.4
5  FY22  Base      Cash   1.2
</code>```

Details:

Where df is:

```<code>       Item  FY20 FY21  FY22
0      Case  High  Low  Base
1  Multiple   1.2  2.3   3.4
2      Cash   1.1  1.4   1.2

df.set_index('Item').T
</code>```

Almost there,

```<code>Item  Case Multiple Cash
FY20  High      1.2  1.1
FY21   Low      2.3  1.4
FY22  Base      3.4  1.2

df.set_index('Item').T.rename_axis('Date').reset_index()
</code>```

Add rename_axis and reset_index to prepare dataframe for melt,

```<code>Item  Date  Case Multiple Cash
0     FY20  High      1.2  1.1
1     FY21   Low      2.3  1.4
2     FY22  Base      3.4  1.2
</code>```

Lastly melt dataframe:

```<code>df.set_index('Item').T.rename_axis('Date').reset_index().melt(['Date', 'Case'])
</code>```

Output:

```<code>   Date  Case      Item value
0  FY20  High  Multiple   1.2
1  FY21   Low  Multiple   2.3
2  FY22  Base  Multiple   3.4
3  FY20  High      Cash   1.1
4  FY21   Low      Cash   1.4
5  FY22  Base      Cash   1.2
</code>```

And, if you only want the "Cash" records, then use this

```<code>df_out = df.set_index('Item').T.rename_axis('Date').reset_index().melt(['Date', 'Case'])
df_out.query('Item == "Cash"')
</code>```

Output:

```<code>   Date  Case  Item value
3  FY20  High  Cash   1.1
4  FY21   Low  Cash   1.4
5  FY22  Base  Cash   1.2
</code>```

Body:
I have a dataframe that is structure as such:

Item FY20 FY21 FY22 ...
Case High Low Base
Multiple 1.2 2.3 3.4
Cash 1.1 1.4 1.2

I need the data to look like this:

Item Date Case Value
Cash FY20 High 1.1
Cash FY21 Low 1.4
Cash FY22 Base 1.2

So I essentially want to transform the data from wide format to a long format based on "Case", the "FY"s and the item.

I've already tried using multi indexes and messed around a bit with pd.pivot but i'm honestly stumped here.

Body:
IIUC, you can use this bit of code to reshape your dataframe:

df.set_index('Item')\ # move Item into dataframe index
  .T\  # transpose dataframe
  .rename_axis('Date')\  #rename index to Date
  .reset_index()\  #move index into dataframe as column
  .melt(['Date', 'Case'])  #melt dataframe to get to long format

Output:

   Date  Case      Item value
0  FY20  High  Multiple   1.2
1  FY21   Low  Multiple   2.3
2  FY22  Base  Multiple   3.4
3  FY20  High      Cash   1.1
4  FY21   Low      Cash   1.4
5  FY22  Base      Cash   1.2

Details:

Where df is:

       Item  FY20 FY21  FY22
0      Case  High  Low  Base
1  Multiple   1.2  2.3   3.4
2      Cash   1.1  1.4   1.2

df.set_index('Item').T

Almost there,

Item  Case Multiple Cash
FY20  High      1.2  1.1
FY21   Low      2.3  1.4
FY22  Base      3.4  1.2

df.set_index('Item').T.rename_axis('Date').reset_index()

Add rename_axis and reset_index to prepare dataframe for melt,

Item  Date  Case Multiple Cash
0     FY20  High      1.2  1.1
1     FY21   Low      2.3  1.4
2     FY22  Base      3.4  1.2

Lastly melt dataframe:

df.set_index('Item').T.rename_axis('Date').reset_index().melt(['Date', 'Case'])

Output:

   Date  Case      Item value
0  FY20  High  Multiple   1.2
1  FY21   Low  Multiple   2.3
2  FY22  Base  Multiple   3.4
3  FY20  High      Cash   1.1
4  FY21   Low      Cash   1.4
5  FY22  Base      Cash   1.2

And, if you only want the "Cash" records, then use this

df_out = df.set_index('Item').T.rename_axis('Date').reset_index().melt(['Date', 'Case'])
df_out.query('Item == "Cash"')

Output:

   Date  Case  Item value
3  FY20  High  Cash   1.1
4  FY21   Low  Cash   1.4
5  FY22  Base  Cash   1.2


问:
Is there a way to make a makefile autodownload another makefile?
i know it is possible to execute standard rules on a makefile by simply including them like

```<code>hi:; echo hello

include hi
</code>```

but there is some way, by doing this, to fetch an external input like a ftp server or, lets say, the aws s3 to fetch a "newborn" makefile and then include it to the project? in runtime?
like

```<code>include https://s3.bucket.domain.com/newmk.mk
</code>```

答:
The make utility has no built-in download support (not even GNU's make which sometimes seems to have the kitchen sink thrown in), but because it can run arbitrary commands, you can fake it up

The simplest case is a fragment like

```<code>your_primary_target: newmk.mk

#...
WGET=wget
WGET_FLAGS=-q

newmk.mk:
    $(WGET) $(WGET_FLAGS) https://s3.bucket.domain.com/newmk.mk
#...
</code>```

which will attempt to download the file only if no such file exists.

The main difficulty here is that your users may need to edit the makefile to specify the command-line downloader they have (perhaps curl instead of wget), or it set any flags their network environment requires.

To make the download unconditional  use a unbuildable, non-existent target

```<code>WGET=wget
WGET_FLAGS=-1

newmk.mk: ALWAYS
    $(WGET) $(WGET_FLAGS) https://s3.bucket.domain.com/newmk.mk

# Here "ALWAYS" is *not* the name of a file existing in the file-system
ALWAYS:
</code>```

(or there are games you can play with .PHONY in GNU-make).

Body:
i know it is possible to execute standard rules on a makefile by simply including them like

hi:; echo hello

include hi

but there is some way, by doing this, to fetch an external input like a ftp server or, lets say, the aws s3 to fetch a "newborn" makefile and then include it to the project? in runtime?
like

include https://s3.bucket.domain.com/newmk.mk

Body:
The make utility has no built-in download support (not even GNU's make which sometimes seems to have the kitchen sink thrown in), but because it can run arbitrary commands, you can fake it up

The simplest case is a fragment like

your_primary_target: newmk.mk

#...
WGET=wget
WGET_FLAGS=-q

newmk.mk:
    $(WGET) $(WGET_FLAGS) https://s3.bucket.domain.com/newmk.mk
#...

which will attempt to download the file only if no such file exists.

The main difficulty here is that your users may need to edit the makefile to specify the command-line downloader they have (perhaps curl instead of wget), or it set any flags their network environment requires.

To make the download unconditional  use a unbuildable, non-existent target

WGET=wget
WGET_FLAGS=-1

newmk.mk: ALWAYS
    $(WGET) $(WGET_FLAGS) https://s3.bucket.domain.com/newmk.mk

# Here "ALWAYS" is *not* the name of a file existing in the file-system
ALWAYS:

(or there are games you can play with .PHONY in GNU-make).


问:
Google Authentication Requirement For Accessing Reporting API
We are trying to use the Google Reporting API from a .NET Core application but are completely confused as to the kind of Authentication requirement.
There seems to be several ways from Keys to Other methods.

Does anyone know what kind of Credentials and how it should be used when trying to access Analytics data using the Reporting API from .NET Core MVC Application

Any assistance would be greatly appreciated.

Man thanks

答:
You will need to create your credentials for your application here: https://console.developers.google.com/apis. This will give you a client ID and client secret (Note - please make sure https://developers.google.com/oauthplayground as an authorized redirect uri). Then go to https://developers.google.com/oauthplayground to create authorization tokens. The access token you are given should be sent to the Google API through the header and value: "Authorization" : "Bearer {{AccessToken}}". If your token expires, you can retrieve a new one by hitting the OAUTH api (https://www.googleapis.com/oauth2/v4/token), sending refresh_token, client_id, client_secret, grant_type and access_type in the query and 'user-agent': 'google-oauth-playground' in the header.

If you get stuck, implement the google API the way they describe here in their quick start guides: https://developers.google.com/analytics/devguides/reporting/core/v4/ . You can then use developer tools to see exactly what values are being sent where.

Hope this helps. :)


问:
How to start mapping a nested json from a certain index and map it back to that index-1 value

I want to map my nested json from a certain index

For example if my json is the following:

```<code>{"data":[{id:1,name:"NAV"},{id:2,name:"Rick"},{id:3,name:"Ceil"}]}
</code>```

I want to start mapping this json from 1st index i.e. id =1 name :rick
and map it till nav so the mapping is in the following order:

{id:2,name:"Rick"}

{id:3,name:"Ceil"}

{id:1,name:"NAV"}

Something like a circular array or queue
I have no idea how to implement this mapping in react native or js.

How I am currently mapping my json

```<code>renderArtciles=()=>{

  return this.state.dataSource.map((item,i)=>{
    <Animated.View key={item._id} >
      <View style={styles.Imagebody}>
        <Image source={{ uri:item.img.data }} style{styles.image}/>
      </View>

      <View  style={styles.inner}>
        <ShareItem id={item._id} />
        <View style={styles.inner}>
          <Text style={styles.titleArrtibute}>Trending</Text>
          <Text style={styles.titleText} >{item.title}</Text>
          <View>
            <Text style={styles.body}>{item.body}</Text>
          </View>
        </View>
      </View >
    </Animated.View>
  });
}
</code>```

答:
You can do it with just the map function if you find the starting index first.

Note: This solution does not modify the array.

const { dataSource } = this.state

// set startingIndex using whatever method you have
// to find the index of the first item
const startingIndex = (dataSource.findIndex(item => item.name === 'NAV') + 1) % dataSource.length

// underscore to ignore the current item,
// since we'll index to a different item instead
return dataSource.map((_, index) => {
  const shiftedIndex = (startingIndex + index) % dataSource.length
  const item = dataSource[shiftedIndex]
  return {/* render code */}
})
```

Body:
I want to map my nested json from a certain index

For example if my json is the following:

{"data":[{id:1,name:"NAV"},{id:2,name:"Rick"},{id:3,name:"Ceil"}]}

I want to start mapping this json from 1st index i.e. id =1 name :rick
and map it till nav so the mapping is in the following order:

{id:2,name:"Rick"}

{id:3,name:"Ceil"}

{id:1,name:"NAV"}

Something like a circular array or queue
I have no idea how to implement this mapping in react native or js.

How I am currently mapping my json

renderArtciles=()=>{

  return this.state.dataSource.map((item,i)=>{
    <Animated.View key={item._id} >
      <View style={styles.Imagebody}>
        <Image source={{ uri:item.img.data }} style{styles.image}/>
      </View>

      <View  style={styles.inner}>
        <ShareItem id={item._id} />
        <View style={styles.inner}>
          <Text style={styles.titleArrtibute}>Trending</Text>
          <Text style={styles.titleText} >{item.title}</Text>
          <View>
            <Text style={styles.body}>{item.body}</Text>
          </View>
        </View>
      </View >
    </Animated.View>
  });
}


问:
R: Error Message of cast "unimplemented type 'list' in 'listgreater"
Using the following commands (x is a table with 3 columns A, B and C)

```<code>library(reshape)
cast(x, A~B)
</code>```

Following error appears:

```<code>Using C as value column.  Use the value argument to cast to override this choice
Error in order(A = list("xxx",  :
  unimplemented type 'list' in 'listgreater'
</code>```

What does it means and how to solve it?

I guess it maybe due to the dataframe's data format (correct me if I am wrong).  As i did a test of the format of the table x and y with str command.

```<code>str(x) returns
$ A: List of 6
..$ : chr "xxx"
....
$ B:chr "yyy" "yy2" ....
...
$ C: List of 6
..$ : num 22.....
...
</code>```

For another table y with column D E and F,  no error message appears when I run the cast command.

```<code>str(y) shows that all D E F columns are Factor w/ 6 levels....
</code>```

How can I make cast work for list and num containing dataframe x?

答:
I think the first data.frame is not a data.frame but a list. Transforming to a data.frame will solve the problem. Use:

```<code>x <- as.data.frame(x)
library(reshape)
cast(x, A~B)
</code>```

HTH

Body:
Using the following commands (x is a table with 3 columns A, B and C)

library(reshape)
cast(x, A~B)

Following error appears:

Using C as value column.  Use the value argument to cast to override this choice
Error in order(A = list("xxx",  :
  unimplemented type 'list' in 'listgreater'

What does it means and how to solve it?

I guess it maybe due to the dataframe's data format (correct me if I am wrong).  As i did a test of the format of the table x and y with str command.

str(x) returns
$ A: List of 6
..$ : chr "xxx"
....
$ B:chr "yyy" "yy2" ....
...
$ C: List of 6
..$ : num 22.....
...

For another table y with column D E and F,  no error message appears when I run the cast command.

str(y) shows that all D E F columns are Factor w/ 6 levels....

How can I make cast work for list and num containing dataframe x?

Body:
I think the first data.frame is not a data.frame but a list. Transforming to a data.frame will solve the problem. Use:

x <- as.data.frame(x)
library(reshape)
cast(x, A~B)

HTH


问:
How to access an array elements child, while looping?
I have divided my home page into 4 divs with the class of ".div-pics". And my goal is everytime you hover on one of them a description appears /with the class of ".div-desc". The animation happens through Greensock TimelineLite and the initial position of the description divs is "top: 100%".

The code I currently have works, but not with the desired effect. Right now once you hover any of the divs (.div-pics), all description divs (.div-desc) will appear.
Instead I would like only the hovered div's description to come on screen, but I don't know how to target it.

function loopDivs() {
  divArray.forEach(div => {
    div.addEventListener("mouseover", showDetails);

    function showDetails() {
      tlDetails = new TimelineLite();

      tlDetails
        .to(".div-desc", 0.5, {
          top: "0%"
        });
    }
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="home-about" class="div-pics div-left">
  <h1 class="div-title">About</h1>
  <div class="div-desc dl">
    <div class="div-arrow">
      <div class="arrow-part arrow-top"></div>
      <div class="arrow-part arrow-bottom"></div>
    </div>
    <p class="div-text dt-left">
      Lorem ipsum ...
    </p>
    <li class="div-link">Order parts</li>
  </div>
</div></code>```

Any help will be highly appreciated (:

答:
It looks like tlsDetails.to(".div-desc", 0.5, {top: "0%"}); might being using querySelectorAll when you pass ".div-desc"

I would suggest passing the mouseevent from the dom.

```<code>function showDetails(event) {
  tlsDetails = new TimelineLite();

  tlsDetails.to(event.target, 0.5, {
    top: "0%"
  });
}
</code>```

looking at the GreenSock docs I found that you can pas the target element as the first parameter. This should give you a proper target vs ALL of the .div-desc classes that it could find.

Body:
I have divided my home page into 4 divs with the class of ".div-pics". And my goal is everytime you hover on one of them a description appears /with the class of ".div-desc". The animation happens through Greensock TimelineLite and the initial position of the description divs is "top: 100%".

The code I currently have works, but not with the desired effect. Right now once you hover any of the divs (.div-pics), all description divs (.div-desc) will appear.
Instead I would like only the hovered div's description to come on screen, but I don't know how to target it.

function loopDivs() {
  divArray.forEach(div => {
    div.addEventListener("mouseover", showDetails);

    function showDetails() {
      tlDetails = new TimelineLite();

      tlDetails
        .to(".div-desc", 0.5, {
          top: "0%"
        });
    }
  });
}

About

      Lorem ipsum ...

Order parts

Any help will be highly appreciated (:

Body:
It looks like tlsDetails.to(".div-desc", 0.5, {top: "0%"}); might being using querySelectorAll when you pass ".div-desc"

I would suggest passing the mouseevent from the dom.

function showDetails(event) {
  tlsDetails = new TimelineLite();

  tlsDetails.to(event.target, 0.5, {
    top: "0%"
  });
}

looking at the GreenSock docs I found that you can pas the target element as the first parameter. This should give you a proper target vs ALL of the .div-desc classes that it could find.


答:
To me it looks like the issue might have to be with how your CCR data is formatted/organized.

Running a similar sort of loop using a random string and then converting that to a list (and then looping through that data using the same loop you have) worked fine for me.

```<code>s = 'Some random string or line with 13.2 in it'
>>> s = s.split(' ')
>>> s
['Some', 'random', 'string', 'or', 'line', 'with', '13.2', 'in', 'it']
>>> x = 0
>>> for line in s:
    x+=1
    print(x)
    if key in line:
        print('Found')
    else:
        print('Not Found')

1
Not Found
2
Not Found
3
Not Found
4
Not Found
5
Not Found
6
Not Found
7
Found
8
Not Found
9
Not Found

</code>```

Maybe you could try splitting your data into a list by a newline character (\n) and then iterate through that to find the data containing the key you're looking for.

Title: Text saved on a variable showing null values when i try to find a specific line

Body:
To me it looks like the issue might have to be with how your CCR data is formatted/organized.

Running a similar sort of loop using a random string and then converting that to a list (and then looping through that data using the same loop you have) worked fine for me.

s = 'Some random string or line with 13.2 in it'
>>> s = s.split(' ')
>>> s
['Some', 'random', 'string', 'or', 'line', 'with', '13.2', 'in', 'it']
>>> x = 0
>>> for line in s:
    x+=1
    print(x)
    if key in line:
        print('Found')
    else:
        print('Not Found')

1
Not Found
2
Not Found
3
Not Found
4
Not Found
5
Not Found
6
Not Found
7
Found
8
Not Found
9
Not Found

Maybe you could try splitting your data into a list by a newline character (\n) and then iterate through that to find the data containing the key you're looking for.


问:
What is this "tool" and how to disable it?
I'm currently developing a program and I have this that shows up at the top of the window. I don't know what it is or how to remove it. I only have it in this specific program so I guess it's related to something I have done.

答: This is the XAML version of the HTML element inspector. By clicking the first button will bring you to the live visual tree window. Over there you can choose to toggle it on or off by clicking the "show runtime tool in application" button (first one on top menu bar)</p>


答:
Input results to a string format so convert the string into float Then check if it is an integer. Change your code into:

```<code>old: if float(c) ==int(c):

new: if c.isdigit():
</code>```

UPDATED:

```<code>enter a string: 21.0
Sorry floats don't have length
</code>```

Title: Unexpected exception being raised when trying to convert an input string to float

Body:
Input results to a string format so convert the string into float Then check if it is an integer. Change your code into:

old: if float(c) ==int(c):

new: if c.isdigit():

UPDATED:

enter a string: 21.0
Sorry floats don't have length


问:
How to check weather login is required or not on given url(website) to proceed
how to check logging is required in a website or not.

suppose i have given url in python code as:'www.amazon.com'
expected result as:'NO login is not required to proceed'.

and url='www.Facebook.com
expected result as :'Yes login is required to proceed'

答:
It will likely be very difficult to consistently detect whether or not you must be logged in to visit a page. There is no standard for determining this. There's a few approaches you can try:

HTTP status

When visiting an unauthorized page, it's possible that the web server will respond with an HTTP 401 or 403 status, telling the browser that it is unauthorized to view the content. You can check for these responses and act accordingly, though it's not guaranteed or even likely that a webpage will return this response.

Page analysis

You could scan the source of a page for HTML input boxes that are indicative of a login page. This will not work for every page, as some websites have a login form on every page when you're not logged in.

URL analysis

You could use a model to determine whether or not the URL you followed leads to a login page. For example, if you are redirected to https://example.com/login when trying to access a resource, it's a good indication that you must be logged in before doing so.


问:
Managing order of HTML elements when adding them using innerHTML
I'm generating a form using document.getElementById.innerHTML and the form is supposed to have a submit button at last. But the form has variable number of fields which are added by clicking on a button, the problem is when a field is added it is inserted below the save button.

```<code><button class="fontButton" onClick="addField()">+</button>
<form id="tasksDataForm"></form>

<script>
var f = document.getElementById("tasksDataForm");
function addField() {

            var tasksDataFields = `<br/> <input type="text"> <br/>`;
<!-- I have to put this button to end of the form and all fields that are added to form should be inserted above it -->
if(tasks.innerHTML == ''){
            tasks.innerHTML += '<input type="submit" value="Save">';
        }

        tasks.innerHTML += tasksDataFields;
    }

</script>
</code>```

答:
Thanks to Randy Casburn for the suggestion, it did the trick.</p>

```<code><button class="fontButton" onClick="addField()">+</button>
<form id="tasksDataForm">
  <div id="fieldsDiv"></div>
  <div id="submitDiv"></div>
</form>

<script>
var tasks = document.getElementById("fieldsDiv");
function addField() {

            var tasksDataFields = `<br/> <input type="text"> <br/>`;

            var submitDiv = document.getElementById("submitDiv");

            if(submitDiv.innerHTML == '')
               submitDiv.innerHTML += '<input type="submit" value="Save">';

            tasks.innerHTML += tasksDataFields;
        }

</script>
</code>```

Body:
I'm generating a form using document.getElementById.innerHTML and the form is supposed to have a submit button at last. But the form has variable number of fields which are added by clicking on a button, the problem is when a field is added it is inserted below the save button.

<button class="fontButton" onClick="addField()">+</button>
<form id="tasksDataForm"></form>

Body:
Thanks to Randy Casburn for the suggestion, it did the trick.

<button class="fontButton" onClick="addField()">&plus;</button>
<form id="tasksDataForm">
  <div id="fieldsDiv"></div>
  <div id="submitDiv"></div>
</form>

<script>
var tasks = document.getElementById("fieldsDiv");
function addField() {

            var tasksDataFields = `<br/> <input type="text"> <br/>`;

            var submitDiv = document.getElementById("submitDiv");

            if(submitDiv.innerHTML == '')
               submitDiv.innerHTML += '<input type="submit" value="Save">';

            tasks.innerHTML += tasksDataFields;
        }

</script>


问:
Verilog: How to deal with if conditions of wires?
Question follows over from here: Why is wire variable causing illegal left-hand side in continuous assignment?

Below is my adjusted code, but I'm still having the problem of reconciling b (which is a reg) and Y (which is a wire) under the same if conditions. I get that a wire has to be viewed as a result of the combinations its attached to, and can't just be assigned a value, and certainly not as a function of itself. And all the stuff about not being allowed to use assign to regs or that wires can't be used in if blocks.

But the problem is once b is calculated, and if b!=0, how do I correct the bth bit error (Y[b]) and getting it to flip from 1 to 0 or vice versa?

```<code>// Hamming code 1-bit error correction
module HCG(I,e,O);
  input [4:1] I;   // input BCD
  input [7:1] e;   // noise simulation
  wire [7:1] X;    // Hamming code
  wire [7:1] Y;     // Hamming code after addition of noise
  wire [3:1] P;     // Parity at start
  wire [3:1] S;    // Parity at end
  integer b;       // the error bit
  output [4:1] O;  // corrected output

  assign X[1]=I[1]^I[2]^I[4];   // Hamming code generator
  assign X[2]=I[1]^I[3]^I[4];
  assign X[3]=I[1];
  assign X[4]=I[2]^I[3]^I[4];
  assign X[5]=I[2];
  assign X[6]=I[3];
  assign X[7]=I[4];

  assign P[1]=X[1]; // Parity at start
  assign P[2]=X[2];
  assign P[3]=X[4];

  assign Y[1]=e[1]^X[1]; // noise added
  assign Y[2]=e[2]^X[2];
  assign Y[3]=e[3]^X[3];
  assign Y[4]=e[4]^X[4];
  assign Y[5]=e[5]^X[5];
  assign Y[6]=e[6]^X[6];
  assign Y[7]=e[7]^X[7];

  assign S[1]=Y[3]^Y[5]^Y[7]; // Parity at end
  assign S[2]=Y[3]^Y[6]^Y[7];
  assign S[3]=Y[5]^Y[6]^Y[7];

  always @(I,e)
  begin
    b=0; // initialize b to zero
  if(S[1]!=P[1])
    b=b+1;
  if(S[2]!=P[2]) // b is cumulative if each of the conditions is true
    b=b+2;
  if(S[3]!=P[3])
    b=b+4;
  if(b!=0)
    begin
    Y[b]=!(Y[b]); // HOW TO CORRECT THIS?
    end
  end

  assign O[1]=Y[3]; // assigning outputs
  assign O[2]=Y[5];
  assign O[3]=Y[6];
  assign O[4]=Y[7];

endmodule
</code>```

答:
So my problem was that I was trying to change Y when it really couldn't be changed (unless the inputs or wires that defined it changed). I fixed the problem by making a new variable reg z to take on the values of Y and then have Z's bth-bit be flipped instead.

```<code>module HCG(I,e,O);
  input [4:1] I;   // input BCD
  input [7:1] e;   // noise simulation
  wire [7:1] X;    // Hamming code
  wire [7:1] Y;     // Hamming code after addition of noise
  wire [3:1] P;     // Parity at start
  wire [3:1] S;    // Parity at end
  integer b;       // the error bit
  reg [7:1] Z;     // corrected hamming code
  output [4:1] O;  // corrected output

  assign X[1]=I[1]^I[2]^I[4];   // Hamming code generator
  assign X[2]=I[1]^I[3]^I[4];
  assign X[3]=I[1];
  assign X[4]=I[2]^I[3]^I[4];
  assign X[5]=I[2];
  assign X[6]=I[3];
  assign X[7]=I[4];

  assign P[1]=X[1]; // Parity at start
  assign P[2]=X[2];
  assign P[3]=X[4];

  assign Y[1]=e[1]^X[1]; // noise added
  assign Y[2]=e[2]^X[2];
  assign Y[3]=e[3]^X[3];
  assign Y[4]=e[4]^X[4];
  assign Y[5]=e[5]^X[5];
  assign Y[6]=e[6]^X[6];
  assign Y[7]=e[7]^X[7];

  assign S[1]=Y[3]^Y[5]^Y[7]; // Parity at end
  assign S[2]=Y[3]^Y[6]^Y[7];
  assign S[3]=Y[5]^Y[6]^Y[7];

  always @( *)
  begin
    b=0; // initialize b to zero
    Z=Y; // initialize Z1~Z7 with Y1~Y1
  if(S[1]!=P[1])
    b=b+1;
  if(S[2]!=P[2]) // b is cumulative if each of the conditions is true
    b=b+2;
  if(S[3]!=P[3])
    b=b+4;
  if(b!=0)
    Z[b]=~(Y[b]); // correct the incorrect b'th-bit
  end

  assign O[1]=Z[3]; // assigning outputs
  assign O[2]=Z[5];
  assign O[3]=Z[6];
  assign O[4]=Z[7];

endmodule
</code>```

Body:
Question follows over from here: Why is wire variable causing illegal left-hand side in continuous assignment?

Below is my adjusted code, but I'm still having the problem of reconciling b (which is a reg) and Y (which is a wire) under the same if conditions. I get that a wire has to be viewed as a result of the combinations its attached to, and can't just be assigned a value, and certainly not as a function of itself. And all the stuff about not being allowed to use assign to regs or that wires can't be used in if blocks.

But the problem is once b is calculated, and if b!=0, how do I correct the bth bit error (Y[b]) and getting it to flip from 1 to 0 or vice versa?

// Hamming code 1-bit error correction
module HCG(I,e,O);
  input [4:1] I;   // input BCD
  input [7:1] e;   // noise simulation
  wire [7:1] X;    // Hamming code
  wire [7:1] Y;     // Hamming code after addition of noise
  wire [3:1] P;     // Parity at start
  wire [3:1] S;    // Parity at end
  integer b;       // the error bit
  output [4:1] O;  // corrected output

  assign X[1]=I[1]^I[2]^I[4];   // Hamming code generator
  assign X[2]=I[1]^I[3]^I[4];
  assign X[3]=I[1];
  assign X[4]=I[2]^I[3]^I[4];
  assign X[5]=I[2];
  assign X[6]=I[3];
  assign X[7]=I[4];

  assign P[1]=X[1]; // Parity at start
  assign P[2]=X[2];
  assign P[3]=X[4];

  assign Y[1]=e[1]^X[1]; // noise added
  assign Y[2]=e[2]^X[2];
  assign Y[3]=e[3]^X[3];
  assign Y[4]=e[4]^X[4];
  assign Y[5]=e[5]^X[5];
  assign Y[6]=e[6]^X[6];
  assign Y[7]=e[7]^X[7];

  assign S[1]=Y[3]^Y[5]^Y[7]; // Parity at end
  assign S[2]=Y[3]^Y[6]^Y[7];
  assign S[3]=Y[5]^Y[6]^Y[7];

  always @(I,e)
  begin
    b=0; // initialize b to zero
  if(S[1]!=P[1])
    b=b+1;
  if(S[2]!=P[2]) // b is cumulative if each of the conditions is true
    b=b+2;
  if(S[3]!=P[3])
    b=b+4;
  if(b!=0)
    begin
    Y[b]=!(Y[b]); // HOW TO CORRECT THIS?
    end
  end

  assign O[1]=Y[3]; // assigning outputs
  assign O[2]=Y[5];
  assign O[3]=Y[6];
  assign O[4]=Y[7];

endmodule

Body:
So my problem was that I was trying to change Y when it really couldn't be changed (unless the inputs or wires that defined it changed). I fixed the problem by making a new variable reg z to take on the values of Y and then have Z's bth-bit be flipped instead.

module HCG(I,e,O);
  input [4:1] I;   // input BCD
  input [7:1] e;   // noise simulation
  wire [7:1] X;    // Hamming code
  wire [7:1] Y;     // Hamming code after addition of noise
  wire [3:1] P;     // Parity at start
  wire [3:1] S;    // Parity at end
  integer b;       // the error bit
  reg [7:1] Z;     // corrected hamming code
  output [4:1] O;  // corrected output

  assign X[1]=I[1]^I[2]^I[4];   // Hamming code generator
  assign X[2]=I[1]^I[3]^I[4];
  assign X[3]=I[1];
  assign X[4]=I[2]^I[3]^I[4];
  assign X[5]=I[2];
  assign X[6]=I[3];
  assign X[7]=I[4];

  assign P[1]=X[1]; // Parity at start
  assign P[2]=X[2];
  assign P[3]=X[4];

  assign Y[1]=e[1]^X[1]; // noise added
  assign Y[2]=e[2]^X[2];
  assign Y[3]=e[3]^X[3];
  assign Y[4]=e[4]^X[4];
  assign Y[5]=e[5]^X[5];
  assign Y[6]=e[6]^X[6];
  assign Y[7]=e[7]^X[7];

  assign S[1]=Y[3]^Y[5]^Y[7]; // Parity at end
  assign S[2]=Y[3]^Y[6]^Y[7];
  assign S[3]=Y[5]^Y[6]^Y[7];

  always @( *)
  begin
    b=0; // initialize b to zero
    Z=Y; // initialize Z1~Z7 with Y1~Y1
  if(S[1]!=P[1])
    b=b+1;
  if(S[2]!=P[2]) // b is cumulative if each of the conditions is true
    b=b+2;
  if(S[3]!=P[3])
    b=b+4;
  if(b!=0)
    Z[b]=~(Y[b]); // correct the incorrect b'th-bit
  end

  assign O[1]=Z[3]; // assigning outputs
  assign O[2]=Z[5];
  assign O[3]=Z[6];
  assign O[4]=Z[7];

endmodule